diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile
index 4fc7a5b73..c7ccbf9fa 100644
--- a/.devcontainer/Dockerfile
+++ b/.devcontainer/Dockerfile
@@ -9,12 +9,21 @@ ARG INSTALL_NODE="true"
ARG NODE_VERSION="lts/*"
RUN if [ "${INSTALL_NODE}" = "true" ]; then su vscode -c "source /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
-# [Optional] Uncomment this section to install additional OS packages.
+# Install additional OS packages
RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
- && apt-get -y install --no-install-recommends libtag1-dev ffmpeg
+ && apt-get -y install --no-install-recommends ffmpeg
-# [Optional] Uncomment the next line to use go get to install anything else you need
-# RUN go get -x
+# Install TagLib from cross-taglib releases
+ARG CROSS_TAGLIB_VERSION="2.2.0-1"
+ARG TARGETARCH
+RUN DOWNLOAD_ARCH="linux-${TARGETARCH}" \
+ && wget -q "https://github.com/navidrome/cross-taglib/releases/download/v${CROSS_TAGLIB_VERSION}/taglib-${DOWNLOAD_ARCH}.tar.gz" -O /tmp/cross-taglib.tar.gz \
+ && tar -xzf /tmp/cross-taglib.tar.gz -C /usr --strip-components=1 \
+ && mv /usr/include/taglib/* /usr/include/ \
+ && rmdir /usr/include/taglib \
+ && rm /tmp/cross-taglib.tar.gz /usr/provenance.json
+
+ENV CGO_CFLAGS_ALLOW="--define-prefix"
# [Optional] Uncomment this line to install global node packages.
# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
index f339f62f7..81398a3ce 100644
--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -4,10 +4,11 @@
"dockerfile": "Dockerfile",
"args": {
// Update the VARIANT arg to pick a version of Go: 1, 1.15, 1.14
- "VARIANT": "1.24",
+ "VARIANT": "1.25",
// Options
"INSTALL_NODE": "true",
- "NODE_VERSION": "v20"
+ "NODE_VERSION": "v24",
+ "CROSS_TAGLIB_VERSION": "2.2.0-1"
}
},
"workspaceMount": "",
@@ -54,12 +55,10 @@
4533,
4633
],
- // Use 'postCreateCommand' to run commands after the container is created.
- // "postCreateCommand": "make setup-dev",
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode",
"remoteEnv": {
"ND_MUSICFOLDER": "./music",
"ND_DATAFOLDER": "./data"
}
-}
+}
\ No newline at end of file
diff --git a/.dockerignore b/.dockerignore
index 596aa2955..eb012c6e2 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -15,4 +15,5 @@ dist
binaries
cache
music
+music.old
!Dockerfile
\ No newline at end of file
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index 9488f20f7..2529aaf36 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -14,7 +14,8 @@ concurrency:
cancel-in-progress: true
env:
- CROSS_TAGLIB_VERSION: "2.1.1-1"
+ CROSS_TAGLIB_VERSION: "2.2.0-1"
+ CGO_CFLAGS_ALLOW: "--define-prefix"
IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') && 'true' || 'false' }}
jobs:
@@ -25,7 +26,7 @@ jobs:
git_tag: ${{ steps.git-version.outputs.GIT_TAG }}
git_sha: ${{ steps.git-version.outputs.GIT_SHA }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
with:
fetch-depth: 0
fetch-tags: true
@@ -63,7 +64,7 @@ jobs:
name: Lint Go code
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Download TagLib
uses: ./.github/actions/download-taglib
@@ -71,7 +72,7 @@ jobs:
version: ${{ env.CROSS_TAGLIB_VERSION }}
- name: golangci-lint
- uses: golangci/golangci-lint-action@v8
+ uses: golangci/golangci-lint-action@v9
with:
version: latest
problem-matchers: true
@@ -88,12 +89,22 @@ jobs:
exit 1
fi
+ - name: Run go generate
+ run: go generate ./...
+ - name: Verify no changes from go generate
+ run: |
+ git status --porcelain
+ if [ -n "$(git status --porcelain)" ]; then
+ echo 'Generated code is out of date. Run "make gen" and commit the changes'
+ exit 1
+ fi
+
go:
name: Test Go code
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
- uses: actions/checkout@v4
+ uses: actions/checkout@v6
- name: Download TagLib
uses: ./.github/actions/download-taglib
@@ -106,7 +117,14 @@ jobs:
- name: Test
run: |
pkg-config --define-prefix --cflags --libs taglib # for debugging
- go test -shuffle=on -tags netgo -race -cover ./... -v
+ go test -shuffle=on -tags netgo,sqlite_fts5 -race ./... -v
+
+ - name: Test ndpgen
+ run: |
+ cd plugins/cmd/ndpgen
+ go test -shuffle=on -v
+ go build -o ndpgen .
+ ./ndpgen --help
js:
name: Test JS code
@@ -114,10 +132,10 @@ jobs:
env:
NODE_OPTIONS: "--max_old_space_size=4096"
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@v6
+ - uses: actions/setup-node@v6
with:
- node-version: 20
+ node-version: 24
cache: "npm"
cache-dependency-path: "**/package-lock.json"
@@ -145,7 +163,7 @@ jobs:
name: Lint i18n files
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- run: |
set -e
for file in resources/i18n/*.json; do
@@ -175,7 +193,7 @@ jobs:
needs: [js, go, go-lint, i18n-lint, git-version, check-push-enabled]
strategy:
matrix:
- platform: [ linux/amd64, linux/arm64, linux/arm/v5, linux/arm/v6, linux/arm/v7, linux/386, darwin/amd64, darwin/arm64, windows/amd64, windows/386 ]
+ platform: [ linux/amd64, linux/arm64, linux/arm/v5, linux/arm/v6, linux/arm/v7, linux/386, linux/riscv64, darwin/amd64, darwin/arm64, windows/amd64, windows/386 ]
runs-on: ubuntu-latest
env:
IS_LINUX: ${{ startsWith(matrix.platform, 'linux/') && 'true' || 'false' }}
@@ -191,7 +209,7 @@ jobs:
PLATFORM=$(echo ${{ matrix.platform }} | tr '/' '_')
echo "PLATFORM=$PLATFORM" >> $GITHUB_ENV
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Prepare Docker Buildx
uses: ./.github/actions/prepare-docker
@@ -203,7 +221,7 @@ jobs:
hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }}
- name: Build Binaries
- uses: docker/build-push-action@v6
+ uses: docker/build-push-action@v7
with:
context: .
file: Dockerfile
@@ -217,7 +235,7 @@ jobs:
CROSS_TAGLIB_VERSION=${{ env.CROSS_TAGLIB_VERSION }}
- name: Upload Binaries
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: navidrome-${{ env.PLATFORM }}
path: ./output
@@ -226,7 +244,7 @@ jobs:
- name: Build and push image by digest
id: push-image
if: env.IS_LINUX == 'true' && env.IS_DOCKER_PUSH_CONFIGURED == 'true' && env.IS_ARMV5 == 'false'
- uses: docker/build-push-action@v6
+ uses: docker/build-push-action@v7
with:
context: .
file: Dockerfile
@@ -248,7 +266,7 @@ jobs:
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
if: env.IS_LINUX == 'true' && env.IS_DOCKER_PUSH_CONFIGURED == 'true' && env.IS_ARMV5 == 'false'
with:
name: digests-${{ env.PLATFORM }}
@@ -256,18 +274,55 @@ jobs:
if-no-files-found: error
retention-days: 1
- push-manifest:
- name: Push Docker manifest
+ push-manifest-ghcr:
+ name: Push to GHCR
+ permissions:
+ contents: read
+ packages: write
runs-on: ubuntu-latest
needs: [build, check-push-enabled]
if: needs.check-push-enabled.outputs.is_enabled == 'true'
env:
REGISTRY_IMAGE: ghcr.io/${{ github.repository }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Download digests
- uses: actions/download-artifact@v4
+ uses: actions/download-artifact@v8
+ with:
+ path: /tmp/digests
+ pattern: digests-*
+ merge-multiple: true
+
+ - name: Prepare Docker Buildx
+ uses: ./.github/actions/prepare-docker
+ id: docker
+ with:
+ github_token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Create manifest list and push to ghcr.io
+ working-directory: /tmp/digests
+ run: |
+ docker buildx imagetools create $(jq -cr '.tags | map(select(startswith("ghcr.io"))) | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
+ $(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)
+
+ - name: Inspect image in ghcr.io
+ run: |
+ docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.docker.outputs.version }}
+
+ push-manifest-dockerhub:
+ name: Push to Docker Hub
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ needs: [build, check-push-enabled]
+ if: needs.check-push-enabled.outputs.is_enabled == 'true' && vars.DOCKER_HUB_REPO != ''
+ continue-on-error: true
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Download digests
+ uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
@@ -282,28 +337,27 @@ jobs:
hub_username: ${{ secrets.DOCKER_HUB_USERNAME }}
hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }}
- - name: Create manifest list and push to ghcr.io
- working-directory: /tmp/digests
- run: |
- docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
- $(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)
-
- name: Create manifest list and push to Docker Hub
- working-directory: /tmp/digests
- if: vars.DOCKER_HUB_REPO != ''
- run: |
- docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
- $(printf '${{ vars.DOCKER_HUB_REPO }}@sha256:%s ' *)
-
- - name: Inspect image in ghcr.io
- run: |
- docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.docker.outputs.version }}
+ uses: nick-fields/retry@v4
+ with:
+ timeout_minutes: 5
+ max_attempts: 3
+ retry_wait_seconds: 30
+ command: |
+ cd /tmp/digests
+ docker buildx imagetools create $(jq -cr '.tags | map(select(startswith("ghcr.io") | not)) | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
+ $(printf 'ghcr.io/${{ github.repository }}@sha256:%s ' *)
- name: Inspect image in Docker Hub
- if: vars.DOCKER_HUB_REPO != ''
run: |
docker buildx imagetools inspect ${{ vars.DOCKER_HUB_REPO }}:${{ steps.docker.outputs.version }}
+ cleanup-digests:
+ name: Cleanup digest artifacts
+ runs-on: ubuntu-latest
+ needs: [push-manifest-ghcr, push-manifest-dockerhub]
+ if: always() && needs.push-manifest-ghcr.result == 'success'
+ steps:
- name: Delete unnecessary digest artifacts
env:
GH_TOKEN: ${{ github.token }}
@@ -318,9 +372,9 @@ jobs:
runs-on: ubuntu-24.04
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- - uses: actions/download-artifact@v4
+ - uses: actions/download-artifact@v8
with:
path: ./binaries
pattern: navidrome-windows*
@@ -339,7 +393,7 @@ jobs:
du -h binaries/msi/*.msi
- name: Upload MSI files
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: navidrome-windows-installers
path: binaries/msi/*.msi
@@ -352,12 +406,12 @@ jobs:
outputs:
package_list: ${{ steps.set-package-list.outputs.package_list }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
with:
fetch-depth: 0
fetch-tags: true
- - uses: actions/download-artifact@v4
+ - uses: actions/download-artifact@v8
with:
path: ./binaries
pattern: navidrome-*
@@ -370,7 +424,7 @@ jobs:
run: echo 'RELEASE_FLAGS=--skip=publish --snapshot' >> $GITHUB_ENV
- name: Run GoReleaser
- uses: goreleaser/goreleaser-action@v6
+ uses: goreleaser/goreleaser-action@v7
with:
version: '~> v2'
args: "release --clean -f release/goreleaser.yml ${{ env.RELEASE_FLAGS }}"
@@ -383,7 +437,7 @@ jobs:
rm ./dist/*.tar.gz ./dist/*.zip
- name: Upload all-packages artifact
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: packages
path: dist/navidrome_0*
@@ -406,13 +460,13 @@ jobs:
item: ${{ fromJson(needs.release.outputs.package_list) }}
steps:
- name: Download all-packages artifact
- uses: actions/download-artifact@v4
+ uses: actions/download-artifact@v8
with:
name: packages
path: ./dist
- name: Upload all-packages artifact
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: navidrome_linux_${{ matrix.item }}
path: dist/navidrome_0*_linux_${{ matrix.item }}
diff --git a/.github/workflows/push-translations.sh b/.github/workflows/push-translations.sh
new file mode 100755
index 000000000..be153eea8
--- /dev/null
+++ b/.github/workflows/push-translations.sh
@@ -0,0 +1,138 @@
+#!/bin/sh
+
+set -e
+
+I18N_DIR=resources/i18n
+
+# Normalize JSON for deterministic comparison:
+# remove empty/null attributes, sort keys alphabetically
+process_json() {
+ jq 'walk(if type == "object" then with_entries(select(.value != null and .value != "" and .value != [] and .value != {})) | to_entries | sort_by(.key) | from_entries else . end)' "$1"
+}
+
+# Get list of all languages configured in the POEditor project
+get_language_list() {
+ curl -s -X POST https://api.poeditor.com/v2/languages/list \
+ -d api_token="${POEDITOR_APIKEY}" \
+ -d id="${POEDITOR_PROJECTID}"
+}
+
+# Extract language name from the language list JSON given a language code
+get_language_name() {
+ lang_code="$1"
+ lang_list="$2"
+ echo "$lang_list" | jq -r ".result.languages[] | select(.code == \"$lang_code\") | .name"
+}
+
+# Extract language code from a file path (e.g., "resources/i18n/fr.json" -> "fr")
+get_lang_code() {
+ filepath="$1"
+ filename=$(basename "$filepath")
+ echo "${filename%.*}"
+}
+
+# Export the current translation for a language from POEditor (v2 API)
+export_language() {
+ lang_code="$1"
+ response=$(curl -s -X POST https://api.poeditor.com/v2/projects/export \
+ -d api_token="${POEDITOR_APIKEY}" \
+ -d id="${POEDITOR_PROJECTID}" \
+ -d language="$lang_code" \
+ -d type="key_value_json")
+
+ url=$(echo "$response" | jq -r '.result.url')
+ if [ -z "$url" ] || [ "$url" = "null" ]; then
+ echo "Failed to export $lang_code: $response" >&2
+ return 1
+ fi
+ echo "$url"
+}
+
+# Flatten nested JSON to POEditor languages/update format.
+# POEditor uses term + context pairs, where:
+# term = the leaf key name
+# context = the parent path as "key1"."key2"."key3" (empty for root keys)
+flatten_to_poeditor() {
+ jq -c '[paths(scalars) as $p |
+ {
+ "term": ($p | last | tostring),
+ "context": (if ($p | length) > 1 then ($p[:-1] | map("\"" + tostring + "\"") | join(".")) else "" end),
+ "translation": {"content": getpath($p)}
+ }
+ ]' "$1"
+}
+
+# Update translations for a language in POEditor via languages/update API
+update_language() {
+ lang_code="$1"
+ file="$2"
+
+ flatten_to_poeditor "$file" > /tmp/poeditor_data.json
+ response=$(curl -s -X POST https://api.poeditor.com/v2/languages/update \
+ -d api_token="${POEDITOR_APIKEY}" \
+ -d id="${POEDITOR_PROJECTID}" \
+ -d language="$lang_code" \
+ --data-urlencode data@/tmp/poeditor_data.json)
+ rm -f /tmp/poeditor_data.json
+
+ status=$(echo "$response" | jq -r '.response.status')
+ if [ "$status" != "success" ]; then
+ echo "Failed to update $lang_code: $response" >&2
+ return 1
+ fi
+
+ parsed=$(echo "$response" | jq -r '.result.translations.parsed')
+ added=$(echo "$response" | jq -r '.result.translations.added')
+ updated=$(echo "$response" | jq -r '.result.translations.updated')
+ echo " Translations - parsed: $parsed, added: $added, updated: $updated"
+}
+
+# --- Main ---
+
+if [ $# -eq 0 ]; then
+ echo "Usage: $0 [file2] ..."
+ echo "No files specified. Nothing to do."
+ exit 0
+fi
+
+lang_list=$(get_language_list)
+upload_count=0
+
+for file in "$@"; do
+ if [ ! -f "$file" ]; then
+ echo "Warning: File not found: $file, skipping"
+ continue
+ fi
+
+ lang_code=$(get_lang_code "$file")
+ lang_name=$(get_language_name "$lang_code" "$lang_list")
+
+ if [ -z "$lang_name" ]; then
+ echo "Warning: Language code '$lang_code' not found in POEditor, skipping $file"
+ continue
+ fi
+
+ echo "Processing $lang_name ($lang_code)..."
+
+ # Export current state from POEditor
+ url=$(export_language "$lang_code")
+ curl -sSL "$url" -o poeditor_export.json
+
+ # Normalize both files for comparison
+ process_json "$file" > local_normalized.json
+ process_json poeditor_export.json > remote_normalized.json
+
+ # Compare normalized versions
+ if diff -q local_normalized.json remote_normalized.json > /dev/null 2>&1; then
+ echo " No differences, skipping"
+ else
+ echo " Differences found, updating POEditor..."
+ update_language "$lang_code" "$file"
+ upload_count=$((upload_count + 1))
+ fi
+
+ rm -f poeditor_export.json local_normalized.json remote_normalized.json
+done
+
+echo ""
+echo "Done. Updated $upload_count translation(s) in POEditor."
diff --git a/.github/workflows/push-translations.yml b/.github/workflows/push-translations.yml
new file mode 100644
index 000000000..f7cf00621
--- /dev/null
+++ b/.github/workflows/push-translations.yml
@@ -0,0 +1,32 @@
+name: POEditor export
+
+on:
+ push:
+ branches:
+ - master
+ paths:
+ - 'resources/i18n/*.json'
+
+jobs:
+ push-translations:
+ runs-on: ubuntu-latest
+ if: ${{ github.repository_owner == 'navidrome' }}
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ fetch-depth: 2
+
+ - name: Detect changed translation files
+ id: changed
+ run: |
+ CHANGED_FILES=$(git diff --name-only HEAD~1 HEAD -- 'resources/i18n/*.json' | tr '\n' ' ')
+ echo "files=$CHANGED_FILES" >> $GITHUB_OUTPUT
+ echo "Changed translation files: $CHANGED_FILES"
+
+ - name: Push translations to POEditor
+ if: ${{ steps.changed.outputs.files != '' }}
+ env:
+ POEDITOR_APIKEY: ${{ secrets.POEDITOR_APIKEY }}
+ POEDITOR_PROJECTID: ${{ secrets.POEDITOR_PROJECTID }}
+ run: |
+ .github/workflows/push-translations.sh ${{ steps.changed.outputs.files }}
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index c8bf3ae7f..69e6ac99e 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -12,7 +12,7 @@ jobs:
pull-requests: write
runs-on: ubuntu-latest
steps:
- - uses: dessant/lock-threads@v5
+ - uses: dessant/lock-threads@v6
with:
process-only: 'issues, prs'
issue-inactive-days: 120
diff --git a/.github/workflows/update-translations.yml b/.github/workflows/update-translations.yml
index 70a9de3d8..8fe0b5379 100644
--- a/.github/workflows/update-translations.yml
+++ b/.github/workflows/update-translations.yml
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'navidrome' }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Get updated translations
id: poeditor
env:
@@ -24,7 +24,7 @@ jobs:
git status --porcelain
git diff
- name: Create Pull Request
- uses: peter-evans/create-pull-request@v7
+ uses: peter-evans/create-pull-request@v8
with:
token: ${{ secrets.PAT }}
author: "navidrome-bot "
diff --git a/.gitignore b/.gitignore
index 74d7ee46f..73475a53a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,18 +17,25 @@ master.zip
testDB
cache/*
*.swp
+coverage.out
dist
music
+music.old
*.db*
.gitinfo
docker-compose.yml
!contrib/docker-compose.yml
binaries
navidrome-*
+/ndpgen
AGENTS.md
.github/prompts
.github/instructions
.github/git-commit-instructions.md
*.exe
*.test
-*.wasm
\ No newline at end of file
+*.wasm
+*.ndp
+openspec/
+go.work*
+.worktrees/
\ No newline at end of file
diff --git a/.golangci.yml b/.golangci.yml
index 996dafccb..b6c632dee 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -2,6 +2,7 @@ version: "2"
run:
build-tags:
- netgo
+ - sqlite_fts5
linters:
enable:
- asasalint
@@ -39,6 +40,11 @@ linters:
enable:
- nilness
exclusions:
+ rules:
+ - linters:
+ - gosec
+ path: _test\.go
+ text: "G703"
generated: lax
presets:
- comments
diff --git a/.nvmrc b/.nvmrc
index 9a2a0e219..54c65116f 100644
--- a/.nvmrc
+++ b/.nvmrc
@@ -1 +1 @@
-v20
+v24
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f2631f597..71c13b497 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -38,7 +38,7 @@ Before submitting a pull request, ensure that you go through the following:
### Commit Conventions
Each commit message must adhere to the following format:
```
-(scope): -
+(scope):
[optional body]
```
diff --git a/Dockerfile b/Dockerfile
index ec3b6d938..b32c1df56 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -2,10 +2,10 @@ FROM --platform=$BUILDPLATFORM ghcr.io/crazy-max/osxcross:14.5-debian AS osxcros
########################################################################################################################
### Build xx (original image: tonistiigi/xx)
-FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/alpine:3.19 AS xx-build
+FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/alpine:3.20 AS xx-build
-# v1.5.0
-ENV XX_VERSION=b4e4c451c778822e6742bfc9d9a91d7c7d885c8a
+# v1.9.0
+ENV XX_VERSION=a5592eab7a57895e8d385394ff12241bc65ecd50
RUN apk add -U --no-cache git
RUN git clone https://github.com/tonistiigi/xx && \
@@ -26,12 +26,14 @@ COPY --from=xx-build /out/ /usr/bin/
########################################################################################################################
### Get TagLib
-FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/alpine:3.19 AS taglib-build
+FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/alpine:3.20 AS taglib-build
ARG TARGETPLATFORM
-ARG CROSS_TAGLIB_VERSION=2.1.1-1
+ARG CROSS_TAGLIB_VERSION=2.2.0-1
ENV CROSS_TAGLIB_RELEASES_URL=https://github.com/navidrome/cross-taglib/releases/download/v${CROSS_TAGLIB_VERSION}/
+# wget in busybox can't follow redirects
RUN < /dev/null || (echo "Installing golangci-lint..." && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/HEAD/install.sh | sh -s v2.1.6)
+ @INSTALL=false; \
+ if PATH=$$PATH:./bin which golangci-lint > /dev/null 2>&1; then \
+ CURRENT_VERSION=$$(PATH=$$PATH:./bin golangci-lint version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n1); \
+ REQUIRED_VERSION=$$(echo "$(GOLANGCI_LINT_VERSION)" | sed 's/^v//'); \
+ if [ "$$CURRENT_VERSION" != "$$REQUIRED_VERSION" ]; then \
+ echo "Found golangci-lint $$CURRENT_VERSION, but $$REQUIRED_VERSION is required. Reinstalling..."; \
+ rm -f ./bin/golangci-lint; \
+ INSTALL=true; \
+ fi; \
+ else \
+ INSTALL=true; \
+ fi; \
+ if [ "$$INSTALL" = "true" ]; then \
+ echo "Installing golangci-lint $(GOLANGCI_LINT_VERSION)..."; \
+ curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/HEAD/install.sh | sh -s $(GOLANGCI_LINT_VERSION); \
+ fi
.PHONY: install-golangci-lint
lint: install-golangci-lint ##@Development Lint Go code
- PATH=$$PATH:./bin golangci-lint run -v --timeout 5m
+ PATH=$$PATH:./bin golangci-lint run --timeout 5m
.PHONY: lint
lintall: lint ##@Development Lint Go and JS code
@@ -84,9 +109,18 @@ format: ##@Development Format code
.PHONY: format
wire: check_go_env ##@Development Update Dependency Injection
- go tool wire gen -tags=netgo ./...
+ go tool wire gen -tags="$$(echo '$(GO_BUILD_TAGS)' | tr ',' ' ')" ./...
.PHONY: wire
+gen: check_go_env ##@Development Run go generate for code generation
+ go generate ./...
+ cd plugins/cmd/ndpgen && go run . -host-wrappers -input=../../host -package=host
+ cd plugins/cmd/ndpgen && go run . -input=../../host -output=../../pdk -go -python -rust
+ cd plugins/cmd/ndpgen && go run . -capability-only -input=../../capabilities -output=../../pdk -go -rust
+ cd plugins/cmd/ndpgen && go run . -schemas -input=../../capabilities
+ go mod tidy -C plugins/pdk/go
+.PHONY: gen
+
snapshots: ##@Development Update (GoLang) Snapshot tests
UPDATE_SNAPSHOTS=true go tool ginkgo ./server/subsonic/responses/...
.PHONY: snapshots
@@ -111,14 +145,14 @@ setup-git: ##@Development Setup Git hooks (pre-commit and pre-push)
.PHONY: setup-git
build: check_go_env buildjs ##@Build Build the project
- go build -ldflags="-X github.com/navidrome/navidrome/consts.gitSha=$(GIT_SHA) -X github.com/navidrome/navidrome/consts.gitTag=$(GIT_TAG)" -tags=netgo
+ go build -ldflags="-X github.com/navidrome/navidrome/consts.gitSha=$(GIT_SHA) -X github.com/navidrome/navidrome/consts.gitTag=$(GIT_TAG)" -tags=$(GO_BUILD_TAGS)
.PHONY: build
buildall: deprecated build
.PHONY: buildall
debug-build: check_go_env buildjs ##@Build Build the project (with remote debug on)
- go build -gcflags="all=-N -l" -ldflags="-X github.com/navidrome/navidrome/consts.gitSha=$(GIT_SHA) -X github.com/navidrome/navidrome/consts.gitTag=$(GIT_TAG)" -tags=netgo
+ go build -gcflags="all=-N -l" -ldflags="-X github.com/navidrome/navidrome/consts.gitSha=$(GIT_SHA) -X github.com/navidrome/navidrome/consts.gitTag=$(GIT_TAG)" -tags=$(GO_BUILD_TAGS)
.PHONY: debug-build
buildjs: check_node_env ui/build/index.html ##@Build Build only frontend
@@ -168,8 +202,8 @@ docker-msi: ##@Cross_Compilation Build MSI installer for Windows
@du -h binaries/msi/*.msi
.PHONY: docker-msi
-run-docker: ##@Development Run a Navidrome Docker image. Usage: make run-docker tag=
- @if [ -z "$(tag)" ]; then echo "Usage: make run-docker tag="; exit 1; fi
+docker-run: ##@Development Run a Navidrome Docker image. Usage: make docker-run tag=
+ @if [ -z "$(tag)" ]; then echo "Usage: make docker-run tag="; exit 1; fi
@TAG_DIR="tmp/$$(echo '$(tag)' | tr '/:' '_')"; mkdir -p "$$TAG_DIR"; \
VOLUMES="-v $(PWD)/$$TAG_DIR:/data"; \
if [ -f navidrome.toml ]; then \
@@ -180,7 +214,7 @@ run-docker: ##@Development Run a Navidrome Docker image. Usage: make run-docker
fi; \
fi; \
echo "Running: docker run --rm -p 4533:4533 $$VOLUMES $(tag)"; docker run --rm -p 4533:4533 $$VOLUMES $(tag)
-.PHONY: run-docker
+.PHONY: docker-run
package: docker-build ##@Cross_Compilation Create binaries and packages for ALL supported platforms
@if [ -z `which goreleaser` ]; then echo "Please install goreleaser first: https://goreleaser.com/install/"; exit 1; fi
@@ -199,6 +233,39 @@ get-music: ##@Development Download some free music from Navidrome's demo instanc
.PHONY: get-music
+##########################################
+#### Worktrees
+
+WORKTREES_DIR := .worktrees
+
+wt: check_go_env ##@Worktrees Create and setup a git worktree. Usage: make wt name=feature-name [go=1]
+ @if [ -z "${name}" ]; then echo "Usage: make wt name= [go=1]"; exit 1; fi
+ @mkdir -p $(WORKTREES_DIR)
+ @echo "Creating worktree for branch '${name}'..."
+ @git worktree add $(WORKTREES_DIR)/${name} -b ${name} 2>/dev/null || \
+ git worktree add $(WORKTREES_DIR)/${name} ${name}
+ @if [ -n "${go}" ]; then \
+ ./scripts/setup-worktree.sh $(WORKTREES_DIR)/${name} --go-only; \
+ else \
+ ./scripts/setup-worktree.sh $(WORKTREES_DIR)/${name}; \
+ fi
+ @echo "\nWorktree ready at $(WORKTREES_DIR)/${name}"
+ @echo " cd $(WORKTREES_DIR)/${name}"
+.PHONY: wt
+
+rm-wt: ##@Worktrees Remove a git worktree. Usage: make rm-wt name=feature-name
+ @if [ -z "${name}" ]; then echo "Usage: make rm-wt name="; exit 1; fi
+ @if [ ! -d "$(WORKTREES_DIR)/${name}" ]; then echo "Worktree '${name}' not found in $(WORKTREES_DIR)/"; exit 1; fi
+ @echo "Removing worktree '${name}'..."
+ @git worktree remove --force $(WORKTREES_DIR)/${name}
+ @echo "Worktree '${name}' removed."
+ @echo "Note: branch '${name}' still exists. Delete it with: git branch -D ${name}"
+.PHONY: rm-wt
+
+ls-wt: ##@Worktrees List all active git worktrees
+ @git worktree list
+.PHONY: ls-wt
+
##########################################
#### Miscellaneous
@@ -250,24 +317,6 @@ deprecated:
@echo "WARNING: This target is deprecated and will be removed in future releases. Use 'make build' instead."
.PHONY: deprecated
-# Generate Go code from plugins/api/api.proto
-plugin-gen: check_go_env ##@Development Generate Go code from plugins protobuf files
- go generate ./plugins/...
-.PHONY: plugin-gen
-
-plugin-examples: check_go_env ##@Development Build all example plugins
- $(MAKE) -C plugins/examples clean all
-.PHONY: plugin-examples
-
-plugin-clean: check_go_env ##@Development Clean all plugins
- $(MAKE) -C plugins/examples clean
- $(MAKE) -C plugins/testdata clean
-.PHONY: plugin-clean
-
-plugin-tests: check_go_env ##@Development Build all test plugins
- $(MAKE) -C plugins/testdata clean all
-.PHONY: plugin-tests
-
.DEFAULT_GOAL := help
HELP_FUN = \
diff --git a/adapters/deezer/client.go b/adapters/deezer/client.go
new file mode 100644
index 000000000..31150c673
--- /dev/null
+++ b/adapters/deezer/client.go
@@ -0,0 +1,217 @@
+package deezer
+
+import (
+ bytes "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ "github.com/microcosm-cc/bluemonday"
+ "github.com/navidrome/navidrome/log"
+)
+
+const apiBaseURL = "https://api.deezer.com"
+const authBaseURL = "https://auth.deezer.com"
+
+var (
+ ErrNotFound = errors.New("deezer: not found")
+)
+
+type httpDoer interface {
+ Do(req *http.Request) (*http.Response, error)
+}
+
+type client struct {
+ httpDoer httpDoer
+ jwt jwtToken
+}
+
+func newClient(hc httpDoer) *client {
+ return &client{
+ httpDoer: hc,
+ }
+}
+
+func (c *client) searchArtists(ctx context.Context, name string, limit int) ([]Artist, error) {
+ params := url.Values{}
+ params.Add("q", name)
+ params.Add("order", "RANKING")
+ params.Add("limit", strconv.Itoa(limit))
+ req, err := http.NewRequestWithContext(ctx, "GET", apiBaseURL+"/search/artist", nil)
+ if err != nil {
+ return nil, err
+ }
+ req.URL.RawQuery = params.Encode()
+
+ var results SearchArtistResults
+ err = c.makeRequest(req, &results)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(results.Data) == 0 {
+ return nil, ErrNotFound
+ }
+ return results.Data, nil
+}
+
+func (c *client) makeRequest(req *http.Request, response any) error {
+ log.Trace(req.Context(), fmt.Sprintf("Sending Deezer %s request", req.Method), "url", req.URL)
+ resp, err := c.httpDoer.Do(req)
+ if err != nil {
+ return err
+ }
+
+ defer resp.Body.Close()
+ data, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return err
+ }
+
+ if resp.StatusCode != 200 {
+ return c.parseError(data)
+ }
+
+ return json.Unmarshal(data, response)
+}
+
+func (c *client) parseError(data []byte) error {
+ var deezerError Error
+ err := json.Unmarshal(data, &deezerError)
+ if err != nil {
+ return err
+ }
+ return fmt.Errorf("deezer error(%d): %s", deezerError.Error.Code, deezerError.Error.Message)
+}
+
+func (c *client) getRelatedArtists(ctx context.Context, artistID int) ([]Artist, error) {
+ req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/artist/%d/related", apiBaseURL, artistID), nil)
+ if err != nil {
+ return nil, err
+ }
+
+ var results RelatedArtists
+ err = c.makeRequest(req, &results)
+ if err != nil {
+ return nil, err
+ }
+
+ return results.Data, nil
+}
+
+func (c *client) getTopTracks(ctx context.Context, artistID int, limit int) ([]Track, error) {
+ params := url.Values{}
+ params.Add("limit", strconv.Itoa(limit))
+ req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/artist/%d/top", apiBaseURL, artistID), nil)
+ if err != nil {
+ return nil, err
+ }
+ req.URL.RawQuery = params.Encode()
+
+ var results TopTracks
+ err = c.makeRequest(req, &results)
+ if err != nil {
+ return nil, err
+ }
+
+ return results.Data, nil
+}
+
+const pipeAPIURL = "https://pipe.deezer.com/api"
+
+var strictPolicy = bluemonday.StrictPolicy()
+
+func (c *client) getArtistBio(ctx context.Context, artistID int, lang string) (string, error) {
+ jwt, err := c.getJWT(ctx)
+ if err != nil {
+ return "", fmt.Errorf("deezer: failed to get JWT: %w", err)
+ }
+
+ query := map[string]any{
+ "operationName": "ArtistBio",
+ "variables": map[string]any{
+ "artistId": strconv.Itoa(artistID),
+ },
+ "query": `query ArtistBio($artistId: String!) {
+ artist(artistId: $artistId) {
+ bio {
+ full
+ }
+ }
+ }`,
+ }
+
+ body, err := json.Marshal(query)
+ if err != nil {
+ return "", err
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "POST", pipeAPIURL, bytes.NewReader(body))
+ if err != nil {
+ return "", err
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept-Language", lang)
+ req.Header.Set("Authorization", "Bearer "+jwt)
+
+ log.Trace(ctx, "Fetching Deezer artist biography via GraphQL", "artistId", artistID, "language", lang)
+ resp, err := c.httpDoer.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != 200 {
+ return "", fmt.Errorf("deezer: failed to fetch biography: %s", resp.Status)
+ }
+
+ data, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", err
+ }
+
+ type graphQLResponse struct {
+ Data struct {
+ Artist struct {
+ Bio struct {
+ Full string `json:"full"`
+ } `json:"bio"`
+ } `json:"artist"`
+ } `json:"data"`
+ Errors []struct {
+ Message string `json:"message"`
+ }
+ }
+
+ var result graphQLResponse
+ if err := json.Unmarshal(data, &result); err != nil {
+ return "", fmt.Errorf("deezer: failed to parse GraphQL response: %w", err)
+ }
+
+ if len(result.Errors) > 0 {
+ var errs []error
+ for m := range result.Errors {
+ errs = append(errs, errors.New(result.Errors[m].Message))
+ }
+ err := errors.Join(errs...)
+ return "", fmt.Errorf("deezer: GraphQL error: %w", err)
+ }
+
+ if result.Data.Artist.Bio.Full == "" {
+ return "", errors.New("deezer: biography not found")
+ }
+
+ return cleanBio(result.Data.Artist.Bio.Full), nil
+}
+
+func cleanBio(bio string) string {
+ bio = strings.ReplaceAll(bio, "
", "\n")
+ return strictPolicy.Sanitize(bio)
+}
diff --git a/adapters/deezer/client_auth.go b/adapters/deezer/client_auth.go
new file mode 100644
index 000000000..eb664c00b
--- /dev/null
+++ b/adapters/deezer/client_auth.go
@@ -0,0 +1,101 @@
+package deezer
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/lestrrat-go/jwx/v3/jwt"
+ "github.com/navidrome/navidrome/log"
+)
+
+type jwtToken struct {
+ token string
+ expiresAt time.Time
+ mu sync.RWMutex
+}
+
+func (j *jwtToken) get() (string, bool) {
+ j.mu.RLock()
+ defer j.mu.RUnlock()
+ if time.Now().Before(j.expiresAt) {
+ return j.token, true
+ }
+ return "", false
+}
+
+func (j *jwtToken) set(token string, expiresIn time.Duration) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ j.token = token
+ j.expiresAt = time.Now().Add(expiresIn)
+}
+
+func (c *client) getJWT(ctx context.Context) (string, error) {
+ // Check if we have a valid cached token
+ if token, valid := c.jwt.get(); valid {
+ return token, nil
+ }
+
+ // Fetch a new anonymous token
+ req, err := http.NewRequestWithContext(ctx, "GET", authBaseURL+"/login/anonymous?jo=p&rto=c", nil)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Accept", "application/json")
+
+ resp, err := c.httpDoer.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != 200 {
+ return "", fmt.Errorf("deezer: failed to get JWT token: %s", resp.Status)
+ }
+
+ data, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", err
+ }
+
+ type authResponse struct {
+ JWT string `json:"jwt"` //nolint:gosec
+ }
+
+ var result authResponse
+ if err := json.Unmarshal(data, &result); err != nil {
+ return "", fmt.Errorf("deezer: failed to parse auth response: %w", err)
+ }
+
+ if result.JWT == "" {
+ return "", errors.New("deezer: no JWT token in response")
+ }
+
+ // Parse JWT to get actual expiration time
+ token, err := jwt.ParseString(result.JWT, jwt.WithVerify(false), jwt.WithValidate(false))
+ if err != nil {
+ return "", fmt.Errorf("deezer: failed to parse JWT token: %w", err)
+ }
+
+ // Calculate TTL with a 1-minute buffer for clock skew and network delays
+ expiresAt, ok := token.Expiration()
+ if !ok || expiresAt.IsZero() {
+ return "", errors.New("deezer: JWT token has no expiration time")
+ }
+
+ ttl := time.Until(expiresAt) - 1*time.Minute
+ if ttl <= 0 {
+ return "", errors.New("deezer: JWT token already expired or expires too soon")
+ }
+
+ c.jwt.set(result.JWT, ttl)
+ log.Trace(ctx, "Fetched new Deezer JWT token", "expiresAt", expiresAt, "ttl", ttl)
+
+ return result.JWT, nil
+}
diff --git a/adapters/deezer/client_auth_test.go b/adapters/deezer/client_auth_test.go
new file mode 100644
index 000000000..005a84e1a
--- /dev/null
+++ b/adapters/deezer/client_auth_test.go
@@ -0,0 +1,294 @@
+package deezer
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/lestrrat-go/jwx/v3/jwt"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("JWT Authentication", func() {
+ var httpClient *fakeHttpClient
+ var client *client
+ var ctx context.Context
+
+ BeforeEach(func() {
+ httpClient = &fakeHttpClient{}
+ client = newClient(httpClient)
+ ctx = context.Background()
+ })
+
+ Describe("getJWT", func() {
+ Context("with a valid JWT response", func() {
+ It("successfully fetches and caches a JWT token", func() {
+ testJWT := createTestJWT(5 * time.Minute)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
+ })
+
+ token, err := client.getJWT(ctx)
+ Expect(err).To(BeNil())
+ Expect(token).To(Equal(testJWT))
+ })
+
+ It("returns the cached token on subsequent calls", func() {
+ testJWT := createTestJWT(5 * time.Minute)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
+ })
+
+ // First call should fetch from API
+ token1, err := client.getJWT(ctx)
+ Expect(err).To(BeNil())
+ Expect(token1).To(Equal(testJWT))
+ Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous"))
+
+ // Second call should return cached token without hitting API
+ httpClient.lastRequest = nil // Clear last request to verify no new request is made
+ token2, err := client.getJWT(ctx)
+ Expect(err).To(BeNil())
+ Expect(token2).To(Equal(testJWT))
+ Expect(httpClient.lastRequest).To(BeNil()) // No new request made
+ })
+
+ It("parses the JWT expiration time correctly", func() {
+ expectedExpiration := time.Now().Add(5 * time.Minute)
+ testToken, err := jwt.NewBuilder().
+ Expiration(expectedExpiration).
+ Build()
+ Expect(err).To(BeNil())
+ testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
+ Expect(err).To(BeNil())
+
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
+ })
+
+ token, err := client.getJWT(ctx)
+ Expect(err).To(BeNil())
+ Expect(token).ToNot(BeEmpty())
+
+ // Verify the token is cached until close to expiration
+ // The cache should expire 1 minute before the JWT expires
+ expectedCacheExpiry := expectedExpiration.Add(-1 * time.Minute)
+ Expect(client.jwt.expiresAt).To(BeTemporally("~", expectedCacheExpiry, 2*time.Second))
+ })
+ })
+
+ Context("with JWT tokens that expire soon", func() {
+ It("rejects tokens that expire in less than 1 minute", func() {
+ // Create a token that expires in 30 seconds (less than 1-minute buffer)
+ testJWT := createTestJWT(30 * time.Second)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
+ })
+
+ _, err := client.getJWT(ctx)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("JWT token already expired or expires too soon"))
+ })
+
+ It("rejects already expired tokens", func() {
+ // Create a token that expired 1 minute ago
+ testJWT := createTestJWT(-1 * time.Minute)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
+ })
+
+ _, err := client.getJWT(ctx)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("JWT token already expired or expires too soon"))
+ })
+
+ It("accepts tokens that expire in more than 1 minute", func() {
+ // Create a token that expires in 2 minutes (just over the 1-minute buffer)
+ testJWT := createTestJWT(2 * time.Minute)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
+ })
+
+ token, err := client.getJWT(ctx)
+ Expect(err).To(BeNil())
+ Expect(token).ToNot(BeEmpty())
+ })
+ })
+
+ Context("with invalid responses", func() {
+ It("handles HTTP error responses", func() {
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 500,
+ Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
+ })
+
+ _, err := client.getJWT(ctx)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("failed to get JWT token"))
+ })
+
+ It("handles malformed JSON responses", func() {
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)),
+ })
+
+ _, err := client.getJWT(ctx)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("failed to parse auth response"))
+ })
+
+ It("handles responses with empty JWT field", func() {
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)),
+ })
+
+ _, err := client.getJWT(ctx)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(Equal("deezer: no JWT token in response"))
+ })
+
+ It("handles invalid JWT tokens", func() {
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)),
+ })
+
+ _, err := client.getJWT(ctx)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("failed to parse JWT token"))
+ })
+
+ It("rejects JWT tokens without expiration", func() {
+ // Create a JWT without expiration claim
+ testToken, err := jwt.NewBuilder().
+ Claim("custom", "value").
+ Build()
+ Expect(err).To(BeNil())
+
+ // Verify token has no expiration
+ _, hasExp := testToken.Expiration()
+ Expect(hasExp).To(BeFalse())
+
+ testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
+ Expect(err).To(BeNil())
+
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
+ })
+
+ _, err = client.getJWT(ctx)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(Equal("deezer: JWT token has no expiration time"))
+ })
+ })
+
+ Context("token caching behavior", func() {
+ It("fetches a new token when the cached token expires", func() {
+ // First token expires in 5 minutes
+ firstJWT := createTestJWT(5 * time.Minute)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))),
+ })
+
+ token1, err := client.getJWT(ctx)
+ Expect(err).To(BeNil())
+ Expect(token1).To(Equal(firstJWT))
+
+ // Manually expire the cached token
+ client.jwt.expiresAt = time.Now().Add(-1 * time.Second)
+
+ // Second token with different expiration (10 minutes)
+ secondJWT := createTestJWT(10 * time.Minute)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))),
+ })
+
+ token2, err := client.getJWT(ctx)
+ Expect(err).To(BeNil())
+ Expect(token2).To(Equal(secondJWT))
+ Expect(token2).ToNot(Equal(token1))
+ })
+ })
+ })
+
+ Describe("jwtToken cache", func() {
+ var cache *jwtToken
+
+ BeforeEach(func() {
+ cache = &jwtToken{}
+ })
+
+ It("returns false for expired tokens", func() {
+ cache.set("test-token", -1*time.Second) // Already expired
+ token, valid := cache.get()
+ Expect(valid).To(BeFalse())
+ Expect(token).To(BeEmpty())
+ })
+
+ It("returns true for valid tokens", func() {
+ cache.set("test-token", 4*time.Minute)
+ token, valid := cache.get()
+ Expect(valid).To(BeTrue())
+ Expect(token).To(Equal("test-token"))
+ })
+
+ It("is thread-safe for concurrent access", func() {
+ wg := sync.WaitGroup{}
+
+ // Writer goroutine
+ wg.Go(func() {
+ for i := range 100 {
+ cache.set(fmt.Sprintf("token-%d", i), 1*time.Hour)
+ time.Sleep(1 * time.Millisecond)
+ }
+ })
+
+ // Reader goroutine
+ wg.Go(func() {
+ for range 100 {
+ cache.get()
+ time.Sleep(1 * time.Millisecond)
+ }
+ })
+
+ // Wait for both goroutines to complete
+ wg.Wait()
+
+ // Verify final state is valid
+ token, valid := cache.get()
+ Expect(valid).To(BeTrue())
+ Expect(token).To(HavePrefix("token-"))
+ })
+ })
+})
+
+// createTestJWT creates a valid JWT token for testing purposes
+func createTestJWT(expiresIn time.Duration) string {
+ token, err := jwt.NewBuilder().
+ Expiration(time.Now().Add(expiresIn)).
+ Build()
+ if err != nil {
+ panic(fmt.Sprintf("failed to create test JWT: %v", err))
+ }
+ signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature())
+ if err != nil {
+ panic(fmt.Sprintf("failed to sign test JWT: %v", err))
+ }
+ return string(signed)
+}
diff --git a/adapters/deezer/client_test.go b/adapters/deezer/client_test.go
new file mode 100644
index 000000000..9fa7afdd9
--- /dev/null
+++ b/adapters/deezer/client_test.go
@@ -0,0 +1,210 @@
+package deezer
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "time"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("client", func() {
+ var httpClient *fakeHttpClient
+ var client *client
+
+ BeforeEach(func() {
+ httpClient = &fakeHttpClient{}
+ client = newClient(httpClient)
+ })
+
+ Describe("ArtistImages", func() {
+ It("returns artist images from a successful request", func() {
+ f, err := os.Open("tests/fixtures/deezer.search.artist.json")
+ Expect(err).To(BeNil())
+ httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200})
+
+ artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
+ Expect(err).To(BeNil())
+ Expect(artists).To(HaveLen(17))
+ Expect(artists[0].Name).To(Equal("Michael Jackson"))
+ Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg"))
+ })
+
+ It("fails if artist was not found", func() {
+ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
+ })
+
+ _, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
+ Expect(err).To(MatchError(ErrNotFound))
+ })
+ })
+
+ Describe("TopTracks", func() {
+ It("returns top tracks with artist and album info from a successful request", func() {
+ f, err := os.Open("tests/fixtures/deezer.artist.top.json")
+ Expect(err).To(BeNil())
+ httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200})
+
+ tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
+ Expect(err).To(BeNil())
+ Expect(tracks).To(HaveLen(5))
+
+ // Verify first track has all expected fields
+ Expect(tracks[0].Title).To(Equal("Instant Crush (feat. Julian Casablancas)"))
+ Expect(tracks[0].Artist.Name).To(Equal("Daft Punk"))
+ Expect(tracks[0].Album.Title).To(Equal("Random Access Memories"))
+
+ // Verify second track
+ Expect(tracks[1].Title).To(Equal("One More Time"))
+ Expect(tracks[1].Artist.Name).To(Equal("Daft Punk"))
+ Expect(tracks[1].Album.Title).To(Equal("Discovery"))
+ })
+ })
+
+ Describe("ArtistBio", func() {
+ BeforeEach(func() {
+ // Mock the JWT token endpoint with a valid JWT that expires in 5 minutes
+ testJWT := createTestJWT(5 * time.Minute)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
+ })
+ })
+
+ It("returns artist bio from a successful request", func() {
+ f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
+ Expect(err).To(BeNil())
+ httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
+
+ bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
+ Expect(err).To(BeNil())
+ Expect(bio).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel"))
+ Expect(bio).ToNot(ContainSubstring(""))
+ Expect(bio).ToNot(ContainSubstring("
"))
+ })
+
+ It("uses the provided language", func() {
+ f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
+ Expect(err).To(BeNil())
+ httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
+
+ _, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
+ Expect(err).To(BeNil())
+ Expect(httpClient.lastRequest.Header.Get("Accept-Language")).To(Equal("fr"))
+ })
+
+ It("includes the JWT token in the request", func() {
+ f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
+ Expect(err).To(BeNil())
+ httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
+
+ _, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
+ Expect(err).To(BeNil())
+ // Verify that the Authorization header has the Bearer token format
+ authHeader := httpClient.lastRequest.Header.Get("Authorization")
+ Expect(authHeader).To(HavePrefix("Bearer "))
+ Expect(len(authHeader)).To(BeNumerically(">", 20)) // JWT tokens are longer than 20 chars
+ })
+
+ It("handles GraphQL errors", func() {
+ errorResponse := `{
+ "data": {
+ "artist": {
+ "bio": {
+ "full": ""
+ }
+ }
+ },
+ "errors": [
+ {
+ "message": "Artist not found"
+ },
+ {
+ "message": "Invalid artist ID"
+ }
+ ]
+ }`
+ httpClient.mock("https://pipe.deezer.com/api", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(errorResponse)),
+ })
+
+ _, err := client.getArtistBio(GinkgoT().Context(), 999, "en")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("GraphQL error"))
+ Expect(err.Error()).To(ContainSubstring("Artist not found"))
+ Expect(err.Error()).To(ContainSubstring("Invalid artist ID"))
+ })
+
+ It("handles empty biography", func() {
+ emptyBioResponse := `{
+ "data": {
+ "artist": {
+ "bio": {
+ "full": ""
+ }
+ }
+ }
+ }`
+ httpClient.mock("https://pipe.deezer.com/api", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)),
+ })
+
+ _, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
+ Expect(err).To(MatchError("deezer: biography not found"))
+ })
+
+ It("handles JWT token fetch failure", func() {
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 500,
+ Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
+ })
+
+ _, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("failed to get JWT"))
+ })
+
+ It("handles JWT token that expires too soon", func() {
+ // Create a JWT that expires in 30 seconds (less than the 1-minute buffer)
+ expiredJWT := createTestJWT(30 * time.Second)
+ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))),
+ })
+
+ _, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("JWT token already expired or expires too soon"))
+ })
+ })
+})
+
+type fakeHttpClient struct {
+ responses map[string]*http.Response
+ lastRequest *http.Request
+}
+
+func (c *fakeHttpClient) mock(url string, response http.Response) {
+ if c.responses == nil {
+ c.responses = make(map[string]*http.Response)
+ }
+ c.responses[url] = &response
+}
+
+func (c *fakeHttpClient) Do(req *http.Request) (*http.Response, error) {
+ c.lastRequest = req
+ u := req.URL
+ u.RawQuery = ""
+ if resp, ok := c.responses[u.String()]; ok {
+ return resp, nil
+ }
+ panic("URL not mocked: " + u.String())
+}
diff --git a/core/agents/deezer/deezer.go b/adapters/deezer/deezer.go
similarity index 53%
rename from core/agents/deezer/deezer.go
rename to adapters/deezer/deezer.go
index 8cabfbcfb..ed3071766 100644
--- a/core/agents/deezer/deezer.go
+++ b/adapters/deezer/deezer.go
@@ -3,6 +3,7 @@ package deezer
import (
"context"
"errors"
+ "fmt"
"net/http"
"strings"
@@ -12,6 +13,7 @@ import (
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/cache"
+ "github.com/navidrome/navidrome/utils/slice"
)
const deezerAgentName = "deezer"
@@ -24,10 +26,14 @@ const deezerArtistSearchLimit = 50
type deezerAgent struct {
dataStore model.DataStore
client *client
+ languages []string
}
func deezerConstructor(dataStore model.DataStore) agents.Interface {
- agent := &deezerAgent{dataStore: dataStore}
+ agent := &deezerAgent{
+ dataStore: dataStore,
+ languages: conf.Server.Deezer.Languages,
+ }
httpClient := &http.Client{
Timeout: consts.DefaultHttpClientTimeOut,
}
@@ -81,13 +87,82 @@ func (s *deezerAgent) searchArtist(ctx context.Context, name string) (*Artist, e
return nil, err
}
+ log.Trace(ctx, "Artists found", "count", len(artists), "searched_name", name)
+ for i := range artists {
+ log.Trace(ctx, fmt.Sprintf("Artists found #%d", i), "name", artists[i].Name, "id", artists[i].ID, "link", artists[i].Link)
+ if i > 2 {
+ break
+ }
+ }
+
// If the first one has the same name, that's the one
if !strings.EqualFold(artists[0].Name, name) {
+ log.Trace(ctx, "Top artist do not match", "searched_name", name, "found_name", artists[0].Name)
return nil, agents.ErrNotFound
}
+ log.Trace(ctx, "Found artist", "name", artists[0].Name, "id", artists[0].ID, "link", artists[0].Link)
return &artists[0], err
}
+func (s *deezerAgent) GetSimilarArtists(ctx context.Context, _, name, _ string, limit int) ([]agents.Artist, error) {
+ artist, err := s.searchArtist(ctx, name)
+ if err != nil {
+ return nil, err
+ }
+
+ related, err := s.client.getRelatedArtists(ctx, artist.ID)
+ if err != nil {
+ return nil, err
+ }
+
+ res := slice.Map(related, func(r Artist) agents.Artist {
+ return agents.Artist{
+ Name: r.Name,
+ }
+ })
+ if len(res) > limit {
+ res = res[:limit]
+ }
+ return res, nil
+}
+
+func (s *deezerAgent) GetArtistTopSongs(ctx context.Context, _, artistName, _ string, count int) ([]agents.Song, error) {
+ artist, err := s.searchArtist(ctx, artistName)
+ if err != nil {
+ return nil, err
+ }
+
+ tracks, err := s.client.getTopTracks(ctx, artist.ID, count)
+ if err != nil {
+ return nil, err
+ }
+
+ res := slice.Map(tracks, func(r Track) agents.Song {
+ return agents.Song{
+ Name: r.Title,
+ Album: r.Album.Title,
+ Duration: uint32(r.Duration * 1000), // Convert seconds to milliseconds
+ }
+ })
+ return res, nil
+}
+
+func (s *deezerAgent) GetArtistBiography(ctx context.Context, _, name, _ string) (string, error) {
+ artist, err := s.searchArtist(ctx, name)
+ if err != nil {
+ return "", err
+ }
+
+ for _, lang := range s.languages {
+ bio, err := s.client.getArtistBio(ctx, artist.ID, lang)
+ if err == nil && bio != "" {
+ return bio, nil
+ }
+ log.Debug(ctx, "Deezer/artist.bio returned empty/error, trying next language", "artist", name, "lang", lang, err)
+ }
+ return "", agents.ErrNotFound
+}
+
func init() {
conf.AddHook(func() {
if conf.Server.Deezer.Enabled {
diff --git a/core/agents/deezer/deezer_suite_test.go b/adapters/deezer/deezer_suite_test.go
similarity index 100%
rename from core/agents/deezer/deezer_suite_test.go
rename to adapters/deezer/deezer_suite_test.go
diff --git a/adapters/deezer/deezer_test.go b/adapters/deezer/deezer_test.go
new file mode 100644
index 000000000..4dd251585
--- /dev/null
+++ b/adapters/deezer/deezer_test.go
@@ -0,0 +1,171 @@
+package deezer
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/core/agents"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("deezerAgent", func() {
+ var ctx context.Context
+
+ BeforeEach(func() {
+ ctx = context.Background()
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Deezer.Enabled = true
+ })
+
+ Describe("deezerConstructor", func() {
+ It("uses configured languages", func() {
+ conf.Server.Deezer.Languages = []string{"pt", "en"}
+ agent := deezerConstructor(&tests.MockDataStore{}).(*deezerAgent)
+ Expect(agent.languages).To(Equal([]string{"pt", "en"}))
+ })
+ })
+
+ Describe("GetArtistBiography - Language Fallback", func() {
+ var agent *deezerAgent
+ var httpClient *langAwareHttpClient
+
+ BeforeEach(func() {
+ httpClient = newLangAwareHttpClient()
+
+ // Mock search artist (returns Michael Jackson)
+ fSearch, _ := os.Open("tests/fixtures/deezer.search.artist.json")
+ httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: 200}
+
+ // Mock JWT token
+ testJWT := createTestJWT(5 * time.Minute)
+ httpClient.jwtResponse = &http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
+ }
+ })
+
+ setupAgent := func(languages []string) {
+ conf.Server.Deezer.Languages = languages
+ agent = &deezerAgent{
+ dataStore: &tests.MockDataStore{},
+ client: newClient(httpClient),
+ languages: languages,
+ }
+ }
+
+ It("returns content in first language when available (1 bio API call)", func() {
+ setupAgent([]string{"fr", "en"})
+
+ // French biography available
+ fFr, _ := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
+ httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: 200}
+
+ bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(bio).To(ContainSubstring("Guy-Manuel de Homem Christo et Thomas Bangalter"))
+ Expect(httpClient.bioRequestCount).To(Equal(1))
+ Expect(httpClient.bioRequests[0].Header.Get("Accept-Language")).To(Equal("fr"))
+ })
+
+ It("falls back to second language when first returns empty (2 bio API calls)", func() {
+ setupAgent([]string{"ja", "en"})
+
+ // Japanese returns empty biography
+ fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
+ httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
+ // English returns full biography
+ fEn, _ := os.Open("tests/fixtures/deezer.artist.bio.en.json")
+ httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: 200}
+
+ bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(bio).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel"))
+ Expect(httpClient.bioRequestCount).To(Equal(2))
+ Expect(httpClient.bioRequests[0].Header.Get("Accept-Language")).To(Equal("ja"))
+ Expect(httpClient.bioRequests[1].Header.Get("Accept-Language")).To(Equal("en"))
+ })
+
+ It("returns ErrNotFound when all languages return empty", func() {
+ setupAgent([]string{"ja", "xx"})
+
+ // Both languages return empty biography
+ fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
+ httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
+ fXx, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
+ httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: 200}
+
+ _, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
+
+ Expect(err).To(MatchError(agents.ErrNotFound))
+ Expect(httpClient.bioRequestCount).To(Equal(2))
+ })
+ })
+})
+
+// langAwareHttpClient is a mock HTTP client that returns different responses based on the Accept-Language header
+type langAwareHttpClient struct {
+ searchResponse *http.Response
+ jwtResponse *http.Response
+ bioResponses map[string]*http.Response
+ bioRequests []*http.Request
+ bioRequestCount int
+}
+
+func newLangAwareHttpClient() *langAwareHttpClient {
+ return &langAwareHttpClient{
+ bioResponses: make(map[string]*http.Response),
+ bioRequests: make([]*http.Request, 0),
+ }
+}
+
+func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
+ // Handle search artist request
+ if req.URL.Host == "api.deezer.com" && req.URL.Path == "/search/artist" {
+ if c.searchResponse != nil {
+ return c.searchResponse, nil
+ }
+ return &http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
+ }, nil
+ }
+
+ // Handle JWT token request
+ if req.URL.Host == "auth.deezer.com" && req.URL.Path == "/login/anonymous" {
+ if c.jwtResponse != nil {
+ return c.jwtResponse, nil
+ }
+ return &http.Response{
+ StatusCode: 500,
+ Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)),
+ }, nil
+ }
+
+ // Handle bio request (GraphQL API)
+ if req.URL.Host == "pipe.deezer.com" && req.URL.Path == "/api" {
+ c.bioRequestCount++
+ c.bioRequests = append(c.bioRequests, req)
+ lang := req.Header.Get("Accept-Language")
+ if resp, ok := c.bioResponses[lang]; ok {
+ return resp, nil
+ }
+ // Return empty bio by default
+ return &http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
+ }, nil
+ }
+
+ panic("URL not mocked: " + req.URL.String())
+}
diff --git a/adapters/deezer/responses.go b/adapters/deezer/responses.go
new file mode 100644
index 000000000..266c44c62
--- /dev/null
+++ b/adapters/deezer/responses.go
@@ -0,0 +1,66 @@
+package deezer
+
+type SearchArtistResults struct {
+ Data []Artist `json:"data"`
+ Total int `json:"total"`
+ Next string `json:"next"`
+}
+
+type Artist struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Link string `json:"link"`
+ Picture string `json:"picture"`
+ PictureSmall string `json:"picture_small"`
+ PictureMedium string `json:"picture_medium"`
+ PictureBig string `json:"picture_big"`
+ PictureXl string `json:"picture_xl"`
+ NbAlbum int `json:"nb_album"`
+ NbFan int `json:"nb_fan"`
+ Radio bool `json:"radio"`
+ Tracklist string `json:"tracklist"`
+ Type string `json:"type"`
+}
+
+type Error struct {
+ Error struct {
+ Type string `json:"type"`
+ Message string `json:"message"`
+ Code int `json:"code"`
+ } `json:"error"`
+}
+
+type RelatedArtists struct {
+ Data []Artist `json:"data"`
+ Total int `json:"total"`
+}
+
+type TopTracks struct {
+ Data []Track `json:"data"`
+ Total int `json:"total"`
+ Next string `json:"next"`
+}
+
+type Track struct {
+ ID int `json:"id"`
+ Title string `json:"title"`
+ Link string `json:"link"`
+ Duration int `json:"duration"`
+ Rank int `json:"rank"`
+ Preview string `json:"preview"`
+ Artist Artist `json:"artist"`
+ Album Album `json:"album"`
+ Contributors []Artist `json:"contributors"`
+}
+
+type Album struct {
+ ID int `json:"id"`
+ Title string `json:"title"`
+ Cover string `json:"cover"`
+ CoverSmall string `json:"cover_small"`
+ CoverMedium string `json:"cover_medium"`
+ CoverBig string `json:"cover_big"`
+ CoverXl string `json:"cover_xl"`
+ Tracklist string `json:"tracklist"`
+ Type string `json:"type"`
+}
diff --git a/core/agents/deezer/responses_test.go b/adapters/deezer/responses_test.go
similarity index 53%
rename from core/agents/deezer/responses_test.go
rename to adapters/deezer/responses_test.go
index 95a7f43f4..a9de5c5fb 100644
--- a/core/agents/deezer/responses_test.go
+++ b/adapters/deezer/responses_test.go
@@ -35,4 +35,35 @@ var _ = Describe("Responses", func() {
Expect(errorResp.Error.Message).To(Equal("Missing parameters: q"))
})
})
+
+ Describe("Related Artists", func() {
+ It("parses the related artists response correctly", func() {
+ var resp RelatedArtists
+ body, err := os.ReadFile("tests/fixtures/deezer.artist.related.json")
+ Expect(err).To(BeNil())
+ err = json.Unmarshal(body, &resp)
+ Expect(err).To(BeNil())
+
+ Expect(resp.Data).To(HaveLen(20))
+ justice := resp.Data[0]
+ Expect(justice.Name).To(Equal("Justice"))
+ Expect(justice.ID).To(Equal(6404))
+ })
+ })
+
+ Describe("Top Tracks", func() {
+ It("parses the top tracks response correctly", func() {
+ var resp TopTracks
+ body, err := os.ReadFile("tests/fixtures/deezer.artist.top.json")
+ Expect(err).To(BeNil())
+ err = json.Unmarshal(body, &resp)
+ Expect(err).To(BeNil())
+
+ Expect(resp.Data).To(HaveLen(5))
+ track := resp.Data[0]
+ Expect(track.Title).To(Equal("Instant Crush (feat. Julian Casablancas)"))
+ Expect(track.ID).To(Equal(67238732))
+ Expect(track.Album.Title).To(Equal("Random Access Memories"))
+ })
+ })
})
diff --git a/adapters/gotaglib/end_to_end_test.go b/adapters/gotaglib/end_to_end_test.go
new file mode 100644
index 000000000..4a93f5b83
--- /dev/null
+++ b/adapters/gotaglib/end_to_end_test.go
@@ -0,0 +1,274 @@
+package gotaglib
+
+import (
+ "io/fs"
+ "os"
+ "time"
+
+ "github.com/djherbis/times"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/metadata"
+ "github.com/navidrome/navidrome/utils/gg"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+type testFileInfo struct {
+ fs.FileInfo
+}
+
+func (t testFileInfo) BirthTime() time.Time {
+ if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
+ return ts.BirthTime()
+ }
+ return t.FileInfo.ModTime()
+}
+
+var _ = Describe("Extractor", func() {
+ toP := func(name, sortName, mbid string) model.Participant {
+ return model.Participant{
+ Artist: model.Artist{Name: name, SortArtistName: sortName, MbzArtistID: mbid},
+ }
+ }
+
+ roles := []struct {
+ model.Role
+ model.ParticipantList
+ }{
+ {model.RoleComposer, model.ParticipantList{
+ toP("coma a", "a, coma", "bf13b584-f27c-43db-8f42-32898d33d4e2"),
+ toP("comb", "comb", "924039a2-09c6-4d29-9b4f-50cc54447d36"),
+ }},
+ {model.RoleLyricist, model.ParticipantList{
+ toP("la a", "a, la", "c84f648f-68a6-40a2-a0cb-d135b25da3c2"),
+ toP("lb", "lb", "0a7c582d-143a-4540-b4e9-77200835af65"),
+ }},
+ {model.RoleArranger, model.ParticipantList{
+ toP("aa", "", "4605a1d4-8d15-42a3-bd00-9c20e42f71e6"),
+ toP("ab", "", "002f0ff8-77bf-42cc-8216-61a9c43dc145"),
+ }},
+ {model.RoleConductor, model.ParticipantList{
+ toP("cona", "", "af86879b-2141-42af-bad2-389a4dc91489"),
+ toP("conb", "", "3dfa3c70-d7d3-4b97-b953-c298dd305e12"),
+ }},
+ {model.RoleDirector, model.ParticipantList{
+ toP("dia", "", "f943187f-73de-4794-be47-88c66f0fd0f4"),
+ toP("dib", "", "bceb75da-1853-4b3d-b399-b27f0cafc389"),
+ }},
+ {model.RoleEngineer, model.ParticipantList{
+ toP("ea", "", "f634bf6d-d66a-425d-888a-28ad39392759"),
+ toP("eb", "", "243d64ae-d514-44e1-901a-b918d692baee"),
+ }},
+ {model.RoleProducer, model.ParticipantList{
+ toP("pra", "", "d971c8d7-999c-4a5f-ac31-719721ab35d6"),
+ toP("prb", "", "f0a09070-9324-434f-a599-6d25ded87b69"),
+ }},
+ {model.RoleRemixer, model.ParticipantList{
+ toP("ra", "", "c7dc6095-9534-4c72-87cc-aea0103462cf"),
+ toP("rb", "", "8ebeef51-c08c-4736-992f-c37870becedd"),
+ }},
+ {model.RoleDJMixer, model.ParticipantList{
+ toP("dja", "", "d063f13b-7589-4efc-ab7f-c60e6db17247"),
+ toP("djb", "", "3636670c-385f-4212-89c8-0ff51d6bc456"),
+ }},
+ {model.RoleMixer, model.ParticipantList{
+ toP("ma", "", "53fb5a2d-7016-427e-a563-d91819a5f35a"),
+ toP("mb", "", "64c13e65-f0da-4ab9-a300-71ee53b0376a"),
+ }},
+ }
+
+ var e *extractor
+
+ parseTestFile := func(path string) *model.MediaFile {
+ mds, err := e.Parse(path)
+ Expect(err).ToNot(HaveOccurred())
+
+ info, ok := mds[path]
+ Expect(ok).To(BeTrue())
+
+ fileInfo, err := os.Stat(path)
+ Expect(err).ToNot(HaveOccurred())
+ info.FileInfo = testFileInfo{FileInfo: fileInfo}
+
+ metadata := metadata.New(path, info)
+ mf := metadata.ToMediaFile(1, "folderID")
+ return &mf
+ }
+
+ BeforeEach(func() {
+ e = &extractor{fs: os.DirFS(".")}
+ })
+
+ Describe("ReplayGain", func() {
+ DescribeTable("test replaygain end-to-end", func(file string, trackGain, trackPeak, albumGain, albumPeak *float64) {
+ mf := parseTestFile("tests/fixtures/" + file)
+
+ Expect(mf.RGTrackGain).To(Equal(trackGain))
+ Expect(mf.RGTrackPeak).To(Equal(trackPeak))
+ Expect(mf.RGAlbumGain).To(Equal(albumGain))
+ Expect(mf.RGAlbumPeak).To(Equal(albumPeak))
+ },
+ Entry("mp3 with no replaygain", "no_replaygain.mp3", nil, nil, nil, nil),
+ Entry("mp3 with no zero replaygain", "zero_replaygain.mp3", gg.P(0.0), gg.P(1.0), gg.P(0.0), gg.P(1.0)),
+ )
+ })
+
+ Describe("lyrics", func() {
+ makeLyrics := func(code, secondLine string) model.Lyrics {
+ return model.Lyrics{
+ DisplayArtist: "",
+ DisplayTitle: "",
+ Lang: code,
+ Line: []model.Line{
+ {Start: gg.P(int64(0)), Value: "This is"},
+ {Start: gg.P(int64(2500)), Value: secondLine},
+ },
+ Offset: nil,
+ Synced: true,
+ }
+ }
+
+ It("should fetch both synced and unsynced lyrics in mixed flac", func() {
+ mf := parseTestFile("tests/fixtures/mixed-lyrics.flac")
+
+ lyrics, err := mf.StructuredLyrics()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(lyrics).To(HaveLen(2))
+
+ Expect(lyrics[0].Synced).To(BeTrue())
+ Expect(lyrics[1].Synced).To(BeFalse())
+ })
+
+ It("should handle mp3 with uslt and sylt", func() {
+ mf := parseTestFile("tests/fixtures/test.mp3")
+
+ lyrics, err := mf.StructuredLyrics()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(lyrics).To(HaveLen(4))
+
+ engSylt := makeLyrics("eng", "English SYLT")
+ engUslt := makeLyrics("eng", "English")
+ unsSylt := makeLyrics("xxx", "unspecified SYLT")
+ unsUslt := makeLyrics("xxx", "unspecified")
+
+ Expect(lyrics).To(ConsistOf(engSylt, engUslt, unsSylt, unsUslt))
+ })
+
+ DescribeTable("format-specific lyrics", func(file string, isId3 bool) {
+ mf := parseTestFile("tests/fixtures/" + file)
+
+ lyrics, err := mf.StructuredLyrics()
+ Expect(err).To(Not(HaveOccurred()))
+ Expect(lyrics).To(HaveLen(2))
+
+ unspec := makeLyrics("xxx", "unspecified")
+ eng := makeLyrics("xxx", "English")
+
+ if isId3 {
+ eng.Lang = "eng"
+ }
+
+ Expect(lyrics).To(Or(
+ Equal(model.LyricList{unspec, eng}),
+ Equal(model.LyricList{eng, unspec})))
+ },
+ Entry("flac", "test.flac", false),
+ Entry("m4a", "test.m4a", false),
+ Entry("ogg", "test.ogg", false),
+ Entry("wma", "test.wma", false),
+ Entry("wv", "test.wv", false),
+ Entry("wav", "test.wav", true),
+ Entry("aiff", "test.aiff", true),
+ )
+ })
+
+ Describe("Participants", func() {
+ DescribeTable("test tags consistent across formats", func(format string) {
+ mf := parseTestFile("tests/fixtures/test." + format)
+
+ for _, data := range roles {
+ role := data.Role
+ artists := data.ParticipantList
+
+ actual := mf.Participants[role]
+ Expect(actual).To(HaveLen(len(artists)))
+
+ for i := range artists {
+ actualArtist := actual[i]
+ expectedArtist := artists[i]
+
+ Expect(actualArtist.Name).To(Equal(expectedArtist.Name))
+ Expect(actualArtist.SortArtistName).To(Equal(expectedArtist.SortArtistName))
+ Expect(actualArtist.MbzArtistID).To(Equal(expectedArtist.MbzArtistID))
+ }
+ }
+
+ if format != "m4a" {
+ performers := mf.Participants[model.RolePerformer]
+ Expect(performers).To(HaveLen(8))
+
+ rules := map[string][]string{
+ "pgaa": {"2fd0b311-9fa8-4ff9-be5d-f6f3d16b835e", "Guitar"},
+ "pgbb": {"223d030b-bf97-4c2a-ad26-b7f7bbe25c93", "Guitar", ""},
+ "pvaa": {"cb195f72-448f-41c8-b962-3f3c13d09d38", "Vocals"},
+ "pvbb": {"60a1f832-8ca2-49f6-8660-84d57f07b520", "Vocals", "Flute"},
+ "pfaa": {"51fb40c-0305-4bf9-a11b-2ee615277725", "", "Flute"},
+ }
+
+ for name, rule := range rules {
+ mbid := rule[0]
+ for i := 1; i < len(rule); i++ {
+ found := false
+
+ for _, mapped := range performers {
+ if mapped.Name == name && mapped.MbzArtistID == mbid && mapped.SubRole == rule[i] {
+ found = true
+ break
+ }
+ }
+
+ Expect(found).To(BeTrue(), "Could not find matching artist")
+ }
+ }
+ }
+ },
+ Entry("FLAC format", "flac"),
+ Entry("M4a format", "m4a"),
+ Entry("OGG format", "ogg"),
+ Entry("WV format", "wv"),
+
+ Entry("MP3 format", "mp3"),
+ Entry("WAV format", "wav"),
+ Entry("AIFF format", "aiff"),
+ )
+
+ It("should parse wma", func() {
+ mf := parseTestFile("tests/fixtures/test.wma")
+
+ for _, data := range roles {
+ role := data.Role
+ artists := data.ParticipantList
+ actual := mf.Participants[role]
+
+ // WMA has no Arranger role
+ if role == model.RoleArranger {
+ Expect(actual).To(HaveLen(0))
+ continue
+ }
+
+ Expect(actual).To(HaveLen(len(artists)), role.String())
+
+ // For some bizarre reason, the order is inverted. We also don't get
+ // sort names or MBIDs
+ for i := range artists {
+ idx := len(artists) - 1 - i
+
+ actualArtist := actual[i]
+ expectedArtist := artists[idx]
+
+ Expect(actualArtist.Name).To(Equal(expectedArtist.Name))
+ }
+ }
+ })
+ })
+})
diff --git a/adapters/gotaglib/gotaglib.go b/adapters/gotaglib/gotaglib.go
new file mode 100644
index 000000000..7ea98a442
--- /dev/null
+++ b/adapters/gotaglib/gotaglib.go
@@ -0,0 +1,301 @@
+// Package gotaglib provides an alternative metadata extractor using go-taglib,
+// a pure Go (WASM-based) implementation of TagLib.
+//
+// This extractor aims for parity with the CGO-based taglib extractor. It uses
+// TagLib's PropertyMap interface for standard tags. The File handle API provides
+// efficient access to format-specific tags (ID3v2 frames, MP4 atoms, ASF attributes)
+// through a single file open operation.
+//
+// This extractor is registered under the name "taglib". It only works with a filesystem
+// (fs.FS) and does not support direct local file paths. Files returned by the filesystem
+// must implement io.ReadSeeker for go-taglib to read them.
+package gotaglib
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "runtime/debug"
+ "strings"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/core/storage/local"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model/metadata"
+ "go.senan.xyz/taglib"
+)
+
+type extractor struct {
+ fs fs.FS
+}
+
+func (e extractor) Parse(files ...string) (map[string]metadata.Info, error) {
+ results := make(map[string]metadata.Info)
+ for _, path := range files {
+ props, err := e.extractMetadata(path)
+ if err != nil {
+ continue
+ }
+ results[path] = *props
+ }
+ return results, nil
+}
+
+func (e extractor) Version() string {
+ bi, ok := debug.ReadBuildInfo()
+ if ok {
+ for _, dep := range bi.Deps {
+ if dep.Path == "go.senan.xyz/taglib" {
+ if dep.Replace != nil {
+ return dep.Replace.Version
+ }
+ return dep.Version
+ }
+ }
+ }
+ return "unknown"
+}
+
+func (e extractor) extractMetadata(filePath string) (info *metadata.Info, err error) {
+ // Recover from panics in the WASM runtime that can occur during any taglib
+ // operation (opening, reading tags, or reading properties). This catches crashes
+ // from malformed files or WASM runtime issues (e.g., wazero mmap failures on
+ // hardened systems with MemoryDenyWriteExecute=true).
+ debug.SetPanicOnFault(true)
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error("gotaglib: WASM runtime panic reading file. Skipping", "filePath", filePath, "panic", r)
+ debug.PrintStack()
+ err = fmt.Errorf("WASM runtime panic: %v", r)
+ }
+ }()
+
+ f, close, err := e.openFile(filePath)
+ if err != nil {
+ log.Warn("gotaglib: Error reading metadata from file. Skipping", "filePath", filePath, err)
+ return nil, err
+ }
+ defer close()
+
+ // Get all tags and properties in one go
+ allTags := f.AllTags()
+ props := f.Properties()
+
+ // Map properties to AudioProperties
+ ap := metadata.AudioProperties{
+ Duration: props.Length.Round(time.Millisecond * 10),
+ BitRate: int(props.Bitrate),
+ Channels: int(props.Channels),
+ SampleRate: int(props.SampleRate),
+ BitDepth: int(props.BitsPerSample),
+ Codec: props.Codec,
+ }
+
+ // Convert normalized tags to lowercase keys (go-taglib returns UPPERCASE keys)
+ normalizedTags := make(map[string][]string, len(allTags.Tags))
+ for key, values := range allTags.Tags {
+ lowerKey := strings.ToLower(key)
+ normalizedTags[lowerKey] = values
+ }
+
+ // Process format-specific raw tags
+ processRawTags(allTags, normalizedTags)
+
+ // Parse track/disc totals from "N/Total" format
+ parseTuple(normalizedTags, "track")
+ parseTuple(normalizedTags, "disc")
+
+ // Adjust some ID3 tags
+ parseLyrics(normalizedTags)
+ parseTIPL(normalizedTags)
+ delete(normalizedTags, "tmcl") // TMCL is already parsed by TagLib
+
+ // Determine if file has embedded picture
+ hasPicture := len(props.Images) > 0
+
+ return &metadata.Info{
+ Tags: normalizedTags,
+ AudioProperties: ap,
+ HasPicture: hasPicture,
+ }, nil
+}
+
+// openFile opens the file at filePath using the extractor's filesystem.
+// It returns a TagLib File handle and a cleanup function to close resources.
+func (e extractor) openFile(filePath string) (f *taglib.File, closeFunc func(), err error) {
+ // Open the file from the filesystem
+ file, err := e.fs.Open(filePath)
+ if err != nil {
+ return nil, nil, err
+ }
+ rs, isSeekable := file.(io.ReadSeeker)
+ if !isSeekable {
+ file.Close()
+ return nil, nil, errors.New("file is not seekable")
+ }
+ // WithFilename provides a format detection hint via the file extension,
+ // since OpenStream alone relies on content-sniffing which fails for some files.
+ f, err = taglib.OpenStream(rs,
+ taglib.WithReadStyle(taglib.ReadStyleFast),
+ taglib.WithFilename(filePath),
+ )
+ if err != nil {
+ file.Close()
+ return nil, nil, err
+ }
+ closeFunc = func() {
+ f.Close()
+ file.Close()
+ }
+ return f, closeFunc, nil
+}
+
+// parseTuple parses track/disc numbers in "N/Total" format and separates them.
+// For example, tracknumber="2/10" becomes tracknumber="2" and tracktotal="10".
+func parseTuple(tags map[string][]string, prop string) {
+ tagName := prop + "number"
+ tagTotal := prop + "total"
+ if value, ok := tags[tagName]; ok && len(value) > 0 {
+ parts := strings.Split(value[0], "/")
+ tags[tagName] = []string{parts[0]}
+ if len(parts) == 2 {
+ tags[tagTotal] = []string{parts[1]}
+ }
+ }
+}
+
+// parseLyrics ensures lyrics tags have a language code.
+// If lyrics exist without a language code, they are moved to "lyrics:xxx".
+func parseLyrics(tags map[string][]string) {
+ lyrics := tags["lyrics"]
+ if len(lyrics) > 0 {
+ tags["lyrics:xxx"] = lyrics
+ delete(tags, "lyrics")
+ }
+}
+
+// processRawTags processes format-specific raw tags based on the detected file format.
+// This handles ID3v2 frames (MP3/WAV/AIFF), MP4 atoms, and ASF attributes.
+func processRawTags(allTags taglib.AllTags, normalizedTags map[string][]string) {
+ switch allTags.Format {
+ case taglib.FormatMPEG, taglib.FormatWAV, taglib.FormatAIFF:
+ parseID3v2Frames(allTags.Raw, normalizedTags)
+ case taglib.FormatMP4:
+ parseMP4Atoms(allTags.Raw, normalizedTags)
+ case taglib.FormatASF:
+ parseASFAttributes(allTags.Raw, normalizedTags)
+ }
+}
+
+// parseID3v2Frames processes ID3v2 raw frames to extract USLT/SYLT with language codes.
+// This extracts language-specific lyrics that the standard Tags() doesn't provide.
+func parseID3v2Frames(rawFrames map[string][]string, tags map[string][]string) {
+ // Process frames that have language-specific data
+ for key, values := range rawFrames {
+ lowerKey := strings.ToLower(key)
+
+ // Handle USLT:xxx and SYLT:xxx (lyrics with language codes)
+ if strings.HasPrefix(lowerKey, "uslt:") || strings.HasPrefix(lowerKey, "sylt:") {
+ parts := strings.SplitN(lowerKey, ":", 2)
+ if len(parts) == 2 && parts[1] != "" {
+ lang := parts[1]
+ lyricsKey := "lyrics:" + lang
+ tags[lyricsKey] = append(tags[lyricsKey], values...)
+ }
+ }
+ }
+
+ // If we found any language-specific lyrics from ID3v2 frames, remove the generic lyrics
+ for key := range tags {
+ if strings.HasPrefix(key, "lyrics:") && key != "lyrics" {
+ delete(tags, "lyrics")
+ break
+ }
+ }
+}
+
+const iTunesKeyPrefix = "----:com.apple.iTunes:"
+
+// parseMP4Atoms processes MP4 raw atoms to get iTunes-specific tags.
+func parseMP4Atoms(rawAtoms map[string][]string, tags map[string][]string) {
+ // Process all atoms and add them to tags
+ for key, values := range rawAtoms {
+ // Strip iTunes prefix and convert to lowercase
+ normalizedKey := strings.TrimPrefix(key, iTunesKeyPrefix)
+ normalizedKey = strings.ToLower(normalizedKey)
+
+ // Only add if the tag doesn't already exist (avoid duplication with PropertyMap)
+ if _, exists := tags[normalizedKey]; !exists {
+ tags[normalizedKey] = values
+ }
+ }
+}
+
+// parseASFAttributes processes ASF raw attributes to get WMA-specific tags.
+func parseASFAttributes(rawAttrs map[string][]string, tags map[string][]string) {
+ // Process all attributes and add them to tags
+ for key, values := range rawAttrs {
+ normalizedKey := strings.ToLower(key)
+
+ // Only add if the tag doesn't already exist (avoid duplication with PropertyMap)
+ if _, exists := tags[normalizedKey]; !exists {
+ tags[normalizedKey] = values
+ }
+ }
+}
+
+// These are the only roles we support, based on Picard's tag map:
+// https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html
+var tiplMapping = map[string]string{
+ "arranger": "arranger",
+ "engineer": "engineer",
+ "producer": "producer",
+ "mix": "mixer",
+ "DJ-mix": "djmixer",
+}
+
+// parseTIPL parses the ID3v2.4 TIPL frame string, which is received from TagLib in the format:
+//
+// "arranger Andrew Powell engineer Chris Blair engineer Pat Stapley producer Eric Woolfson".
+//
+// and breaks it down into a map of roles and names, e.g.:
+//
+// {"arranger": ["Andrew Powell"], "engineer": ["Chris Blair", "Pat Stapley"], "producer": ["Eric Woolfson"]}.
+func parseTIPL(tags map[string][]string) {
+ tipl := tags["tipl"]
+ if len(tipl) == 0 {
+ return
+ }
+ addRole := func(currentRole string, currentValue []string) {
+ if currentRole != "" && len(currentValue) > 0 {
+ role := tiplMapping[currentRole]
+ tags[role] = append(tags[role], strings.Join(currentValue, " "))
+ }
+ }
+ var currentRole string
+ var currentValue []string
+ for part := range strings.SplitSeq(tipl[0], " ") {
+ if _, ok := tiplMapping[part]; ok {
+ addRole(currentRole, currentValue)
+ currentRole = part
+ currentValue = nil
+ continue
+ }
+ currentValue = append(currentValue, part)
+ }
+ addRole(currentRole, currentValue)
+ delete(tags, "tipl")
+}
+
+var _ local.Extractor = (*extractor)(nil)
+
+func init() {
+ local.RegisterExtractor("taglib", func(fsys fs.FS, baseDir string) local.Extractor {
+ return &extractor{fsys}
+ })
+ conf.AddHook(func() {
+ log.Debug("go-taglib version", "version", extractor{}.Version())
+ })
+}
diff --git a/adapters/gotaglib/gotaglib_suite_test.go b/adapters/gotaglib/gotaglib_suite_test.go
new file mode 100644
index 000000000..cc7ddc471
--- /dev/null
+++ b/adapters/gotaglib/gotaglib_suite_test.go
@@ -0,0 +1,17 @@
+package gotaglib
+
+import (
+ "testing"
+
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+func TestGoTagLib(t *testing.T) {
+ tests.Init(t, true)
+ log.SetLevel(log.LevelFatal)
+ RegisterFailHandler(Fail)
+ RunSpecs(t, "GoTagLib Suite")
+}
diff --git a/adapters/gotaglib/gotaglib_test.go b/adapters/gotaglib/gotaglib_test.go
new file mode 100644
index 000000000..8fdf5b406
--- /dev/null
+++ b/adapters/gotaglib/gotaglib_test.go
@@ -0,0 +1,305 @@
+package gotaglib
+
+import (
+ "io/fs"
+ "os"
+ "strings"
+
+ "github.com/navidrome/navidrome/utils"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Extractor", func() {
+ var e *extractor
+
+ BeforeEach(func() {
+ e = &extractor{fs: os.DirFS(".")}
+ })
+
+ Describe("Parse", func() {
+ It("correctly parses metadata from all files in folder", func() {
+ mds, err := e.Parse(
+ "tests/fixtures/test.mp3",
+ "tests/fixtures/test.ogg",
+ )
+ Expect(err).NotTo(HaveOccurred())
+ Expect(mds).To(HaveLen(2))
+
+ // Test MP3
+ m := mds["tests/fixtures/test.mp3"]
+ Expect(m.Tags).To(HaveKeyWithValue("title", []string{"Song"}))
+ Expect(m.Tags).To(HaveKeyWithValue("album", []string{"Album"}))
+ Expect(m.Tags).To(HaveKeyWithValue("artist", []string{"Artist"}))
+ Expect(m.Tags).To(HaveKeyWithValue("albumartist", []string{"Album Artist"}))
+
+ Expect(m.HasPicture).To(BeTrue())
+ Expect(m.AudioProperties.Duration.String()).To(Equal("1.02s"))
+ Expect(m.AudioProperties.BitRate).To(Equal(192))
+ Expect(m.AudioProperties.Channels).To(Equal(2))
+ Expect(m.AudioProperties.SampleRate).To(Equal(44100))
+
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("compilation", []string{"1"}),
+ HaveKeyWithValue("tcmp", []string{"1"})),
+ )
+ Expect(m.Tags).To(HaveKeyWithValue("genre", []string{"Rock"}))
+ Expect(m.Tags).To(HaveKeyWithValue("date", []string{"2014-05-21"}))
+ Expect(m.Tags).To(HaveKeyWithValue("originaldate", []string{"1996-11-21"}))
+ Expect(m.Tags).To(HaveKeyWithValue("releasedate", []string{"2020-12-31"}))
+ Expect(m.Tags).To(HaveKeyWithValue("discnumber", []string{"1"}))
+ Expect(m.Tags).To(HaveKeyWithValue("disctotal", []string{"2"}))
+ Expect(m.Tags).To(HaveKeyWithValue("comment", []string{"Comment1\nComment2"}))
+ Expect(m.Tags).To(HaveKeyWithValue("bpm", []string{"123"}))
+ Expect(m.Tags).To(HaveKeyWithValue("replaygain_album_gain", []string{"+3.21518 dB"}))
+ Expect(m.Tags).To(HaveKeyWithValue("replaygain_album_peak", []string{"0.9125"}))
+ Expect(m.Tags).To(HaveKeyWithValue("replaygain_track_gain", []string{"-1.48 dB"}))
+ Expect(m.Tags).To(HaveKeyWithValue("replaygain_track_peak", []string{"0.4512"}))
+
+ Expect(m.Tags).To(HaveKeyWithValue("tracknumber", []string{"2"}))
+ Expect(m.Tags).To(HaveKeyWithValue("tracktotal", []string{"10"}))
+
+ Expect(m.Tags).ToNot(HaveKey("lyrics"))
+ Expect(m.Tags).To(Or(HaveKeyWithValue("lyrics:eng", []string{
+ "[00:00.00]This is\n[00:02.50]English SYLT\n",
+ "[00:00.00]This is\n[00:02.50]English",
+ }), HaveKeyWithValue("lyrics:eng", []string{
+ "[00:00.00]This is\n[00:02.50]English",
+ "[00:00.00]This is\n[00:02.50]English SYLT\n",
+ })))
+ Expect(m.Tags).To(Or(HaveKeyWithValue("lyrics:xxx", []string{
+ "[00:00.00]This is\n[00:02.50]unspecified SYLT\n",
+ "[00:00.00]This is\n[00:02.50]unspecified",
+ }), HaveKeyWithValue("lyrics:xxx", []string{
+ "[00:00.00]This is\n[00:02.50]unspecified",
+ "[00:00.00]This is\n[00:02.50]unspecified SYLT\n",
+ })))
+
+ // Test OGG
+ m = mds["tests/fixtures/test.ogg"]
+ Expect(err).To(BeNil())
+ Expect(m.Tags).To(HaveKeyWithValue("fbpm", []string{"141.7"}))
+
+ // TagLib 1.12 returns 18, previous versions return 39.
+ // See https://github.com/taglib/taglib/commit/2f238921824741b2cfe6fbfbfc9701d9827ab06b
+ Expect(m.AudioProperties.BitRate).To(BeElementOf(18, 19, 39, 40, 43, 49))
+ Expect(m.AudioProperties.Channels).To(BeElementOf(2))
+ Expect(m.AudioProperties.SampleRate).To(BeElementOf(8000))
+ Expect(m.HasPicture).To(BeTrue())
+ })
+
+ DescribeTable("Format-Specific tests",
+ func(file, duration string, channels, samplerate, bitdepth int, albumGain, albumPeak, trackGain, trackPeak string, id3Lyrics bool, image bool) {
+ file = "tests/fixtures/" + file
+ mds, err := e.Parse(file)
+ Expect(err).NotTo(HaveOccurred())
+ Expect(mds).To(HaveLen(1))
+
+ m := mds[file]
+
+ Expect(m.HasPicture).To(Equal(image))
+ Expect(m.AudioProperties.Duration.String()).To(Equal(duration))
+ Expect(m.AudioProperties.Channels).To(Equal(channels))
+ Expect(m.AudioProperties.SampleRate).To(Equal(samplerate))
+ Expect(m.AudioProperties.BitDepth).To(Equal(bitdepth))
+
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("replaygain_album_gain", []string{albumGain}),
+ HaveKeyWithValue("----:com.apple.itunes:replaygain_album_gain", []string{albumGain}),
+ ))
+
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("replaygain_album_peak", []string{albumPeak}),
+ HaveKeyWithValue("----:com.apple.itunes:replaygain_album_peak", []string{albumPeak}),
+ ))
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("replaygain_track_gain", []string{trackGain}),
+ HaveKeyWithValue("----:com.apple.itunes:replaygain_track_gain", []string{trackGain}),
+ ))
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("replaygain_track_peak", []string{trackPeak}),
+ HaveKeyWithValue("----:com.apple.itunes:replaygain_track_peak", []string{trackPeak}),
+ ))
+
+ Expect(m.Tags).To(HaveKeyWithValue("title", []string{"Title"}))
+ Expect(m.Tags).To(HaveKeyWithValue("album", []string{"Album"}))
+ Expect(m.Tags).To(HaveKeyWithValue("artist", []string{"Artist"}))
+ Expect(m.Tags).To(HaveKeyWithValue("albumartist", []string{"Album Artist"}))
+ Expect(m.Tags).To(HaveKeyWithValue("genre", []string{"Rock"}))
+ Expect(m.Tags).To(HaveKeyWithValue("date", []string{"2014"}))
+
+ Expect(m.Tags).To(HaveKeyWithValue("bpm", []string{"123"}))
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("tracknumber", []string{"3"}),
+ HaveKeyWithValue("tracknumber", []string{"3/10"}),
+ ))
+ if !strings.HasSuffix(file, "test.wma") {
+ // TODO Not sure why this is not working for WMA
+ Expect(m.Tags).To(HaveKeyWithValue("tracktotal", []string{"10"}))
+ }
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("discnumber", []string{"1"}),
+ HaveKeyWithValue("discnumber", []string{"1/2"}),
+ ))
+ Expect(m.Tags).To(HaveKeyWithValue("disctotal", []string{"2"}))
+
+ // WMA does not have a "compilation" tag, but "wm/iscompilation"
+ Expect(m.Tags).To(Or(
+ HaveKeyWithValue("compilation", []string{"1"}),
+ HaveKeyWithValue("wm/iscompilation", []string{"1"})),
+ )
+
+ if id3Lyrics {
+ Expect(m.Tags).To(HaveKeyWithValue("lyrics:eng", []string{
+ "[00:00.00]This is\n[00:02.50]English",
+ }))
+ Expect(m.Tags).To(HaveKeyWithValue("lyrics:xxx", []string{
+ "[00:00.00]This is\n[00:02.50]unspecified",
+ }))
+ } else {
+ Expect(m.Tags).To(HaveKeyWithValue("lyrics:xxx", []string{
+ "[00:00.00]This is\n[00:02.50]unspecified",
+ "[00:00.00]This is\n[00:02.50]English",
+ }))
+ }
+
+ Expect(m.Tags).To(HaveKeyWithValue("comment", []string{"Comment1\nComment2"}))
+ },
+
+ // ffmpeg -f lavfi -i "sine=frequency=1200:duration=1" test.flac
+ Entry("correctly parses flac tags", "test.flac", "1s", 1, 44100, 16, "+4.06 dB", "0.12496948", "+4.06 dB", "0.12496948", false, true),
+
+ Entry("correctly parses m4a (aac) gain tags", "01 Invisible (RED) Edit Version.m4a", "1.04s", 2, 44100, 16, "0.37", "0.48", "0.37", "0.48", false, true),
+ Entry("correctly parses m4a (aac) gain tags (uppercase)", "test.m4a", "1.04s", 2, 44100, 16, "0.37", "0.48", "0.37", "0.48", false, true),
+ Entry("correctly parses ogg (vorbis) tags", "test.ogg", "1.04s", 2, 8000, 0, "+7.64 dB", "0.11772506", "+7.64 dB", "0.11772506", false, true),
+
+ // ffmpeg -f lavfi -i "sine=frequency=1100:duration=1" -c:a libopus test.opus (tags added via mutagen)
+ Entry("correctly parses opus tags (#4998)", "test.opus", "1s", 1, 48000, 0, "+5.12 dB", "0.11345678", "+5.12 dB", "0.11345678", false, true),
+
+ // ffmpeg -f lavfi -i "sine=frequency=900:duration=1" test.wma
+ // Weird note: for the tag parsing to work, the lyrics are actually stored in the reverse order
+ Entry("correctly parses wma/asf tags", "test.wma", "1.02s", 1, 44100, 16, "3.27 dB", "0.132914", "3.27 dB", "0.132914", false, true),
+
+ // ffmpeg -f lavfi -i "sine=frequency=800:duration=1" test.wv
+ Entry("correctly parses wv (wavpak) tags", "test.wv", "1s", 1, 44100, 16, "3.43 dB", "0.125061", "3.43 dB", "0.125061", false, true),
+
+ // ffmpeg -f lavfi -i "sine=frequency=1000:duration=1" test.wav
+ Entry("correctly parses wav tags", "test.wav", "1s", 1, 44100, 16, "3.06 dB", "0.125056", "3.06 dB", "0.125056", true, true),
+
+ // ffmpeg -f lavfi -i "sine=frequency=1400:duration=1" test.aiff
+ Entry("correctly parses aiff tags", "test.aiff", "1s", 1, 44100, 16, "2.00 dB", "0.124972", "2.00 dB", "0.124972", true, true),
+ )
+
+ // Skip these tests when running as root
+ Context("Access Forbidden", func() {
+ var accessForbiddenFile string
+ var RegularUserContext = XContext
+ var isRegularUser = os.Getuid() != 0
+ if isRegularUser {
+ RegularUserContext = Context
+ }
+
+ // Only run permission tests if we are not root
+ RegularUserContext("when run without root privileges", func() {
+ BeforeEach(func() {
+ // Use root fs for absolute paths in temp directory
+ e = &extractor{fs: os.DirFS("/")}
+ accessForbiddenFile = utils.TempFileName("access_forbidden-", ".mp3")
+
+ f, err := os.OpenFile(accessForbiddenFile, os.O_WRONLY|os.O_CREATE, 0222)
+ Expect(err).ToNot(HaveOccurred())
+
+ DeferCleanup(func() {
+ Expect(f.Close()).To(Succeed())
+ Expect(os.Remove(accessForbiddenFile)).To(Succeed())
+ })
+ })
+
+ It("correctly handle unreadable file due to insufficient read permission", func() {
+ // Strip leading slash for DirFS rooted at "/"
+ _, err := e.extractMetadata(accessForbiddenFile[1:])
+ Expect(err).To(MatchError(os.ErrPermission))
+ })
+
+ It("skips the file if it cannot be read", func() {
+ // Get current working directory to construct paths relative to root
+ cwd, err := os.Getwd()
+ Expect(err).ToNot(HaveOccurred())
+ // Strip leading slash for DirFS rooted at "/"
+ files := []string{
+ cwd[1:] + "/tests/fixtures/test.mp3",
+ cwd[1:] + "/tests/fixtures/test.ogg",
+ accessForbiddenFile[1:],
+ }
+ mds, err := e.Parse(files...)
+ Expect(err).NotTo(HaveOccurred())
+ Expect(mds).To(HaveLen(2))
+ Expect(mds).ToNot(HaveKey(accessForbiddenFile[1:]))
+ })
+ })
+ })
+
+ })
+
+ Describe("Error Checking", func() {
+ It("returns a generic ErrPath if file does not exist", func() {
+ testFilePath := "tests/fixtures/NON_EXISTENT.ogg"
+ _, err := e.extractMetadata(testFilePath)
+ Expect(err).To(MatchError(fs.ErrNotExist))
+ })
+ It("does not throw a SIGSEGV error when reading a file with an invalid frame", func() {
+ // File has an empty TDAT frame
+ md, err := e.extractMetadata("tests/fixtures/invalid-files/test-invalid-frame.mp3")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(md.Tags).To(HaveKeyWithValue("albumartist", []string{"Elvis Presley"}))
+ })
+ })
+
+ Describe("parseTIPL", func() {
+ var tags map[string][]string
+
+ BeforeEach(func() {
+ tags = make(map[string][]string)
+ })
+
+ Context("when the TIPL string is populated", func() {
+ It("correctly parses roles and names", func() {
+ tags["tipl"] = []string{"arranger Andrew Powell DJ-mix François Kevorkian DJ-mix Jane Doe engineer Chris Blair"}
+ parseTIPL(tags)
+ Expect(tags["arranger"]).To(ConsistOf("Andrew Powell"))
+ Expect(tags["engineer"]).To(ConsistOf("Chris Blair"))
+ Expect(tags["djmixer"]).To(ConsistOf("François Kevorkian", "Jane Doe"))
+ })
+
+ It("handles multiple names for a single role", func() {
+ tags["tipl"] = []string{"engineer Pat Stapley producer Eric Woolfson engineer Chris Blair"}
+ parseTIPL(tags)
+ Expect(tags["producer"]).To(ConsistOf("Eric Woolfson"))
+ Expect(tags["engineer"]).To(ConsistOf("Pat Stapley", "Chris Blair"))
+ })
+
+ It("discards roles without names", func() {
+ tags["tipl"] = []string{"engineer Pat Stapley producer engineer Chris Blair"}
+ parseTIPL(tags)
+ Expect(tags).ToNot(HaveKey("producer"))
+ Expect(tags["engineer"]).To(ConsistOf("Pat Stapley", "Chris Blair"))
+ })
+ })
+
+ Context("when the TIPL string is empty", func() {
+ It("does nothing", func() {
+ tags["tipl"] = []string{""}
+ parseTIPL(tags)
+ Expect(tags).To(BeEmpty())
+ })
+ })
+
+ Context("when the TIPL is not present", func() {
+ It("does nothing", func() {
+ parseTIPL(tags)
+ Expect(tags).To(BeEmpty())
+ })
+ })
+ })
+
+})
diff --git a/core/agents/lastfm/agent.go b/adapters/lastfm/agent.go
similarity index 68%
rename from core/agents/lastfm/agent.go
rename to adapters/lastfm/agent.go
index d01b496ec..b3e89a9dc 100644
--- a/core/agents/lastfm/agent.go
+++ b/adapters/lastfm/agent.go
@@ -26,18 +26,25 @@ const (
sessionKeyProperty = "LastFMSessionKey"
)
-var ignoredBiographies = []string{
- // Unknown Artist
+var ignoredContent = []string{
+ // Empty Artist/Album
`Read more on Last\.fm\.?`)
+
+func cleanContent(content string) string {
+ return strings.TrimSpace(lastFMReadMoreRegex.ReplaceAllString(content, ""))
+}
+
type lastfmAgent struct {
ds model.DataStore
sessionKeys *agents.SessionKeys
apiKey string
secret string
- lang string
+ languages []string
client *client
+ httpClient httpDoer
getInfoMutex sync.Mutex
}
@@ -47,7 +54,7 @@ func lastFMConstructor(ds model.DataStore) *lastfmAgent {
}
l := &lastfmAgent{
ds: ds,
- lang: conf.Server.LastFM.Language,
+ languages: conf.Server.LastFM.Languages,
apiKey: conf.Server.LastFM.ApiKey,
secret: conf.Server.LastFM.Secret,
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
@@ -56,7 +63,8 @@ func lastFMConstructor(ds model.DataStore) *lastfmAgent {
Timeout: consts.DefaultHttpClientTimeOut,
}
chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
- l.client = newClient(l.apiKey, l.secret, l.lang, chc)
+ l.httpClient = chc
+ l.client = newClient(l.apiKey, l.secret, chc)
return l
}
@@ -66,22 +74,47 @@ func (l *lastfmAgent) AgentName() string {
var imageRegex = regexp.MustCompile(`u\/(\d+)`)
-func (l *lastfmAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid string) (*agents.AlbumInfo, error) {
- a, err := l.callAlbumGetInfo(ctx, name, artist, mbid)
- if err != nil {
- return nil, err
+// isValidContent checks if content is non-empty and not in the ignored list
+func isValidContent(content string) bool {
+ content = strings.TrimSpace(content)
+ if content == "" {
+ return false
}
+ for _, ign := range ignoredContent {
+ if strings.HasPrefix(content, ign) {
+ return false
+ }
+ }
+ return true
+}
- return &agents.AlbumInfo{
- Name: a.Name,
- MBID: a.MBID,
- Description: a.Description.Summary,
- URL: a.URL,
- }, nil
+func (l *lastfmAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid string) (*agents.AlbumInfo, error) {
+ var a *Album
+ var resp agents.AlbumInfo
+ for _, lang := range l.languages {
+ var err error
+ a, err = l.callAlbumGetInfo(ctx, name, artist, mbid, lang)
+ if err != nil {
+ return nil, err
+ }
+ resp.Name = a.Name
+ resp.MBID = a.MBID
+ resp.URL = a.URL
+ if isValidContent(a.Description.Summary) {
+ resp.Description = cleanContent(a.Description.Summary)
+ return &resp, nil
+ }
+ log.Debug(ctx, "LastFM/album.getInfo returned empty/ignored description, trying next language", "album", name, "artist", artist, "lang", lang)
+ }
+ // This condition should not be hit (languages default to ["en"]), but just in case
+ if a == nil {
+ return nil, agents.ErrNotFound
+ }
+ return &resp, nil
}
func (l *lastfmAgent) GetAlbumImages(ctx context.Context, name, artist, mbid string) ([]agents.ExternalImage, error) {
- a, err := l.callAlbumGetInfo(ctx, name, artist, mbid)
+ a, err := l.callAlbumGetInfo(ctx, name, artist, mbid, l.languages[0])
if err != nil {
return nil, err
}
@@ -116,7 +149,7 @@ func (l *lastfmAgent) GetAlbumImages(ctx context.Context, name, artist, mbid str
}
func (l *lastfmAgent) GetArtistMBID(ctx context.Context, id string, name string) (string, error) {
- a, err := l.callArtistGetInfo(ctx, name)
+ a, err := l.callArtistGetInfo(ctx, name, l.languages[0])
if err != nil {
return "", err
}
@@ -127,7 +160,7 @@ func (l *lastfmAgent) GetArtistMBID(ctx context.Context, id string, name string)
}
func (l *lastfmAgent) GetArtistURL(ctx context.Context, id, name, mbid string) (string, error) {
- a, err := l.callArtistGetInfo(ctx, name)
+ a, err := l.callArtistGetInfo(ctx, name, l.languages[0])
if err != nil {
return "", err
}
@@ -138,20 +171,17 @@ func (l *lastfmAgent) GetArtistURL(ctx context.Context, id, name, mbid string) (
}
func (l *lastfmAgent) GetArtistBiography(ctx context.Context, id, name, mbid string) (string, error) {
- a, err := l.callArtistGetInfo(ctx, name)
- if err != nil {
- return "", err
- }
- a.Bio.Summary = strings.TrimSpace(a.Bio.Summary)
- if a.Bio.Summary == "" {
- return "", agents.ErrNotFound
- }
- for _, ign := range ignoredBiographies {
- if strings.HasPrefix(a.Bio.Summary, ign) {
- return "", nil
+ for _, lang := range l.languages {
+ a, err := l.callArtistGetInfo(ctx, name, lang)
+ if err != nil {
+ return "", err
}
+ if isValidContent(a.Bio.Summary) {
+ return cleanContent(a.Bio.Summary), nil
+ }
+ log.Debug(ctx, "LastFM/artist.getInfo returned empty/ignored biography, trying next language", "artist", name, "lang", lang)
}
- return a.Bio.Summary, nil
+ return "", agents.ErrNotFound
}
func (l *lastfmAgent) GetSimilarArtists(ctx context.Context, id, name, mbid string, limit int) ([]agents.Artist, error) {
@@ -190,14 +220,34 @@ func (l *lastfmAgent) GetArtistTopSongs(ctx context.Context, id, artistName, mbi
return res, nil
}
-var artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
+func (l *lastfmAgent) GetSimilarSongsByTrack(ctx context.Context, id, name, artist, mbid string, count int) ([]agents.Song, error) {
+ resp, err := l.callTrackGetSimilar(ctx, name, artist, count)
+ if err != nil {
+ return nil, err
+ }
+ if len(resp) == 0 {
+ return nil, agents.ErrNotFound
+ }
+ res := make([]agents.Song, 0, len(resp))
+ for _, t := range resp {
+ res = append(res, agents.Song{
+ Name: t.Name,
+ MBID: t.MBID,
+ Artist: t.Artist.Name,
+ ArtistMBID: t.Artist.MBID,
+ })
+ }
+ return res, nil
+}
+
+var (
+ artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
+ artistIgnoredImage = "2a96cbd8b46e442fc41c2b86b821562f" // Last.fm artist placeholder image name
+)
func (l *lastfmAgent) GetArtistImages(ctx context.Context, _, name, mbid string) ([]agents.ExternalImage, error) {
log.Debug(ctx, "Getting artist images from Last.fm", "name", name)
- hc := http.Client{
- Timeout: consts.DefaultHttpClientTimeOut,
- }
- a, err := l.callArtistGetInfo(ctx, name)
+ a, err := l.callArtistGetInfo(ctx, name, l.languages[0])
if err != nil {
return nil, fmt.Errorf("get artist info: %w", err)
}
@@ -205,7 +255,7 @@ func (l *lastfmAgent) GetArtistImages(ctx context.Context, _, name, mbid string)
if err != nil {
return nil, fmt.Errorf("create artist image request: %w", err)
}
- resp, err := hc.Do(req)
+ resp, err := l.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("get artist url: %w", err)
}
@@ -222,24 +272,29 @@ func (l *lastfmAgent) GetArtistImages(ctx context.Context, _, name, mbid string)
return res, nil
}
for _, attr := range n.Attr {
- if attr.Key == "content" {
- res = []agents.ExternalImage{
- {URL: attr.Val},
- }
- break
+ if attr.Key != "content" {
+ continue
+ }
+ if strings.Contains(attr.Val, artistIgnoredImage) {
+ log.Debug(ctx, "Artist image is ignored default image", "name", name, "url", attr.Val)
+ return res, nil
+ }
+
+ res = []agents.ExternalImage{
+ {URL: attr.Val},
}
}
return res, nil
}
-func (l *lastfmAgent) callAlbumGetInfo(ctx context.Context, name, artist, mbid string) (*Album, error) {
- a, err := l.client.albumGetInfo(ctx, name, artist, mbid)
+func (l *lastfmAgent) callAlbumGetInfo(ctx context.Context, name, artist, mbid string, lang string) (*Album, error) {
+ a, err := l.client.albumGetInfo(ctx, name, artist, mbid, lang)
var lfErr *lastFMError
isLastFMError := errors.As(err, &lfErr)
if mbid != "" && (isLastFMError && lfErr.Code == 6) {
log.Debug(ctx, "LastFM/album.getInfo could not find album by mbid, trying again", "album", name, "mbid", mbid)
- return l.callAlbumGetInfo(ctx, name, artist, "")
+ return l.callAlbumGetInfo(ctx, name, artist, "", lang)
}
if err != nil {
@@ -253,11 +308,11 @@ func (l *lastfmAgent) callAlbumGetInfo(ctx context.Context, name, artist, mbid s
return a, nil
}
-func (l *lastfmAgent) callArtistGetInfo(ctx context.Context, name string) (*Artist, error) {
+func (l *lastfmAgent) callArtistGetInfo(ctx context.Context, name string, lang string) (*Artist, error) {
l.getInfoMutex.Lock()
defer l.getInfoMutex.Unlock()
- a, err := l.client.artistGetInfo(ctx, name)
+ a, err := l.client.artistGetInfo(ctx, name, lang)
if err != nil {
log.Error(ctx, "Error calling LastFM/artist.getInfo", "artist", name, err)
return nil, err
@@ -283,11 +338,20 @@ func (l *lastfmAgent) callArtistGetTopTracks(ctx context.Context, artistName str
return t.Track, nil
}
-func (l *lastfmAgent) getArtistForScrobble(track *model.MediaFile) string {
- if conf.Server.LastFM.ScrobbleFirstArtistOnly && len(track.Participants[model.RoleArtist]) > 0 {
- return track.Participants[model.RoleArtist][0].Name
+func (l *lastfmAgent) callTrackGetSimilar(ctx context.Context, name, artist string, count int) ([]SimilarTrack, error) {
+ s, err := l.client.trackGetSimilar(ctx, name, artist, count)
+ if err != nil {
+ log.Error(ctx, "Error calling LastFM/track.getSimilar", "track", name, "artist", artist, err)
+ return nil, err
}
- return track.Artist
+ return s.Track, nil
+}
+
+func (l *lastfmAgent) getArtistForScrobble(track *model.MediaFile, role model.Role, displayName string) string {
+ if conf.Server.LastFM.ScrobbleFirstArtistOnly && len(track.Participants[role]) > 0 {
+ return track.Participants[role][0].Name
+ }
+ return displayName
}
func (l *lastfmAgent) NowPlaying(ctx context.Context, userId string, track *model.MediaFile, position int) error {
@@ -297,13 +361,13 @@ func (l *lastfmAgent) NowPlaying(ctx context.Context, userId string, track *mode
}
err = l.client.updateNowPlaying(ctx, sk, ScrobbleInfo{
- artist: l.getArtistForScrobble(track),
+ artist: l.getArtistForScrobble(track, model.RoleArtist, track.Artist),
track: track.Title,
album: track.Album,
trackNumber: track.TrackNumber,
mbid: track.MbzRecordingID,
duration: int(track.Duration),
- albumArtist: track.AlbumArtist,
+ albumArtist: l.getArtistForScrobble(track, model.RoleAlbumArtist, track.AlbumArtist),
})
if err != nil {
log.Warn(ctx, "Last.fm client.updateNowPlaying returned error", "track", track.Title, err)
@@ -323,13 +387,13 @@ func (l *lastfmAgent) Scrobble(ctx context.Context, userId string, s scrobbler.S
return nil
}
err = l.client.scrobble(ctx, sk, ScrobbleInfo{
- artist: l.getArtistForScrobble(&s.MediaFile),
+ artist: l.getArtistForScrobble(&s.MediaFile, model.RoleArtist, s.Artist),
track: s.Title,
album: s.Album,
trackNumber: s.TrackNumber,
mbid: s.MbzRecordingID,
duration: int(s.Duration),
- albumArtist: s.AlbumArtist,
+ albumArtist: l.getArtistForScrobble(&s.MediaFile, model.RoleAlbumArtist, s.AlbumArtist),
timestamp: s.TimeStamp,
})
if err == nil {
diff --git a/core/agents/lastfm/agent_test.go b/adapters/lastfm/agent_test.go
similarity index 55%
rename from core/agents/lastfm/agent_test.go
rename to adapters/lastfm/agent_test.go
index 4476d592f..94788b8bd 100644
--- a/core/agents/lastfm/agent_test.go
+++ b/adapters/lastfm/agent_test.go
@@ -6,6 +6,7 @@ import (
"errors"
"io"
"net/http"
+ "net/url"
"os"
"strconv"
"time"
@@ -38,12 +39,12 @@ var _ = Describe("lastfmAgent", func() {
})
Describe("lastFMConstructor", func() {
When("Agent is properly configured", func() {
- It("uses configured api key and language", func() {
- conf.Server.LastFM.Language = "pt"
+ It("uses configured api key and languages", func() {
+ conf.Server.LastFM.Languages = []string{"pt", "en"}
agent := lastFMConstructor(ds)
Expect(agent.apiKey).To(Equal("123"))
Expect(agent.secret).To(Equal("secret"))
- Expect(agent.lang).To(Equal("pt"))
+ Expect(agent.languages).To(Equal([]string{"pt", "en"}))
})
})
When("Agent is disabled", func() {
@@ -71,7 +72,7 @@ var _ = Describe("lastfmAgent", func() {
var httpClient *tests.FakeHttpClient
BeforeEach(func() {
httpClient = &tests.FakeHttpClient{}
- client := newClient("API_KEY", "SECRET", "pt", httpClient)
+ client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds)
agent.client = client
})
@@ -79,7 +80,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns the biography", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
- Expect(agent.GetArtistBiography(ctx, "123", "U2", "")).To(Equal("U2 é uma das mais importantes bandas de rock de todos os tempos. Formada em 1976 em Dublin, composta por Bono (vocalista e guitarrista), The Edge (guitarrista, pianista e backing vocal), Adam Clayton (baixista), Larry Mullen, Jr. (baterista e percussionista).\n\nDesde a década de 80, U2 é uma das bandas mais populares no mundo. Seus shows são únicos e um verdadeiro festival de efeitos especiais, além de serem um dos que mais arrecadam anualmente. Read more on Last.fm"))
+ Expect(agent.GetArtistBiography(ctx, "123", "U2", "")).To(Equal("U2 é uma das mais importantes bandas de rock de todos os tempos. Formada em 1976 em Dublin, composta por Bono (vocalista e guitarrista), The Edge (guitarrista, pianista e backing vocal), Adam Clayton (baixista), Larry Mullen, Jr. (baterista e percussionista).\n\nDesde a década de 80, U2 é uma das bandas mais populares no mundo. Seus shows são únicos e um verdadeiro festival de efeitos especiais, além de serem um dos que mais arrecadam anualmente."))
Expect(httpClient.RequestCount).To(Equal(1))
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2"))
})
@@ -101,12 +102,129 @@ var _ = Describe("lastfmAgent", func() {
})
})
+ Describe("Language Fallback", func() {
+ Describe("GetArtistBiography", func() {
+ var agent *lastfmAgent
+ var httpClient *langAwareHttpClient
+
+ BeforeEach(func() {
+ httpClient = newLangAwareHttpClient()
+ })
+
+ It("returns content in first language when available (1 API call)", func() {
+ conf.Server.LastFM.Languages = []string{"pt", "en"}
+ agent = lastFMConstructor(ds)
+ agent.client = newClient("API_KEY", "SECRET", httpClient)
+
+ // Portuguese biography available
+ f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
+ httpClient.responses["pt"] = http.Response{Body: f, StatusCode: 200}
+
+ bio, err := agent.GetArtistBiography(ctx, "123", "U2", "")
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(bio).To(ContainSubstring("U2 é uma das mais importantes bandas de rock"))
+ Expect(httpClient.requestCount).To(Equal(1))
+ Expect(httpClient.requests[0].URL.Query().Get("lang")).To(Equal("pt"))
+ })
+
+ It("falls back to second language when first returns empty (2 API calls)", func() {
+ conf.Server.LastFM.Languages = []string{"ja", "en"}
+ agent = lastFMConstructor(ds)
+ agent.client = newClient("API_KEY", "SECRET", httpClient)
+
+ // Japanese returns empty/ignored biography (actual Last.fm response with just "Read more" link)
+ fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
+ httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
+ // English returns full biography
+ fEn, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.en.json")
+ httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
+
+ bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(bio).To(ContainSubstring("Legião Urbana was a Brazilian post-punk band"))
+ Expect(httpClient.requestCount).To(Equal(2))
+ Expect(httpClient.requests[0].URL.Query().Get("lang")).To(Equal("ja"))
+ Expect(httpClient.requests[1].URL.Query().Get("lang")).To(Equal("en"))
+ })
+
+ It("returns ErrNotFound when all languages return empty", func() {
+ conf.Server.LastFM.Languages = []string{"ja", "xx"}
+ agent = lastFMConstructor(ds)
+ agent.client = newClient("API_KEY", "SECRET", httpClient)
+
+ // Both languages return empty/ignored biography (using actual Last.fm response format)
+ fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
+ httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
+ // Second language also returns empty
+ fXx, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
+ httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
+
+ _, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
+
+ Expect(err).To(MatchError(agents.ErrNotFound))
+ Expect(httpClient.requestCount).To(Equal(2))
+ })
+ })
+
+ Describe("GetAlbumInfo", func() {
+ var agent *lastfmAgent
+ var httpClient *langAwareHttpClient
+
+ BeforeEach(func() {
+ httpClient = newLangAwareHttpClient()
+ })
+
+ It("falls back to second language when first returns empty description (2 API calls)", func() {
+ conf.Server.LastFM.Languages = []string{"ja", "en"}
+ agent = lastFMConstructor(ds)
+ agent.client = newClient("API_KEY", "SECRET", httpClient)
+
+ // Japanese returns album without wiki/description (actual Last.fm response)
+ fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
+ httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
+ // English returns album with description
+ fEn, _ := os.Open("tests/fixtures/lastfm.album.getinfo.en.json")
+ httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
+
+ albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(albumInfo.Name).To(Equal("Dois"))
+ Expect(albumInfo.Description).To(ContainSubstring("segundo álbum de estúdio"))
+ Expect(httpClient.requestCount).To(Equal(2))
+ Expect(httpClient.requests[0].URL.Query().Get("lang")).To(Equal("ja"))
+ Expect(httpClient.requests[1].URL.Query().Get("lang")).To(Equal("en"))
+ })
+
+ It("returns album without description when all languages return empty", func() {
+ conf.Server.LastFM.Languages = []string{"ja", "xx"}
+ agent = lastFMConstructor(ds)
+ agent.client = newClient("API_KEY", "SECRET", httpClient)
+
+ // Both languages return album without description
+ fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
+ httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
+ fXx, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
+ httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
+
+ albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(albumInfo.Name).To(Equal("Dois"))
+ Expect(albumInfo.Description).To(BeEmpty())
+ Expect(httpClient.requestCount).To(Equal(2))
+ })
+ })
+ })
+
Describe("GetSimilarArtists", func() {
var agent *lastfmAgent
var httpClient *tests.FakeHttpClient
BeforeEach(func() {
httpClient = &tests.FakeHttpClient{}
- client := newClient("API_KEY", "SECRET", "pt", httpClient)
+ client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds)
agent.client = client
})
@@ -144,7 +262,7 @@ var _ = Describe("lastfmAgent", func() {
var httpClient *tests.FakeHttpClient
BeforeEach(func() {
httpClient = &tests.FakeHttpClient{}
- client := newClient("API_KEY", "SECRET", "pt", httpClient)
+ client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds)
agent.client = client
})
@@ -177,6 +295,54 @@ var _ = Describe("lastfmAgent", func() {
})
})
+ Describe("GetSimilarSongsByTrack", func() {
+ var agent *lastfmAgent
+ var httpClient *tests.FakeHttpClient
+ BeforeEach(func() {
+ httpClient = &tests.FakeHttpClient{}
+ client := newClient("API_KEY", "SECRET", httpClient)
+ agent = lastFMConstructor(ds)
+ agent.client = client
+ })
+
+ It("returns similar songs", func() {
+ f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ Expect(agent.GetSimilarSongsByTrack(ctx, "123", "Just Can't Get Enough", "Depeche Mode", "", 5)).To(Equal([]agents.Song{
+ {Name: "Dreaming of Me", MBID: "027b553e-7c74-3ed4-a95e-1d4fea51f174", Artist: "Depeche Mode", ArtistMBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"},
+ {Name: "Everything Counts", MBID: "5a5a3ca4-bdb8-4641-a674-9b54b9b319a6", Artist: "Depeche Mode", ArtistMBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"},
+ {Name: "Don't You Want Me", MBID: "", Artist: "The Human League", ArtistMBID: "7adaabfb-acfb-47bc-8c7c-59471c2f0db8"},
+ {Name: "Tainted Love", MBID: "", Artist: "Soft Cell", ArtistMBID: "7fb50287-029d-47cc-825a-235ca28024b2"},
+ {Name: "Blue Monday", MBID: "727e84c6-1b56-31dd-a958-a5f46305cec0", Artist: "New Order", ArtistMBID: "f1106b17-dcbb-45f6-b938-199ccfab50cc"},
+ }))
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.Query().Get("track")).To(Equal("Just Can't Get Enough"))
+ Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Depeche Mode"))
+ })
+
+ It("returns ErrNotFound when no similar songs found", func() {
+ f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ _, err := agent.GetSimilarSongsByTrack(ctx, "123", "UnknownTrack", "UnknownArtist", "", 3)
+ Expect(err).To(MatchError(agents.ErrNotFound))
+ Expect(httpClient.RequestCount).To(Equal(1))
+ })
+
+ It("returns an error if Last.fm call fails", func() {
+ httpClient.Err = errors.New("error")
+ _, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ })
+
+ It("returns an error if Last.fm call returns an error", func() {
+ httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
+ _, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ })
+ })
+
Describe("Scrobbling", func() {
var agent *lastfmAgent
var httpClient *tests.FakeHttpClient
@@ -184,7 +350,7 @@ var _ = Describe("lastfmAgent", func() {
BeforeEach(func() {
_ = ds.UserProps(ctx).Put("user-1", sessionKeyProperty, "SK-1")
httpClient = &tests.FakeHttpClient{}
- client := newClient("API_KEY", "SECRET", "en", httpClient)
+ client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds)
agent.client = client
track = &model.MediaFile{
@@ -201,6 +367,10 @@ var _ = Describe("lastfmAgent", func() {
{Artist: model.Artist{ID: "ar-1", Name: "First Artist"}},
{Artist: model.Artist{ID: "ar-2", Name: "Second Artist"}},
},
+ model.RoleAlbumArtist: []model.Participant{
+ {Artist: model.Artist{ID: "ar-1", Name: "First Album Artist"}},
+ {Artist: model.Artist{ID: "ar-2", Name: "Second Album Artist"}},
+ },
},
}
})
@@ -213,7 +383,8 @@ var _ = Describe("lastfmAgent", func() {
Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
- sentParams := httpClient.SavedRequest.URL.Query()
+ body, _ := io.ReadAll(httpClient.SavedRequest.Body)
+ sentParams, _ := url.ParseQuery(string(body))
Expect(sentParams.Get("method")).To(Equal("track.updateNowPlaying"))
Expect(sentParams.Get("sk")).To(Equal("SK-1"))
Expect(sentParams.Get("track")).To(Equal(track.Title))
@@ -229,6 +400,24 @@ var _ = Describe("lastfmAgent", func() {
err := agent.NowPlaying(ctx, "user-2", track, 0)
Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
})
+
+ When("ScrobbleFirstArtistOnly is true", func() {
+ BeforeEach(func() {
+ conf.Server.LastFM.ScrobbleFirstArtistOnly = true
+ })
+
+ It("uses only the first artist", func() {
+ httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
+
+ err := agent.NowPlaying(ctx, "user-1", track, 0)
+
+ Expect(err).ToNot(HaveOccurred())
+ body, _ := io.ReadAll(httpClient.SavedRequest.Body)
+ sentParams, _ := url.ParseQuery(string(body))
+ Expect(sentParams.Get("artist")).To(Equal("First Artist"))
+ Expect(sentParams.Get("albumArtist")).To(Equal("First Album Artist"))
+ })
+ })
})
Describe("scrobble", func() {
@@ -240,7 +429,8 @@ var _ = Describe("lastfmAgent", func() {
Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
- sentParams := httpClient.SavedRequest.URL.Query()
+ body, _ := io.ReadAll(httpClient.SavedRequest.Body)
+ sentParams, _ := url.ParseQuery(string(body))
Expect(sentParams.Get("method")).To(Equal("track.scrobble"))
Expect(sentParams.Get("sk")).To(Equal("SK-1"))
Expect(sentParams.Get("track")).To(Equal(track.Title))
@@ -265,8 +455,10 @@ var _ = Describe("lastfmAgent", func() {
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
Expect(err).ToNot(HaveOccurred())
- sentParams := httpClient.SavedRequest.URL.Query()
+ body, _ := io.ReadAll(httpClient.SavedRequest.Body)
+ sentParams, _ := url.ParseQuery(string(body))
Expect(sentParams.Get("artist")).To(Equal("First Artist"))
+ Expect(sentParams.Get("albumArtist")).To(Equal("First Album Artist"))
})
})
@@ -332,7 +524,7 @@ var _ = Describe("lastfmAgent", func() {
var httpClient *tests.FakeHttpClient
BeforeEach(func() {
httpClient = &tests.FakeHttpClient{}
- client := newClient("API_KEY", "SECRET", "pt", httpClient)
+ client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds)
agent.client = client
})
@@ -343,7 +535,7 @@ var _ = Describe("lastfmAgent", func() {
Expect(agent.GetAlbumInfo(ctx, "Believe", "Cher", "03c91c40-49a6-44a7-90e7-a700edf97a62")).To(Equal(&agents.AlbumInfo{
Name: "Believe",
MBID: "03c91c40-49a6-44a7-90e7-a700edf97a62",
- Description: "Believe is the twenty-third studio album by American singer-actress Cher, released on November 10, 1998 by Warner Bros. Records. The RIAA certified it Quadruple Platinum on December 23, 1999, recognizing four million shipments in the United States; Worldwide, the album has sold more than 20 million copies, making it the biggest-selling album of her career. In 1999 the album received three Grammy Awards nominations including \"Record of the Year\", \"Best Pop Album\" and winning \"Best Dance Recording\" for the single \"Believe\". It was released by Warner Bros. Records at the end of 1998. The album was executive produced by Rob Read more on Last.fm.",
+ Description: "Believe is the twenty-third studio album by American singer-actress Cher, released on November 10, 1998 by Warner Bros. Records. The RIAA certified it Quadruple Platinum on December 23, 1999, recognizing four million shipments in the United States; Worldwide, the album has sold more than 20 million copies, making it the biggest-selling album of her career. In 1999 the album received three Grammy Awards nominations including \"Record of the Year\", \"Best Pop Album\" and winning \"Best Dance Recording\" for the single \"Believe\". It was released by Warner Bros. Records at the end of 1998. The album was executive produced by Rob",
URL: "https://www.last.fm/music/Cher/Believe",
}))
Expect(httpClient.RequestCount).To(Equal(1))
@@ -393,4 +585,101 @@ var _ = Describe("lastfmAgent", func() {
})
})
})
+
+ Describe("GetArtistImages", func() {
+ var agent *lastfmAgent
+ var apiClient *tests.FakeHttpClient
+ var httpClient *tests.FakeHttpClient
+
+ BeforeEach(func() {
+ apiClient = &tests.FakeHttpClient{}
+ httpClient = &tests.FakeHttpClient{}
+ client := newClient("API_KEY", "SECRET", apiClient)
+ agent = lastFMConstructor(ds)
+ agent.client = client
+ agent.httpClient = httpClient
+ })
+
+ It("returns the artist image from the page", func() {
+ fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
+ apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
+
+ fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.html")
+ httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
+
+ images, err := agent.GetArtistImages(ctx, "123", "U2", "")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(images).To(HaveLen(1))
+ Expect(images[0].URL).To(Equal("https://lastfm.freetls.fastly.net/i/u/ar0/818148bf682d429dc21b59a73ef6f68e.png"))
+ })
+
+ It("returns empty list if image is the ignored default image", func() {
+ fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
+ apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
+
+ fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.ignored.html")
+ httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
+
+ images, err := agent.GetArtistImages(ctx, "123", "U2", "")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(images).To(BeEmpty())
+ })
+
+ It("returns empty list if page has no meta tags", func() {
+ fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
+ apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
+
+ fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.no_meta.html")
+ httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
+
+ images, err := agent.GetArtistImages(ctx, "123", "U2", "")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(images).To(BeEmpty())
+ })
+
+ It("returns error if API call fails", func() {
+ apiClient.Err = errors.New("api error")
+ _, err := agent.GetArtistImages(ctx, "123", "U2", "")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("get artist info"))
+ })
+
+ It("returns error if scraper call fails", func() {
+ fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
+ apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
+
+ httpClient.Err = errors.New("scraper error")
+ _, err := agent.GetArtistImages(ctx, "123", "U2", "")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("get artist url"))
+ })
+ })
})
+
+// langAwareHttpClient is a mock HTTP client that returns different responses based on the lang parameter
+type langAwareHttpClient struct {
+ responses map[string]http.Response
+ requests []*http.Request
+ requestCount int
+}
+
+func newLangAwareHttpClient() *langAwareHttpClient {
+ return &langAwareHttpClient{
+ responses: make(map[string]http.Response),
+ requests: make([]*http.Request, 0),
+ }
+}
+
+func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
+ c.requestCount++
+ c.requests = append(c.requests, req)
+ lang := req.URL.Query().Get("lang")
+ if resp, ok := c.responses[lang]; ok {
+ return &resp, nil
+ }
+ // Return default empty response if no specific response is configured
+ return &http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(bytes.NewBufferString(`{}`)),
+ }, nil
+}
diff --git a/core/agents/lastfm/auth_router.go b/adapters/lastfm/auth_router.go
similarity index 96%
rename from core/agents/lastfm/auth_router.go
rename to adapters/lastfm/auth_router.go
index 290caaad3..162ae9037 100644
--- a/core/agents/lastfm/auth_router.go
+++ b/adapters/lastfm/auth_router.go
@@ -44,7 +44,7 @@ func NewRouter(ds model.DataStore) *Router {
hc := &http.Client{
Timeout: consts.DefaultHttpClientTimeOut,
}
- r.client = newClient(r.apiKey, r.secret, "en", hc)
+ r.client = newClient(r.apiKey, r.secret, hc)
return r
}
@@ -65,7 +65,7 @@ func (s *Router) routes() http.Handler {
}
func (s *Router) getLinkStatus(w http.ResponseWriter, r *http.Request) {
- resp := map[string]interface{}{
+ resp := map[string]any{
"apiKey": s.apiKey,
}
u, _ := request.UserFrom(r.Context())
@@ -110,7 +110,7 @@ func (s *Router) callback(w http.ResponseWriter, r *http.Request) {
if err != nil {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
- _, _ = w.Write([]byte("An error occurred while authorizing with Last.fm. \n\nRequest ID: " + middleware.GetReqID(ctx)))
+ _, _ = w.Write([]byte("An error occurred while authorizing with Last.fm. \n\nRequest ID: " + middleware.GetReqID(ctx))) //nolint:gosec
return
}
diff --git a/core/agents/lastfm/client.go b/adapters/lastfm/client.go
similarity index 84%
rename from core/agents/lastfm/client.go
rename to adapters/lastfm/client.go
index 6a24ac80a..726df1360 100644
--- a/core/agents/lastfm/client.go
+++ b/adapters/lastfm/client.go
@@ -34,24 +34,23 @@ type httpDoer interface {
Do(req *http.Request) (*http.Response, error)
}
-func newClient(apiKey string, secret string, lang string, hc httpDoer) *client {
- return &client{apiKey, secret, lang, hc}
+func newClient(apiKey string, secret string, hc httpDoer) *client {
+ return &client{apiKey, secret, hc}
}
type client struct {
apiKey string
secret string
- lang string
hc httpDoer
}
-func (c *client) albumGetInfo(ctx context.Context, name string, artist string, mbid string) (*Album, error) {
+func (c *client) albumGetInfo(ctx context.Context, name string, artist string, mbid string, lang string) (*Album, error) {
params := url.Values{}
params.Add("method", "album.getInfo")
params.Add("album", name)
params.Add("artist", artist)
params.Add("mbid", mbid)
- params.Add("lang", c.lang)
+ params.Add("lang", lang)
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
if err != nil {
return nil, err
@@ -59,11 +58,11 @@ func (c *client) albumGetInfo(ctx context.Context, name string, artist string, m
return &response.Album, nil
}
-func (c *client) artistGetInfo(ctx context.Context, name string) (*Artist, error) {
+func (c *client) artistGetInfo(ctx context.Context, name string, lang string) (*Artist, error) {
params := url.Values{}
params.Add("method", "artist.getInfo")
params.Add("artist", name)
- params.Add("lang", c.lang)
+ params.Add("lang", lang)
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
if err != nil {
return nil, err
@@ -95,6 +94,19 @@ func (c *client) artistGetTopTracks(ctx context.Context, name string, limit int)
return &response.TopTracks, nil
}
+func (c *client) trackGetSimilar(ctx context.Context, name, artist string, limit int) (*SimilarTracks, error) {
+ params := url.Values{}
+ params.Add("method", "track.getSimilar")
+ params.Add("track", name)
+ params.Add("artist", artist)
+ params.Add("limit", strconv.Itoa(limit))
+ response, err := c.makeRequest(ctx, http.MethodGet, params, false)
+ if err != nil {
+ return nil, err
+ }
+ return &response.SimilarTracks, nil
+}
+
func (c *client) GetToken(ctx context.Context) (string, error) {
params := url.Values{}
params.Add("method", "auth.getToken")
@@ -185,8 +197,15 @@ func (c *client) makeRequest(ctx context.Context, method string, params url.Valu
c.sign(params)
}
- req, _ := http.NewRequestWithContext(ctx, method, apiBaseUrl, nil)
- req.URL.RawQuery = params.Encode()
+ var req *http.Request
+ if method == http.MethodPost {
+ body := strings.NewReader(params.Encode())
+ req, _ = http.NewRequestWithContext(ctx, method, apiBaseUrl, body)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ } else {
+ req, _ = http.NewRequestWithContext(ctx, method, apiBaseUrl, nil)
+ req.URL.RawQuery = params.Encode()
+ }
log.Trace(ctx, fmt.Sprintf("Sending Last.fm %s request", req.Method), "url", req.URL)
resp, err := c.hc.Do(req)
diff --git a/core/agents/lastfm/client_test.go b/adapters/lastfm/client_test.go
similarity index 59%
rename from core/agents/lastfm/client_test.go
rename to adapters/lastfm/client_test.go
index 85ec11506..271ae1419 100644
--- a/core/agents/lastfm/client_test.go
+++ b/adapters/lastfm/client_test.go
@@ -22,7 +22,7 @@ var _ = Describe("client", func() {
BeforeEach(func() {
httpClient = &tests.FakeHttpClient{}
- client = newClient("API_KEY", "SECRET", "pt", httpClient)
+ client = newClient("API_KEY", "SECRET", httpClient)
})
Describe("albumGetInfo", func() {
@@ -30,7 +30,7 @@ var _ = Describe("client", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
- album, err := client.albumGetInfo(context.Background(), "Believe", "U2", "mbid-1234")
+ album, err := client.albumGetInfo(context.Background(), "Believe", "U2", "mbid-1234", "pt")
Expect(err).To(BeNil())
Expect(album.Name).To(Equal("Believe"))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?album=Believe&api_key=API_KEY&artist=U2&format=json&lang=pt&mbid=mbid-1234&method=album.getInfo"))
@@ -42,7 +42,7 @@ var _ = Describe("client", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
- artist, err := client.artistGetInfo(context.Background(), "U2")
+ artist, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).To(BeNil())
Expect(artist.Name).To(Equal("U2"))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&lang=pt&method=artist.getInfo"))
@@ -54,7 +54,7 @@ var _ = Describe("client", func() {
StatusCode: 500,
}
- _, err := client.artistGetInfo(context.Background(), "U2")
+ _, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).To(MatchError("last.fm http status: (500)"))
})
@@ -64,7 +64,7 @@ var _ = Describe("client", func() {
StatusCode: 400,
}
- _, err := client.artistGetInfo(context.Background(), "U2")
+ _, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).To(MatchError(&lastFMError{Code: 3, Message: "Invalid Method - No method with that name in this package"}))
})
@@ -74,14 +74,14 @@ var _ = Describe("client", func() {
StatusCode: 200,
}
- _, err := client.artistGetInfo(context.Background(), "U2")
+ _, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).To(MatchError(&lastFMError{Code: 6, Message: "The artist you supplied could not be found"}))
})
It("fails if HttpClient.Do() returns error", func() {
httpClient.Err = errors.New("generic error")
- _, err := client.artistGetInfo(context.Background(), "U2")
+ _, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).To(MatchError("generic error"))
})
@@ -91,7 +91,7 @@ var _ = Describe("client", func() {
StatusCode: 200,
}
- _, err := client.artistGetInfo(context.Background(), "U2")
+ _, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).To(MatchError("invalid character '<' looking for beginning of value"))
})
@@ -121,6 +121,30 @@ var _ = Describe("client", func() {
})
})
+ Describe("trackGetSimilar", func() {
+ It("returns similar tracks for a successful response", func() {
+ f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+
+ similar, err := client.trackGetSimilar(context.Background(), "Just Can't Get Enough", "Depeche Mode", 5)
+ Expect(err).To(BeNil())
+ Expect(len(similar.Track)).To(Equal(5))
+ Expect(similar.Track[0].Name).To(Equal("Dreaming of Me"))
+ Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode"))
+ Expect(similar.Track[0].Match).To(Equal(1.0))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=Depeche+Mode&format=json&limit=5&method=track.getSimilar&track=Just+Can%27t+Get+Enough"))
+ })
+
+ It("returns empty list when no similar tracks found", func() {
+ f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+
+ similar, err := client.trackGetSimilar(context.Background(), "UnknownTrack", "UnknownArtist", 3)
+ Expect(err).To(BeNil())
+ Expect(similar.Track).To(BeEmpty())
+ })
+ })
+
Describe("GetToken", func() {
It("returns a token when the request is successful", func() {
httpClient.Res = http.Response{
@@ -154,6 +178,74 @@ var _ = Describe("client", func() {
})
})
+ Describe("scrobble", func() {
+ It("sends parameters in request body for POST", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)),
+ StatusCode: 200,
+ }
+
+ info := ScrobbleInfo{
+ artist: "U2",
+ track: "One",
+ album: "Achtung Baby",
+ trackNumber: 1,
+ duration: 276,
+ albumArtist: "U2",
+ }
+ err := client.scrobble(context.Background(), "SESSION_KEY", info)
+ Expect(err).To(BeNil())
+
+ req := httpClient.SavedRequest
+ Expect(req.Method).To(Equal(http.MethodPost))
+ Expect(req.Header.Get("Content-Type")).To(Equal("application/x-www-form-urlencoded"))
+ Expect(req.URL.RawQuery).To(BeEmpty())
+
+ body, _ := io.ReadAll(req.Body)
+ bodyParams, _ := url.ParseQuery(string(body))
+ Expect(bodyParams.Get("method")).To(Equal("track.scrobble"))
+ Expect(bodyParams.Get("artist")).To(Equal("U2"))
+ Expect(bodyParams.Get("track")).To(Equal("One"))
+ Expect(bodyParams.Get("sk")).To(Equal("SESSION_KEY"))
+ Expect(bodyParams.Get("api_key")).To(Equal("API_KEY"))
+ Expect(bodyParams.Get("api_sig")).ToNot(BeEmpty())
+ })
+ })
+
+ Describe("updateNowPlaying", func() {
+ It("sends parameters in request body for POST", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"nowplaying":{"ignoredMessage":{"code":"0"}}}`)),
+ StatusCode: 200,
+ }
+
+ info := ScrobbleInfo{
+ artist: "U2",
+ track: "One",
+ album: "Achtung Baby",
+ trackNumber: 1,
+ duration: 276,
+ albumArtist: "U2",
+ }
+ err := client.updateNowPlaying(context.Background(), "SESSION_KEY", info)
+ Expect(err).To(BeNil())
+
+ req := httpClient.SavedRequest
+ Expect(req.Method).To(Equal(http.MethodPost))
+ Expect(req.Header.Get("Content-Type")).To(Equal("application/x-www-form-urlencoded"))
+ Expect(req.URL.RawQuery).To(BeEmpty())
+
+ body, _ := io.ReadAll(req.Body)
+ bodyParams, _ := url.ParseQuery(string(body))
+ Expect(bodyParams.Get("method")).To(Equal("track.updateNowPlaying"))
+ Expect(bodyParams.Get("artist")).To(Equal("U2"))
+ Expect(bodyParams.Get("track")).To(Equal("One"))
+ Expect(bodyParams.Get("sk")).To(Equal("SESSION_KEY"))
+ Expect(bodyParams.Get("api_key")).To(Equal("API_KEY"))
+ Expect(bodyParams.Get("api_sig")).ToNot(BeEmpty())
+ })
+ })
+
Describe("sign", func() {
It("adds an api_sig param with the signature", func() {
params := url.Values{}
diff --git a/core/agents/lastfm/lastfm_suite_test.go b/adapters/lastfm/lastfm_suite_test.go
similarity index 100%
rename from core/agents/lastfm/lastfm_suite_test.go
rename to adapters/lastfm/lastfm_suite_test.go
diff --git a/core/agents/lastfm/responses.go b/adapters/lastfm/responses.go
similarity index 84%
rename from core/agents/lastfm/responses.go
rename to adapters/lastfm/responses.go
index 1ceebe767..026741672 100644
--- a/core/agents/lastfm/responses.go
+++ b/adapters/lastfm/responses.go
@@ -5,6 +5,7 @@ type Response struct {
SimilarArtists SimilarArtists `json:"similarartists"`
TopTracks TopTracks `json:"toptracks"`
Album Album `json:"album"`
+ SimilarTracks SimilarTracks `json:"similartracks"`
Error int `json:"error"`
Message string `json:"message"`
Token string `json:"token"`
@@ -59,6 +60,28 @@ type TopTracks struct {
Attr Attr `json:"@attr"`
}
+type SimilarTracks struct {
+ Track []SimilarTrack `json:"track"`
+ Attr SimilarAttr `json:"@attr"`
+}
+
+type SimilarTrack struct {
+ Name string `json:"name"`
+ MBID string `json:"mbid"`
+ Match float64 `json:"match"`
+ Artist SimilarTrackArtist `json:"artist"`
+}
+
+type SimilarTrackArtist struct {
+ Name string `json:"name"`
+ MBID string `json:"mbid"`
+}
+
+type SimilarAttr struct {
+ Artist string `json:"artist"`
+ Track string `json:"track"`
+}
+
type Session struct {
Name string `json:"name"`
Key string `json:"key"`
diff --git a/core/agents/lastfm/responses_test.go b/adapters/lastfm/responses_test.go
similarity index 100%
rename from core/agents/lastfm/responses_test.go
rename to adapters/lastfm/responses_test.go
diff --git a/core/agents/lastfm/token_received.html b/adapters/lastfm/token_received.html
similarity index 100%
rename from core/agents/lastfm/token_received.html
rename to adapters/lastfm/token_received.html
diff --git a/core/agents/listenbrainz/agent.go b/adapters/listenbrainz/agent.go
similarity index 55%
rename from core/agents/listenbrainz/agent.go
rename to adapters/listenbrainz/agent.go
index 769b0f5a6..019c6e9f4 100644
--- a/core/agents/listenbrainz/agent.go
+++ b/adapters/listenbrainz/agent.go
@@ -118,12 +118,129 @@ func (l *listenBrainzAgent) IsAuthorized(ctx context.Context, userId string) boo
return err == nil && sk != ""
}
+func (l *listenBrainzAgent) GetArtistURL(ctx context.Context, id, name, mbid string) (string, error) {
+ if mbid == "" {
+ return "", agents.ErrNotFound
+ }
+
+ url, err := l.client.getArtistUrl(ctx, mbid)
+ if err != nil {
+ return "", err
+ }
+ return url, nil
+}
+
+func (l *listenBrainzAgent) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]agents.Song, error) {
+ resp, err := l.client.getArtistTopSongs(ctx, mbid, count)
+ if err != nil {
+ return nil, err
+ }
+ if len(resp) == 0 {
+ return nil, agents.ErrNotFound
+ }
+
+ res := make([]agents.Song, len(resp))
+ for i, t := range resp {
+ mbid := ""
+ if len(t.ArtistMBIDs) > 0 {
+ mbid = t.ArtistMBIDs[0]
+ }
+
+ res[i] = agents.Song{
+ Album: t.ReleaseName,
+ AlbumMBID: t.ReleaseMBID,
+ Artist: t.ArtistName,
+ ArtistMBID: mbid,
+ Duration: t.DurationMs,
+ Name: t.RecordingName,
+ MBID: t.RecordingMbid,
+ }
+ }
+ return res, nil
+}
+
+func (l *listenBrainzAgent) GetSimilarArtists(ctx context.Context, id string, name string, mbid string, limit int) ([]agents.Artist, error) {
+ if mbid == "" {
+ return nil, agents.ErrNotFound
+ }
+
+ resp, err := l.client.getSimilarArtists(ctx, mbid, limit)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(resp) == 0 {
+ return nil, agents.ErrNotFound
+ }
+
+ artists := make([]agents.Artist, len(resp))
+ for i, artist := range resp {
+ artists[i] = agents.Artist{
+ MBID: artist.MBID,
+ Name: artist.Name,
+ }
+ }
+
+ return artists, nil
+}
+
+func (l *listenBrainzAgent) GetSimilarSongsByTrack(ctx context.Context, id string, name string, artist string, mbid string, limit int) ([]agents.Song, error) {
+ if mbid == "" {
+ return nil, agents.ErrNotFound
+ }
+
+ resp, err := l.client.getSimilarRecordings(ctx, mbid, limit)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(resp) == 0 {
+ return nil, agents.ErrNotFound
+ }
+
+ songs := make([]agents.Song, len(resp))
+ for i, song := range resp {
+ songs[i] = agents.Song{
+ Album: song.ReleaseName,
+ AlbumMBID: song.ReleaseMBID,
+ Artist: song.Artist,
+ MBID: song.MBID,
+ Name: song.Name,
+ }
+ }
+
+ return songs, nil
+}
+
func init() {
conf.AddHook(func() {
if conf.Server.ListenBrainz.Enabled {
scrobbler.Register(listenBrainzAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
- return listenBrainzConstructor(ds)
+ // This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
+ // See https://go.dev/doc/faq#nil_error
+ a := listenBrainzConstructor(ds)
+ if a != nil {
+ return a
+ }
+ return nil
+ })
+
+ agents.Register(listenBrainzAgentName, func(ds model.DataStore) agents.Interface {
+ // This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
+ // See https://go.dev/doc/faq#nil_error
+ a := listenBrainzConstructor(ds)
+ if a != nil {
+ return a
+ }
+ return nil
})
}
})
}
+
+var (
+ _ agents.ArtistTopSongsRetriever = (*listenBrainzAgent)(nil)
+ _ agents.ArtistURLRetriever = (*listenBrainzAgent)(nil)
+ _ agents.ArtistSimilarRetriever = (*listenBrainzAgent)(nil)
+ _ agents.SimilarSongsByTrackRetriever = (*listenBrainzAgent)(nil)
+)
diff --git a/adapters/listenbrainz/agent_test.go b/adapters/listenbrainz/agent_test.go
new file mode 100644
index 000000000..df70ec9c4
--- /dev/null
+++ b/adapters/listenbrainz/agent_test.go
@@ -0,0 +1,443 @@
+package listenbrainz
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "os"
+ "time"
+
+ "github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/core/agents"
+ "github.com/navidrome/navidrome/core/scrobbler"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ . "github.com/onsi/gomega/gstruct"
+)
+
+var _ = Describe("listenBrainzAgent", func() {
+ var ds model.DataStore
+ var ctx context.Context
+ var agent *listenBrainzAgent
+ var httpClient *tests.FakeHttpClient
+ var track *model.MediaFile
+
+ BeforeEach(func() {
+ ds = &tests.MockDataStore{}
+ ctx = context.Background()
+ _ = ds.UserProps(ctx).Put("user-1", sessionKeyProperty, "SK-1")
+ httpClient = &tests.FakeHttpClient{}
+ agent = listenBrainzConstructor(ds)
+ agent.client = newClient("http://localhost:8080", httpClient)
+ track = &model.MediaFile{
+ ID: "123",
+ Title: "Track Title",
+ Album: "Track Album",
+ Artist: "Track Artist",
+ TrackNumber: 1,
+ MbzRecordingID: "mbz-123",
+ MbzAlbumID: "mbz-456",
+ MbzReleaseGroupID: "mbz-789",
+ Duration: 142.2,
+ Participants: map[model.Role]model.ParticipantList{
+ model.RoleArtist: []model.Participant{
+ {Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}},
+ {Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}},
+ },
+ },
+ }
+ })
+
+ Describe("formatListen", func() {
+ It("constructs the listenInfo properly", func() {
+ lr := agent.formatListen(track)
+ Expect(lr).To(MatchAllFields(Fields{
+ "ListenedAt": Equal(0),
+ "TrackMetadata": MatchAllFields(Fields{
+ "ArtistName": Equal(track.Artist),
+ "TrackName": Equal(track.Title),
+ "ReleaseName": Equal(track.Album),
+ "AdditionalInfo": MatchAllFields(Fields{
+ "SubmissionClient": Equal(consts.AppName),
+ "SubmissionClientVersion": Equal(consts.Version),
+ "TrackNumber": Equal(track.TrackNumber),
+ "RecordingMBID": Equal(track.MbzRecordingID),
+ "ReleaseMBID": Equal(track.MbzAlbumID),
+ "ReleaseGroupMBID": Equal(track.MbzReleaseGroupID),
+ "ArtistNames": ConsistOf("Artist 1", "Artist 2"),
+ "ArtistMBIDs": ConsistOf("mbz-111", "mbz-222"),
+ "DurationMs": Equal(142200),
+ }),
+ }),
+ }))
+ })
+ })
+
+ Describe("NowPlaying", func() {
+ It("updates NowPlaying successfully", func() {
+ httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
+
+ err := agent.NowPlaying(ctx, "user-1", track, 0)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("returns ErrNotAuthorized if user is not linked", func() {
+ err := agent.NowPlaying(ctx, "user-2", track, 0)
+ Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
+ })
+ })
+
+ Describe("Scrobble", func() {
+ var sc scrobbler.Scrobble
+
+ BeforeEach(func() {
+ sc = scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}
+ })
+
+ It("sends a Scrobble successfully", func() {
+ httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
+
+ err := agent.Scrobble(ctx, "user-1", sc)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("sets the Timestamp properly", func() {
+ httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
+
+ err := agent.Scrobble(ctx, "user-1", sc)
+ Expect(err).ToNot(HaveOccurred())
+
+ decoder := json.NewDecoder(httpClient.SavedRequest.Body)
+ var lr listenBrainzRequestBody
+ err = decoder.Decode(&lr)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(lr.Payload[0].ListenedAt).To(Equal(int(sc.TimeStamp.Unix())))
+ })
+
+ It("returns ErrNotAuthorized if user is not linked", func() {
+ err := agent.Scrobble(ctx, "user-2", sc)
+ Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
+ })
+
+ It("returns ErrRetryLater on error 503", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)),
+ StatusCode: 503,
+ }
+
+ err := agent.Scrobble(ctx, "user-1", sc)
+ Expect(err).To(MatchError(scrobbler.ErrRetryLater))
+ })
+
+ It("returns ErrRetryLater on error 500", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)),
+ StatusCode: 500,
+ }
+
+ err := agent.Scrobble(ctx, "user-1", sc)
+ Expect(err).To(MatchError(scrobbler.ErrRetryLater))
+ })
+
+ It("returns ErrRetryLater on http errors", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)),
+ StatusCode: 500,
+ }
+
+ err := agent.Scrobble(ctx, "user-1", sc)
+ Expect(err).To(MatchError(scrobbler.ErrRetryLater))
+ })
+
+ It("returns ErrUnrecoverable on other errors", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)),
+ StatusCode: 400,
+ }
+
+ err := agent.Scrobble(ctx, "user-1", sc)
+ Expect(err).To(MatchError(scrobbler.ErrUnrecoverable))
+ })
+ })
+
+ Describe("GetArtistUrl", func() {
+ var agent *listenBrainzAgent
+ var httpClient *tests.FakeHttpClient
+ BeforeEach(func() {
+ httpClient = &tests.FakeHttpClient{}
+ client := newClient("BASE_URL", httpClient)
+ agent = listenBrainzConstructor(ds)
+ agent.client = client
+ })
+
+ It("returns artist url when MBID present", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ Expect(agent.GetArtistURL(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")).To(Equal("http://projectmili.com/"))
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
+ })
+
+ It("returns error when url not present", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ _, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("7c2cc610-f998-43ef-a08f-dae3344b8973"))
+ })
+
+ It("returns error when fetch calls fails", func() {
+ httpClient.Err = errors.New("error")
+ _, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("7c2cc610-f998-43ef-a08f-dae3344b8973"))
+ })
+
+ It("returns error when ListenBrainz returns an error", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
+ StatusCode: 400,
+ }
+ _, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("7c2cc610-f998-43ef-a08f-dae3344b8973"))
+ })
+ })
+
+ Describe("GetTopSongs", func() {
+ var agent *listenBrainzAgent
+ var httpClient *tests.FakeHttpClient
+ BeforeEach(func() {
+ httpClient = &tests.FakeHttpClient{}
+ client := newClient("BASE_URL", httpClient)
+ agent = listenBrainzConstructor(ds)
+ agent.client = client
+ })
+
+ It("returns error when fetch calls", func() {
+ httpClient.Err = errors.New("error")
+ _, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.Path).To(Equal("/1/popularity/top-recordings-for-artist/d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
+ })
+
+ It("returns an error on listenbrainz error", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
+ StatusCode: 400,
+ }
+ _, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.Path).To(Equal("/1/popularity/top-recordings-for-artist/1"))
+ })
+
+ It("returns all tracks when asked", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(data).To(Equal([]agents.Song{
+ {
+ ID: "",
+ Name: "world.execute(me);",
+ MBID: "9980309d-3480-4e7e-89ce-fce971a452be",
+ Artist: "Mili",
+ ArtistMBID: "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56",
+ Album: "Miracle Milk",
+ AlbumMBID: "38a8f6e1-0e34-4418-a89d-78240a367408",
+ Duration: 211912,
+ },
+ {
+ ID: "",
+ Name: "String Theocracy",
+ MBID: "afa2c83d-b17f-4029-b9da-790ea9250cf9",
+ Artist: "Mili",
+ ArtistMBID: "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56",
+ Album: "String Theocracy",
+ AlbumMBID: "d79a38e3-7016-4f39-a31a-f495ce914b8e",
+ Duration: 174000,
+ },
+ }))
+ })
+
+ It("returns only one track when prompted", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(data).To(Equal([]agents.Song{
+ {
+ ID: "",
+ Name: "world.execute(me);",
+ MBID: "9980309d-3480-4e7e-89ce-fce971a452be",
+ Artist: "Mili",
+ ArtistMBID: "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56",
+ Album: "Miracle Milk",
+ AlbumMBID: "38a8f6e1-0e34-4418-a89d-78240a367408",
+ Duration: 211912,
+ },
+ }))
+ })
+ })
+
+ Describe("GetSimilarArtists", func() {
+ var agent *listenBrainzAgent
+ var httpClient *tests.FakeHttpClient
+ baseUrl := "https://labs.api.listenbrainz.org/similar-artists/json?algorithm=session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30&artist_mbids="
+ mbid := "db92a151-1ac2-438b-bc43-b82e149ddd50"
+
+ BeforeEach(func() {
+ httpClient = &tests.FakeHttpClient{}
+ client := newClient("BASE_URL", httpClient)
+ agent = listenBrainzConstructor(ds)
+ agent.client = client
+ })
+
+ It("returns error when fetch calls", func() {
+ httpClient.Err = errors.New("error")
+ _, err := agent.GetSimilarArtists(ctx, "", "", mbid, 1)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + mbid))
+ })
+
+ It("returns an error on listenbrainz error", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
+ StatusCode: 400,
+ }
+ _, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
+ })
+
+ It("returns all data on call", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+
+ resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + mbid))
+ Expect(resp).To(Equal([]agents.Artist{
+ {MBID: "f27ec8db-af05-4f36-916e-3d57f91ecf5e", Name: "Michael Jackson"},
+ {MBID: "7364dea6-ca9a-48e3-be01-b44ad0d19897", Name: "a-ha"},
+ }))
+ })
+
+ It("returns subset of data on call", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+
+ resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + mbid))
+ Expect(resp).To(Equal([]agents.Artist{
+ {MBID: "f27ec8db-af05-4f36-916e-3d57f91ecf5e", Name: "Michael Jackson"},
+ }))
+ })
+ })
+
+ Describe("GetSimilarTracks", func() {
+ var agent *listenBrainzAgent
+ var httpClient *tests.FakeHttpClient
+ mbid := "8f3471b5-7e6a-48da-86a9-c1c07a0f47ae"
+ baseUrl := "https://labs.api.listenbrainz.org/similar-recordings/json?algorithm=session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30&recording_mbids="
+
+ BeforeEach(func() {
+ httpClient = &tests.FakeHttpClient{}
+ client := newClient("BASE_URL", httpClient)
+ agent = listenBrainzConstructor(ds)
+ agent.client = client
+ })
+
+ It("returns error when fetch calls", func() {
+ httpClient.Err = errors.New("error")
+ _, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + mbid))
+ })
+
+ It("returns an error on listenbrainz error", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
+ StatusCode: 400,
+ }
+ _, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
+ Expect(err).To(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
+ })
+
+ It("returns all data on call", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+
+ resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + mbid))
+ Expect(resp).To(Equal([]agents.Song{
+ {
+ ID: "",
+ Name: "Take On Me",
+ MBID: "12f65dca-de8f-43fe-a65d-f12a02aaadf3",
+ ISRC: "",
+ Artist: "a‐ha",
+ ArtistMBID: "",
+ Album: "Hunting High and Low",
+ AlbumMBID: "4ec07fe8-e7c6-3106-a0aa-fdf92f13f7fc",
+ Duration: 0,
+ },
+ {
+ ID: "",
+ Name: "Wake Me Up Before You Go‐Go",
+ MBID: "80033c72-aa19-4ba8-9227-afb075fec46e",
+ ISRC: "",
+ Artist: "Wham!",
+ ArtistMBID: "",
+ Album: "Make It Big",
+ AlbumMBID: "c143d542-48dc-446b-b523-1762da721638",
+ Duration: 0,
+ },
+ }))
+ })
+
+ It("returns subset of data on call", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+
+ resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.RequestCount).To(Equal(1))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + mbid))
+ Expect(resp).To(Equal([]agents.Song{
+ {
+ ID: "",
+ Name: "Take On Me",
+ MBID: "12f65dca-de8f-43fe-a65d-f12a02aaadf3",
+ ISRC: "",
+ Artist: "a‐ha",
+ ArtistMBID: "",
+ Album: "Hunting High and Low",
+ AlbumMBID: "4ec07fe8-e7c6-3106-a0aa-fdf92f13f7fc",
+ Duration: 0,
+ },
+ }))
+ })
+ })
+})
diff --git a/core/agents/listenbrainz/auth_router.go b/adapters/listenbrainz/auth_router.go
similarity index 95%
rename from core/agents/listenbrainz/auth_router.go
rename to adapters/listenbrainz/auth_router.go
index 2382aeb73..7cb9eb16a 100644
--- a/core/agents/listenbrainz/auth_router.go
+++ b/adapters/listenbrainz/auth_router.go
@@ -60,7 +60,7 @@ func (s *Router) routes() http.Handler {
}
func (s *Router) getLinkStatus(w http.ResponseWriter, r *http.Request) {
- resp := map[string]interface{}{}
+ resp := map[string]any{}
u, _ := request.UserFrom(r.Context())
key, err := s.sessionKeys.Get(r.Context(), u.ID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
@@ -107,7 +107,7 @@ func (s *Router) link(w http.ResponseWriter, r *http.Request) {
return
}
- _ = rest.RespondWithJSON(w, http.StatusOK, map[string]interface{}{"status": resp.Valid, "user": resp.UserName})
+ _ = rest.RespondWithJSON(w, http.StatusOK, map[string]any{"status": resp.Valid, "user": resp.UserName})
}
func (s *Router) unlink(w http.ResponseWriter, r *http.Request) {
diff --git a/core/agents/listenbrainz/auth_router_test.go b/adapters/listenbrainz/auth_router_test.go
similarity index 97%
rename from core/agents/listenbrainz/auth_router_test.go
rename to adapters/listenbrainz/auth_router_test.go
index dc705dbc9..c3861799a 100644
--- a/core/agents/listenbrainz/auth_router_test.go
+++ b/adapters/listenbrainz/auth_router_test.go
@@ -37,7 +37,7 @@ var _ = Describe("ListenBrainz Auth Router", func() {
req = httptest.NewRequest("GET", "/listenbrainz/link", nil)
r.getLinkStatus(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
- var parsed map[string]interface{}
+ var parsed map[string]any
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
Expect(parsed["status"]).To(Equal(false))
})
@@ -47,7 +47,7 @@ var _ = Describe("ListenBrainz Auth Router", func() {
req = httptest.NewRequest("GET", "/listenbrainz/link", nil)
r.getLinkStatus(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
- var parsed map[string]interface{}
+ var parsed map[string]any
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
Expect(parsed["status"]).To(Equal(true))
})
@@ -80,7 +80,7 @@ var _ = Describe("ListenBrainz Auth Router", func() {
req = httptest.NewRequest("PUT", "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`))
r.link(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
- var parsed map[string]interface{}
+ var parsed map[string]any
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
Expect(parsed["status"]).To(Equal(true))
Expect(parsed["user"]).To(Equal("ListenBrainzUser"))
diff --git a/adapters/listenbrainz/client.go b/adapters/listenbrainz/client.go
new file mode 100644
index 000000000..708f02f28
--- /dev/null
+++ b/adapters/listenbrainz/client.go
@@ -0,0 +1,378 @@
+package listenbrainz
+
+import (
+ "bytes"
+ "cmp"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "path"
+ "slices"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/log"
+)
+
+const (
+ lbzApiUrl = "https://api.listenbrainz.org/1/"
+ labsBase = "https://labs.api.listenbrainz.org/"
+)
+
+var (
+ ErrorNotFound = errors.New("listenbrainz: not found")
+)
+
+type listenBrainzError struct {
+ Code int
+ Message string
+}
+
+func (e *listenBrainzError) Error() string {
+ return fmt.Sprintf("ListenBrainz error(%d): %s", e.Code, e.Message)
+}
+
+type httpDoer interface {
+ Do(req *http.Request) (*http.Response, error)
+}
+
+func newClient(baseURL string, hc httpDoer) *client {
+ return &client{baseURL, hc}
+}
+
+type client struct {
+ baseURL string
+ hc httpDoer
+}
+
+type listenBrainzResponse struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ Error string `json:"error"`
+ Status string `json:"status"`
+ Valid bool `json:"valid"`
+ UserName string `json:"user_name"`
+}
+
+type listenBrainzRequest struct {
+ ApiKey string //nolint:gosec
+ Body listenBrainzRequestBody
+}
+
+type listenBrainzRequestBody struct {
+ ListenType listenType `json:"listen_type,omitempty"`
+ Payload []listenInfo `json:"payload,omitempty"`
+}
+
+type listenType string
+
+const (
+ Single listenType = "single"
+ PlayingNow listenType = "playing_now"
+)
+
+type listenInfo struct {
+ ListenedAt int `json:"listened_at,omitempty"`
+ TrackMetadata trackMetadata `json:"track_metadata"`
+}
+
+type trackMetadata struct {
+ ArtistName string `json:"artist_name,omitempty"`
+ TrackName string `json:"track_name,omitempty"`
+ ReleaseName string `json:"release_name,omitempty"`
+ AdditionalInfo additionalInfo `json:"additional_info"`
+}
+
+type additionalInfo struct {
+ SubmissionClient string `json:"submission_client,omitempty"`
+ SubmissionClientVersion string `json:"submission_client_version,omitempty"`
+ TrackNumber int `json:"tracknumber,omitempty"`
+ ArtistNames []string `json:"artist_names,omitempty"`
+ ArtistMBIDs []string `json:"artist_mbids,omitempty"`
+ RecordingMBID string `json:"recording_mbid,omitempty"`
+ ReleaseMBID string `json:"release_mbid,omitempty"`
+ ReleaseGroupMBID string `json:"release_group_mbid,omitempty"`
+ DurationMs int `json:"duration_ms,omitempty"`
+}
+
+func (c *client) validateToken(ctx context.Context, apiKey string) (*listenBrainzResponse, error) {
+ r := &listenBrainzRequest{
+ ApiKey: apiKey,
+ }
+ response, err := c.makeAuthenticatedRequest(ctx, http.MethodGet, "validate-token", r)
+ if err != nil {
+ return nil, err
+ }
+ return response, nil
+}
+
+func (c *client) updateNowPlaying(ctx context.Context, apiKey string, li listenInfo) error {
+ r := &listenBrainzRequest{
+ ApiKey: apiKey,
+ Body: listenBrainzRequestBody{
+ ListenType: PlayingNow,
+ Payload: []listenInfo{li},
+ },
+ }
+
+ resp, err := c.makeAuthenticatedRequest(ctx, http.MethodPost, "submit-listens", r)
+ if err != nil {
+ return err
+ }
+ if resp.Status != "ok" {
+ log.Warn(ctx, "ListenBrainz: NowPlaying was not accepted", "status", resp.Status)
+ }
+ return nil
+}
+
+func (c *client) scrobble(ctx context.Context, apiKey string, li listenInfo) error {
+ r := &listenBrainzRequest{
+ ApiKey: apiKey,
+ Body: listenBrainzRequestBody{
+ ListenType: Single,
+ Payload: []listenInfo{li},
+ },
+ }
+ resp, err := c.makeAuthenticatedRequest(ctx, http.MethodPost, "submit-listens", r)
+ if err != nil {
+ return err
+ }
+ if resp.Status != "ok" {
+ log.Warn(ctx, "ListenBrainz: Scrobble was not accepted", "status", resp.Status)
+ }
+ return nil
+}
+
+func (c *client) path(endpoint string) (string, error) {
+ u, err := url.Parse(c.baseURL)
+ if err != nil {
+ return "", err
+ }
+ u.Path = path.Join(u.Path, endpoint)
+ return u.String(), nil
+}
+
+func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) {
+ b, _ := json.Marshal(r.Body)
+ uri, err := c.path(endpoint)
+ if err != nil {
+ return nil, err
+ }
+ req, _ := http.NewRequestWithContext(ctx, method, uri, bytes.NewBuffer(b))
+ req.Header.Add("Content-Type", "application/json; charset=UTF-8")
+
+ if r.ApiKey != "" {
+ req.Header.Add("Authorization", fmt.Sprintf("Token %s", r.ApiKey))
+ }
+
+ log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz %s request", req.Method), "url", req.URL)
+ resp, err := c.hc.Do(req)
+ if err != nil {
+ return nil, err
+ }
+
+ defer resp.Body.Close()
+ decoder := json.NewDecoder(resp.Body)
+
+ var response listenBrainzResponse
+ jsonErr := decoder.Decode(&response)
+ if resp.StatusCode != 200 && jsonErr != nil {
+ return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
+ }
+ if jsonErr != nil {
+ return nil, jsonErr
+ }
+ if response.Code != 0 && response.Code != 200 {
+ return &response, &listenBrainzError{Code: response.Code, Message: response.Error}
+ }
+
+ return &response, nil
+}
+
+type lbzHttpError struct {
+ Code int `json:"code"`
+ Error string `json:"error"`
+}
+
+func (c *client) makeGenericRequest(ctx context.Context, method string, endpoint string, params url.Values) (*http.Response, error) {
+ req, _ := http.NewRequestWithContext(ctx, method, lbzApiUrl+endpoint, nil)
+ req.Header.Add("Content-Type", "application/json; charset=UTF-8")
+ req.URL.RawQuery = params.Encode()
+
+ log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz %s request", req.Method), "url", req.URL)
+ resp, err := c.hc.Do(req)
+
+ if err != nil {
+ return nil, err
+ }
+
+ // On a 200 code, there is no code. Decode using using error message if it exists
+ if resp.StatusCode != 200 {
+ defer resp.Body.Close()
+ decoder := json.NewDecoder(resp.Body)
+
+ var lbzError lbzHttpError
+ jsonErr := decoder.Decode(&lbzError)
+
+ if jsonErr != nil {
+ return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
+ }
+
+ return nil, &listenBrainzError{Code: lbzError.Code, Message: lbzError.Error}
+ }
+
+ return resp, err
+}
+
+type artistMetadataResult struct {
+ Rels struct {
+ OfficialHomepage string `json:"official homepage,omitempty"`
+ } `json:"rels,omitzero"`
+}
+
+func (c *client) getArtistUrl(ctx context.Context, mbid string) (string, error) {
+ params := url.Values{}
+ params.Add("artist_mbids", mbid)
+ resp, err := c.makeGenericRequest(ctx, http.MethodGet, "metadata/artist", params)
+ if err != nil {
+ return "", err
+ }
+
+ defer resp.Body.Close()
+ decoder := json.NewDecoder(resp.Body)
+
+ var response []artistMetadataResult
+ jsonErr := decoder.Decode(&response)
+ if jsonErr != nil {
+ return "", fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
+ }
+
+ if len(response) == 0 || response[0].Rels.OfficialHomepage == "" {
+ return "", ErrorNotFound
+ }
+
+ return response[0].Rels.OfficialHomepage, nil
+}
+
+type trackInfo struct {
+ ArtistName string `json:"artist_name"`
+ ArtistMBIDs []string `json:"artist_mbids"`
+ DurationMs uint32 `json:"length"`
+ RecordingName string `json:"recording_name"`
+ RecordingMbid string `json:"recording_mbid"`
+ ReleaseName string `json:"release_name"`
+ ReleaseMBID string `json:"release_mbid"`
+}
+
+func (c *client) getArtistTopSongs(ctx context.Context, mbid string, count int) ([]trackInfo, error) {
+ resp, err := c.makeGenericRequest(ctx, http.MethodGet, "popularity/top-recordings-for-artist/"+mbid, url.Values{})
+ if err != nil {
+ return nil, err
+ }
+
+ defer resp.Body.Close()
+ decoder := json.NewDecoder(resp.Body)
+
+ var response []trackInfo
+ jsonErr := decoder.Decode(&response)
+ if jsonErr != nil {
+ return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
+ }
+
+ if len(response) > count {
+ return response[0:count], nil
+ }
+
+ return response, nil
+}
+
+type artist struct {
+ MBID string `json:"artist_mbid"`
+ Name string `json:"name"`
+ Score int `json:"score"`
+}
+
+func (c *client) getSimilarArtists(ctx context.Context, mbid string, limit int) ([]artist, error) {
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-artists/json", nil)
+ req.Header.Add("Content-Type", "application/json; charset=UTF-8")
+ req.URL.RawQuery = url.Values{
+ "artist_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.ArtistAlgorithm},
+ }.Encode()
+
+ log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
+ resp, err := c.hc.Do(req)
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer resp.Body.Close()
+ decoder := json.NewDecoder(resp.Body)
+
+ var artists []artist
+ jsonErr := decoder.Decode(&artists)
+ if jsonErr != nil {
+ return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
+ }
+
+ if len(artists) > limit {
+ return artists[:limit], nil
+ }
+
+ return artists, nil
+}
+
+type recording struct {
+ MBID string `json:"recording_mbid"`
+ Name string `json:"recording_name"`
+ Artist string `json:"artist_credit_name"`
+ ReleaseName string `json:"release_name"`
+ ReleaseMBID string `json:"release_mbid"`
+ Score int `json:"score"`
+}
+
+func (c *client) getSimilarRecordings(ctx context.Context, mbid string, limit int) ([]recording, error) {
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil)
+ req.Header.Add("Content-Type", "application/json; charset=UTF-8")
+ req.URL.RawQuery = url.Values{
+ "recording_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.TrackAlgorithm},
+ }.Encode()
+
+ log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
+ resp, err := c.hc.Do(req)
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer resp.Body.Close()
+ decoder := json.NewDecoder(resp.Body)
+
+ var recordings []recording
+ jsonErr := decoder.Decode(&recordings)
+ if jsonErr != nil {
+ return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
+ }
+
+ // For whatever reason, labs API isn't guaranteed to give results in the proper order
+ // and may also provide duplicates. See listenbrainz.labs.similar-recordings-real-out-of-order.json
+ // generated from https://labs.api.listenbrainz.org/similar-recordings/json?recording_mbids=8f3471b5-7e6a-48da-86a9-c1c07a0f47ae&algorithm=session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30
+ slices.SortFunc(recordings, func(a, b recording) int {
+ return cmp.Or(
+ cmp.Compare(b.Score, a.Score), // Sort by score descending
+ cmp.Compare(a.MBID, b.MBID), // Then by MBID ascending to ensure deterministic order for duplicates
+ )
+ })
+
+ recordings = slices.CompactFunc(recordings, func(a, b recording) bool {
+ return a.MBID == b.MBID
+ })
+
+ if len(recordings) > limit {
+ return recordings[:limit], nil
+ }
+
+ return recordings, nil
+}
diff --git a/adapters/listenbrainz/client_test.go b/adapters/listenbrainz/client_test.go
new file mode 100644
index 000000000..319cf01ab
--- /dev/null
+++ b/adapters/listenbrainz/client_test.go
@@ -0,0 +1,464 @@
+package listenbrainz
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("client", func() {
+ var httpClient *tests.FakeHttpClient
+ var client *client
+ BeforeEach(func() {
+ httpClient = &tests.FakeHttpClient{}
+ client = newClient("BASE_URL/", httpClient)
+ })
+
+ Describe("listenBrainzResponse", func() {
+ It("parses a response properly", func() {
+ var response listenBrainzResponse
+ err := json.Unmarshal([]byte(`{"code": 200, "message": "Message", "user_name": "UserName", "valid": true, "status": "ok", "error": "Error"}`), &response)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(response.Code).To(Equal(200))
+ Expect(response.Message).To(Equal("Message"))
+ Expect(response.UserName).To(Equal("UserName"))
+ Expect(response.Valid).To(BeTrue())
+ Expect(response.Status).To(Equal("ok"))
+ Expect(response.Error).To(Equal("Error"))
+ })
+ })
+
+ Describe("validateToken", func() {
+ BeforeEach(func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
+ StatusCode: 200,
+ }
+ })
+
+ It("formats the request properly", func() {
+ _, err := client.validateToken(context.Background(), "LB-TOKEN")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/validate-token"))
+ Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("parses and returns the response", func() {
+ res, err := client.validateToken(context.Background(), "LB-TOKEN")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(res.Valid).To(Equal(true))
+ Expect(res.UserName).To(Equal("ListenBrainzUser"))
+ })
+ })
+
+ Context("with listenInfo", func() {
+ var li listenInfo
+ BeforeEach(func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)),
+ StatusCode: 200,
+ }
+ li = listenInfo{
+ TrackMetadata: trackMetadata{
+ ArtistName: "Track Artist",
+ TrackName: "Track Title",
+ ReleaseName: "Track Album",
+ AdditionalInfo: additionalInfo{
+ TrackNumber: 1,
+ ArtistNames: []string{"Artist 1", "Artist 2"},
+ ArtistMBIDs: []string{"mbz-789", "mbz-012"},
+ RecordingMBID: "mbz-123",
+ ReleaseMBID: "mbz-456",
+ DurationMs: 142200,
+ },
+ },
+ }
+ })
+
+ Describe("updateNowPlaying", func() {
+ It("formats the request properly", func() {
+ Expect(client.updateNowPlaying(context.Background(), "LB-TOKEN", li)).To(Succeed())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
+ Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+
+ body, _ := io.ReadAll(httpClient.SavedRequest.Body)
+ f, _ := os.ReadFile("tests/fixtures/listenbrainz.nowplaying.request.json")
+ Expect(body).To(MatchJSON(f))
+ })
+ })
+
+ Describe("scrobble", func() {
+ BeforeEach(func() {
+ li.ListenedAt = 1635000000
+ })
+
+ It("formats the request properly", func() {
+ Expect(client.scrobble(context.Background(), "LB-TOKEN", li)).To(Succeed())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
+ Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+
+ body, _ := io.ReadAll(httpClient.SavedRequest.Body)
+ f, _ := os.ReadFile("tests/fixtures/listenbrainz.scrobble.request.json")
+ Expect(body).To(MatchJSON(f))
+ })
+ })
+ })
+
+ Context("getArtistUrl", func() {
+ baseUrl := "https://api.listenbrainz.org/1/metadata/artist?"
+ It("handles a malformed request with status code", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
+ StatusCode: 400,
+ }
+ _, err := client.getArtistUrl(context.Background(), "1")
+ Expect(err.Error()).To(Equal("ListenBrainz error(400): artist mbid 1 is not valid."))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("handles a malformed request without meaningful body", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(``)),
+ StatusCode: 501,
+ }
+ _, err := client.getArtistUrl(context.Background(), "1")
+ Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (501)"))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("It returns not found when the artist has no official homepage", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ _, err := client.getArtistUrl(context.Background(), "7c2cc610-f998-43ef-a08f-dae3344b8973")
+ Expect(err.Error()).To(Equal("listenbrainz: not found"))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=7c2cc610-f998-43ef-a08f-dae3344b8973"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("It returns data when the artist has a homepage", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ url, err := client.getArtistUrl(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(url).To(Equal("http://projectmili.com/"))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+ })
+
+ Context("getArtistTopSongs", func() {
+ baseUrl := "https://api.listenbrainz.org/1/popularity/top-recordings-for-artist/"
+
+ It("handles a malformed request with status code", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
+ StatusCode: 400,
+ }
+ _, err := client.getArtistTopSongs(context.Background(), "1", 50)
+ Expect(err.Error()).To(Equal("ListenBrainz error(400): artist_mbid: '1' is not a valid uuid"))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("handles a malformed request without standard body", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(``)),
+ StatusCode: 500,
+ }
+ _, err := client.getArtistTopSongs(context.Background(), "1", 1)
+ Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (500)"))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("It returns all tracks when given the opportunity", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(data).To(Equal([]trackInfo{
+ {
+ ArtistName: "Mili",
+ ArtistMBIDs: []string{"d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"},
+ DurationMs: 211912,
+ RecordingName: "world.execute(me);",
+ RecordingMbid: "9980309d-3480-4e7e-89ce-fce971a452be",
+ ReleaseName: "Miracle Milk",
+ ReleaseMBID: "38a8f6e1-0e34-4418-a89d-78240a367408",
+ },
+ {
+ ArtistName: "Mili",
+ ArtistMBIDs: []string{"d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"},
+ DurationMs: 174000,
+ RecordingName: "String Theocracy",
+ RecordingMbid: "afa2c83d-b17f-4029-b9da-790ea9250cf9",
+ ReleaseName: "String Theocracy",
+ ReleaseMBID: "d79a38e3-7016-4f39-a31a-f495ce914b8e",
+ },
+ }))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("It returns a subset of tracks when allowed", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(data).To(Equal([]trackInfo{
+ {
+ ArtistName: "Mili",
+ ArtistMBIDs: []string{"d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"},
+ DurationMs: 211912,
+ RecordingName: "world.execute(me);",
+ RecordingMbid: "9980309d-3480-4e7e-89ce-fce971a452be",
+ ReleaseName: "Miracle Milk",
+ ReleaseMBID: "38a8f6e1-0e34-4418-a89d-78240a367408",
+ },
+ }))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+ })
+
+ Context("getSimilarArtists", func() {
+ var algorithm string
+
+ BeforeEach(func() {
+ algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
+ DeferCleanup(configtest.SetupConfig())
+ })
+
+ getUrl := func(mbid string) string {
+ return fmt.Sprintf("https://labs.api.listenbrainz.org/similar-artists/json?algorithm=%s&artist_mbids=%s", algorithm, mbid)
+ }
+
+ mbid := "db92a151-1ac2-438b-bc43-b82e149ddd50"
+
+ It("handles a malformed request with status code", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
+ StatusCode: 400,
+ }
+ _, err := client.getSimilarArtists(context.Background(), "1", 2)
+ Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("handles real data properly", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ resp, err := client.getSimilarArtists(context.Background(), mbid, 2)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ Expect(resp).To(Equal([]artist{
+ {MBID: "f27ec8db-af05-4f36-916e-3d57f91ecf5e", Name: "Michael Jackson", Score: 800},
+ {MBID: "7364dea6-ca9a-48e3-be01-b44ad0d19897", Name: "a-ha", Score: 792},
+ }))
+ })
+
+ It("truncates data when requested", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ resp, err := client.getSimilarArtists(context.Background(), "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ Expect(resp).To(Equal([]artist{
+ {MBID: "f27ec8db-af05-4f36-916e-3d57f91ecf5e", Name: "Michael Jackson", Score: 800},
+ }))
+ })
+
+ It("fetches a different endpoint when algorithm changes", func() {
+ algorithm = "session_based_days_1825_session_300_contribution_3_threshold_10_limit_100_filter_True_skip_30"
+ conf.Server.ListenBrainz.ArtistAlgorithm = algorithm
+
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ resp, err := client.getSimilarArtists(context.Background(), mbid, 2)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ Expect(resp).To(Equal([]artist{
+ {MBID: "f27ec8db-af05-4f36-916e-3d57f91ecf5e", Name: "Michael Jackson", Score: 800},
+ {MBID: "7364dea6-ca9a-48e3-be01-b44ad0d19897", Name: "a-ha", Score: 792},
+ }))
+ })
+ })
+
+ Context("getSimilarRecordings", func() {
+ var algorithm string
+
+ BeforeEach(func() {
+ algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
+ DeferCleanup(configtest.SetupConfig())
+ })
+
+ getUrl := func(mbid string) string {
+ return fmt.Sprintf("https://labs.api.listenbrainz.org/similar-recordings/json?algorithm=%s&recording_mbids=%s", algorithm, mbid)
+ }
+
+ mbid := "8f3471b5-7e6a-48da-86a9-c1c07a0f47ae"
+
+ It("handles a malformed request with status code", func() {
+ httpClient.Res = http.Response{
+ Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
+ StatusCode: 400,
+ }
+ _, err := client.getSimilarRecordings(context.Background(), "1", 2)
+ Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ })
+
+ It("handles real data properly", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ resp, err := client.getSimilarRecordings(context.Background(), mbid, 2)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ Expect(resp).To(Equal([]recording{
+ {
+ MBID: "12f65dca-de8f-43fe-a65d-f12a02aaadf3",
+ Name: "Take On Me",
+ Artist: "a‐ha",
+ ReleaseName: "Hunting High and Low",
+ ReleaseMBID: "4ec07fe8-e7c6-3106-a0aa-fdf92f13f7fc",
+ Score: 124,
+ },
+ {
+ MBID: "80033c72-aa19-4ba8-9227-afb075fec46e",
+ Name: "Wake Me Up Before You Go‐Go",
+ Artist: "Wham!",
+ ReleaseName: "Make It Big",
+ ReleaseMBID: "c143d542-48dc-446b-b523-1762da721638",
+ Score: 65,
+ },
+ }))
+ })
+
+ It("truncates data when requested", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ resp, err := client.getSimilarRecordings(context.Background(), mbid, 1)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ Expect(resp).To(Equal([]recording{
+ {
+ MBID: "12f65dca-de8f-43fe-a65d-f12a02aaadf3",
+ Name: "Take On Me",
+ Artist: "a‐ha",
+ ReleaseName: "Hunting High and Low",
+ ReleaseMBID: "4ec07fe8-e7c6-3106-a0aa-fdf92f13f7fc",
+ Score: 124,
+ },
+ }))
+ })
+
+ It("properly sorts by score and truncates duplicates", func() {
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ // There are actually 5 items. The dedup should happen FIRST
+ resp, err := client.getSimilarRecordings(context.Background(), mbid, 4)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ Expect(resp).To(Equal([]recording{
+ {
+ MBID: "12f65dca-de8f-43fe-a65d-f12a02aaadf3",
+ Name: "Take On Me",
+ Artist: "a‐ha",
+ ReleaseName: "Hunting High and Low",
+ ReleaseMBID: "4ec07fe8-e7c6-3106-a0aa-fdf92f13f7fc",
+ Score: 124,
+ },
+ {
+ MBID: "e4b347be-ecb2-44ff-aaa8-3d4c517d7ea5",
+ Name: "Everybody Wants to Rule the World",
+ Artist: "Tears for Fears",
+ ReleaseName: "Songs From the Big Chair",
+ ReleaseMBID: "21f19b06-81f1-347a-add5-5d0c77696597",
+ Score: 68,
+ },
+ {
+ MBID: "80033c72-aa19-4ba8-9227-afb075fec46e",
+ Name: "Wake Me Up Before You Go‐Go",
+ Artist: "Wham!",
+ ReleaseName: "Make It Big",
+ ReleaseMBID: "c143d542-48dc-446b-b523-1762da721638",
+ Score: 65,
+ },
+ {
+ MBID: "ef4c6855-949e-4e22-b41e-8e0a2d372d5f",
+ Name: "Tainted Love",
+ Artist: "Soft Cell",
+ ReleaseName: "Non-Stop Erotic Cabaret",
+ ReleaseMBID: "1acaa870-6e0c-4b6e-9e91-fdec4e5ea4b1",
+ Score: 61,
+ },
+ }))
+ })
+
+ It("uses a different algorithm when configured", func() {
+ algorithm = "session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30"
+ conf.Server.ListenBrainz.TrackAlgorithm = algorithm
+
+ f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
+ httpClient.Res = http.Response{Body: f, StatusCode: 200}
+ resp, err := client.getSimilarRecordings(context.Background(), mbid, 1)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
+ Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
+ Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
+ Expect(resp).To(Equal([]recording{
+ {
+ MBID: "12f65dca-de8f-43fe-a65d-f12a02aaadf3",
+ Name: "Take On Me",
+ Artist: "a‐ha",
+ ReleaseName: "Hunting High and Low",
+ ReleaseMBID: "4ec07fe8-e7c6-3106-a0aa-fdf92f13f7fc",
+ Score: 124,
+ },
+ }))
+ })
+ })
+})
diff --git a/core/agents/listenbrainz/listenbrainz_suite_test.go b/adapters/listenbrainz/listenbrainz_suite_test.go
similarity index 100%
rename from core/agents/listenbrainz/listenbrainz_suite_test.go
rename to adapters/listenbrainz/listenbrainz_suite_test.go
diff --git a/adapters/taglib/end_to_end_test.go b/adapters/taglib/end_to_end_test.go
index e4d94bb24..265f258f5 100644
--- a/adapters/taglib/end_to_end_test.go
+++ b/adapters/taglib/end_to_end_test.go
@@ -151,11 +151,7 @@ var _ = Describe("Extractor", func() {
unsSylt := makeLyrics("xxx", "unspecified SYLT")
unsUslt := makeLyrics("xxx", "unspecified")
- // Why is the order inconsistent between runs? Nobody knows
- Expect(lyrics).To(Or(
- Equal(model.LyricList{engSylt, engUslt, unsSylt, unsUslt}),
- Equal(model.LyricList{unsSylt, unsUslt, engSylt, engUslt}),
- ))
+ Expect(lyrics).To(ConsistOf(engSylt, engUslt, unsSylt, unsUslt))
})
DescribeTable("format-specific lyrics", func(file string, isId3 bool) {
diff --git a/adapters/taglib/taglib.go b/adapters/taglib/taglib.go
index 62a949d85..ac299ea2b 100644
--- a/adapters/taglib/taglib.go
+++ b/adapters/taglib/taglib.go
@@ -43,23 +43,21 @@ func (e extractor) extractMetadata(filePath string) (*metadata.Info, error) {
// Parse audio properties
ap := metadata.AudioProperties{}
- if length, ok := tags["_lengthinmilliseconds"]; ok && len(length) > 0 {
- millis, _ := strconv.Atoi(length[0])
- if millis > 0 {
- ap.Duration = (time.Millisecond * time.Duration(millis)).Round(time.Millisecond * 10)
- }
- delete(tags, "_lengthinmilliseconds")
- }
- parseProp := func(prop string, target *int) {
- if value, ok := tags[prop]; ok && len(value) > 0 {
- *target, _ = strconv.Atoi(value[0])
- delete(tags, prop)
- }
- }
- parseProp("_bitrate", &ap.BitRate)
- parseProp("_channels", &ap.Channels)
- parseProp("_samplerate", &ap.SampleRate)
- parseProp("_bitspersample", &ap.BitDepth)
+ ap.BitRate = parseProp(tags, "__bitrate")
+ ap.Channels = parseProp(tags, "__channels")
+ ap.SampleRate = parseProp(tags, "__samplerate")
+ ap.BitDepth = parseProp(tags, "__bitspersample")
+ length := parseProp(tags, "__lengthinmilliseconds")
+ ap.Duration = (time.Millisecond * time.Duration(length)).Round(time.Millisecond * 10)
+
+ // Extract basic tags
+ parseBasicTag(tags, "__title", "title")
+ parseBasicTag(tags, "__artist", "artist")
+ parseBasicTag(tags, "__album", "album")
+ parseBasicTag(tags, "__comment", "comment")
+ parseBasicTag(tags, "__genre", "genre")
+ parseBasicTag(tags, "__year", "year")
+ parseBasicTag(tags, "__track", "tracknumber")
// Parse track/disc totals
parseTuple := func(prop string) {
@@ -107,6 +105,31 @@ var tiplMapping = map[string]string{
"DJ-mix": "djmixer",
}
+// parseProp parses a property from the tags map and sets it to the target integer.
+// It also deletes the property from the tags map after parsing.
+func parseProp(tags map[string][]string, prop string) int {
+ if value, ok := tags[prop]; ok && len(value) > 0 {
+ v, _ := strconv.Atoi(value[0])
+ delete(tags, prop)
+ return v
+ }
+ return 0
+}
+
+// parseBasicTag checks if a basic tag (like __title, __artist, etc.) exists in the tags map.
+// If it does, it moves the value to a more appropriate tag name (like title, artist, etc.),
+// and deletes the basic tag from the map. If the target tag already exists, it ignores the basic tag.
+func parseBasicTag(tags map[string][]string, basicName string, tagName string) {
+ basicValue := tags[basicName]
+ if len(basicValue) == 0 {
+ return
+ }
+ delete(tags, basicName)
+ if len(tags[tagName]) == 0 {
+ tags[tagName] = basicValue
+ }
+}
+
// parseTIPL parses the ID3v2.4 TIPL frame string, which is received from TagLib in the format:
//
// "arranger Andrew Powell engineer Chris Blair engineer Pat Stapley producer Eric Woolfson".
@@ -145,7 +168,7 @@ func parseTIPL(tags map[string][]string) {
var _ local.Extractor = (*extractor)(nil)
func init() {
- local.RegisterExtractor("taglib", func(_ fs.FS, baseDir string) local.Extractor {
+ local.RegisterExtractor("legacy-taglib", func(_ fs.FS, baseDir string) local.Extractor {
// ignores fs, as taglib extractor only works with local files
return &extractor{baseDir}
})
diff --git a/adapters/taglib/taglib_test.go b/adapters/taglib/taglib_test.go
index f24c0e839..f524f77ec 100644
--- a/adapters/taglib/taglib_test.go
+++ b/adapters/taglib/taglib_test.go
@@ -80,12 +80,11 @@ var _ = Describe("Extractor", func() {
Expect(err).To(BeNil())
Expect(m.Tags).To(HaveKeyWithValue("fbpm", []string{"141.7"}))
- // TabLib 1.12 returns 18, previous versions return 39.
+ // TagLib 1.12 returns 18, previous versions return 39.
// See https://github.com/taglib/taglib/commit/2f238921824741b2cfe6fbfbfc9701d9827ab06b
Expect(m.AudioProperties.BitRate).To(BeElementOf(18, 19, 39, 40, 43, 49))
Expect(m.AudioProperties.Channels).To(BeElementOf(2))
Expect(m.AudioProperties.SampleRate).To(BeElementOf(8000))
- Expect(m.AudioProperties.SampleRate).To(BeElementOf(8000))
Expect(m.HasPicture).To(BeTrue())
})
@@ -106,7 +105,7 @@ var _ = Describe("Extractor", func() {
Expect(m.Tags).To(Or(
HaveKeyWithValue("replaygain_album_gain", []string{albumGain}),
- HaveKeyWithValue("----:com.apple.itunes:replaygain_track_gain", []string{albumGain}),
+ HaveKeyWithValue("----:com.apple.itunes:replaygain_album_gain", []string{albumGain}),
))
Expect(m.Tags).To(Or(
diff --git a/adapters/taglib/taglib_wrapper.cpp b/adapters/taglib/taglib_wrapper.cpp
index 224642c6d..2985e8f18 100644
--- a/adapters/taglib/taglib_wrapper.cpp
+++ b/adapters/taglib/taglib_wrapper.cpp
@@ -45,31 +45,63 @@ int taglib_read(const FILENAME_CHAR_T *filename, unsigned long id) {
// Add audio properties to the tags
const TagLib::AudioProperties *props(f.audioProperties());
- goPutInt(id, (char *)"_lengthinmilliseconds", props->lengthInMilliseconds());
- goPutInt(id, (char *)"_bitrate", props->bitrate());
- goPutInt(id, (char *)"_channels", props->channels());
- goPutInt(id, (char *)"_samplerate", props->sampleRate());
+ goPutInt(id, (char *)"__lengthinmilliseconds", props->lengthInMilliseconds());
+ goPutInt(id, (char *)"__bitrate", props->bitrate());
+ goPutInt(id, (char *)"__channels", props->channels());
+ goPutInt(id, (char *)"__samplerate", props->sampleRate());
+ // Extract bits per sample for supported formats
+ int bitsPerSample = 0;
if (const auto* apeProperties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", apeProperties->bitsPerSample());
- if (const auto* asfProperties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", asfProperties->bitsPerSample());
+ bitsPerSample = apeProperties->bitsPerSample();
+ else if (const auto* asfProperties{ dynamic_cast(props) })
+ bitsPerSample = asfProperties->bitsPerSample();
else if (const auto* flacProperties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", flacProperties->bitsPerSample());
+ bitsPerSample = flacProperties->bitsPerSample();
else if (const auto* mp4Properties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", mp4Properties->bitsPerSample());
+ bitsPerSample = mp4Properties->bitsPerSample();
else if (const auto* wavePackProperties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", wavePackProperties->bitsPerSample());
+ bitsPerSample = wavePackProperties->bitsPerSample();
else if (const auto* aiffProperties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", aiffProperties->bitsPerSample());
+ bitsPerSample = aiffProperties->bitsPerSample();
else if (const auto* wavProperties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", wavProperties->bitsPerSample());
+ bitsPerSample = wavProperties->bitsPerSample();
else if (const auto* dsfProperties{ dynamic_cast(props) })
- goPutInt(id, (char *)"_bitspersample", dsfProperties->bitsPerSample());
+ bitsPerSample = dsfProperties->bitsPerSample();
+
+ if (bitsPerSample > 0) {
+ goPutInt(id, (char *)"__bitspersample", bitsPerSample);
+ }
// Send all properties to the Go map
TagLib::PropertyMap tags = f.file()->properties();
+ // Make sure at least the basic properties are extracted
+ TagLib::Tag *basic = f.file()->tag();
+ if (!basic->isEmpty()) {
+ if (!basic->title().isEmpty()) {
+ tags.insert("__title", basic->title());
+ }
+ if (!basic->artist().isEmpty()) {
+ tags.insert("__artist", basic->artist());
+ }
+ if (!basic->album().isEmpty()) {
+ tags.insert("__album", basic->album());
+ }
+ if (!basic->comment().isEmpty()) {
+ tags.insert("__comment", basic->comment());
+ }
+ if (!basic->genre().isEmpty()) {
+ tags.insert("__genre", basic->genre());
+ }
+ if (basic->year() > 0) {
+ tags.insert("__year", TagLib::String::number(basic->year()));
+ }
+ if (basic->track() > 0) {
+ tags.insert("__track", TagLib::String::number(basic->track()));
+ }
+ }
+
TagLib::ID3v2::Tag *id3Tags = NULL;
// Get some extended/non-standard ID3-only tags (ex: iTunes extended frames)
diff --git a/cmd/pls.go b/cmd/pls.go
index fc0f22fba..9b94c9e8f 100644
--- a/cmd/pls.go
+++ b/cmd/pls.go
@@ -10,11 +10,8 @@ import (
"strconv"
"github.com/Masterminds/squirrel"
- "github.com/navidrome/navidrome/core/auth"
- "github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/persistence"
"github.com/spf13/cobra"
)
@@ -52,7 +49,7 @@ var (
Short: "Export playlists",
Long: "Export Navidrome playlists to M3U files",
Run: func(cmd *cobra.Command, args []string) {
- runExporter()
+ runExporter(cmd.Context())
},
}
@@ -60,15 +57,13 @@ var (
Use: "list",
Short: "List playlists",
Run: func(cmd *cobra.Command, args []string) {
- runList()
+ runList(cmd.Context())
},
}
)
-func runExporter() {
- sqlDB := db.Db()
- ds := persistence.New(sqlDB)
- ctx := auth.WithAdminUser(context.Background(), ds)
+func runExporter(ctx context.Context) {
+ ds, ctx := getAdminContext(ctx)
playlist, err := ds.Playlist(ctx).GetWithTracks(playlistID, true, false)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Fatal("Error retrieving playlist", "name", playlistID, err)
@@ -100,31 +95,19 @@ func runExporter() {
}
}
-func runList() {
+func runList(ctx context.Context) {
if outputFormat != "csv" && outputFormat != "json" {
log.Fatal("Invalid output format. Must be one of csv, json", "format", outputFormat)
}
- sqlDB := db.Db()
- ds := persistence.New(sqlDB)
- ctx := auth.WithAdminUser(context.Background(), ds)
-
+ ds, ctx := getAdminContext(ctx)
options := model.QueryOptions{Sort: "owner_name"}
if userID != "" {
- user, err := ds.User(ctx).FindByUsername(userID)
-
- if err != nil && !errors.Is(err, model.ErrNotFound) {
- log.Fatal("Error retrieving user by name", "name", userID, err)
+ user, err := getUser(ctx, userID, ds)
+ if err != nil {
+ log.Fatal(ctx, "Error retrieving user", "username or id", userID)
}
-
- if errors.Is(err, model.ErrNotFound) {
- user, err = ds.User(ctx).Get(userID)
- if err != nil {
- log.Fatal("Error retrieving user by id", "id", userID, err)
- }
- }
-
options.Filters = squirrel.Eq{"owner_id": user.ID}
}
diff --git a/cmd/plugin.go b/cmd/plugin.go
deleted file mode 100644
index 0f3b66078..000000000
--- a/cmd/plugin.go
+++ /dev/null
@@ -1,716 +0,0 @@
-package cmd
-
-import (
- "cmp"
- "crypto/sha256"
- "encoding/hex"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "strings"
- "text/tabwriter"
- "time"
-
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/plugins"
- "github.com/navidrome/navidrome/plugins/schema"
- "github.com/navidrome/navidrome/utils"
- "github.com/navidrome/navidrome/utils/slice"
- "github.com/spf13/cobra"
-)
-
-const (
- pluginPackageExtension = ".ndp"
- pluginDirPermissions = 0700
- pluginFilePermissions = 0600
-)
-
-func init() {
- pluginCmd := &cobra.Command{
- Use: "plugin",
- Short: "Manage Navidrome plugins",
- Long: "Commands for managing Navidrome plugins",
- }
-
- listCmd := &cobra.Command{
- Use: "list",
- Short: "List installed plugins",
- Long: "List all installed plugins with their metadata",
- Run: pluginList,
- }
-
- infoCmd := &cobra.Command{
- Use: "info [pluginPackage|pluginName]",
- Short: "Show details of a plugin",
- Long: "Show detailed information about a plugin package (.ndp file) or an installed plugin",
- Args: cobra.ExactArgs(1),
- Run: pluginInfo,
- }
-
- installCmd := &cobra.Command{
- Use: "install [pluginPackage]",
- Short: "Install a plugin from a .ndp file",
- Long: "Install a Navidrome Plugin Package (.ndp) file",
- Args: cobra.ExactArgs(1),
- Run: pluginInstall,
- }
-
- removeCmd := &cobra.Command{
- Use: "remove [pluginName]",
- Short: "Remove an installed plugin",
- Long: "Remove a plugin by name",
- Args: cobra.ExactArgs(1),
- Run: pluginRemove,
- }
-
- updateCmd := &cobra.Command{
- Use: "update [pluginPackage]",
- Short: "Update an existing plugin",
- Long: "Update an installed plugin with a new version from a .ndp file",
- Args: cobra.ExactArgs(1),
- Run: pluginUpdate,
- }
-
- refreshCmd := &cobra.Command{
- Use: "refresh [pluginName]",
- Short: "Reload a plugin without restarting Navidrome",
- Long: "Reload and recompile a plugin without needing to restart Navidrome",
- Args: cobra.ExactArgs(1),
- Run: pluginRefresh,
- }
-
- devCmd := &cobra.Command{
- Use: "dev [folder_path]",
- Short: "Create symlink to development folder",
- Long: "Create a symlink from a plugin development folder to the plugins directory for easier development",
- Args: cobra.ExactArgs(1),
- Run: pluginDev,
- }
-
- pluginCmd.AddCommand(listCmd, infoCmd, installCmd, removeCmd, updateCmd, refreshCmd, devCmd)
- rootCmd.AddCommand(pluginCmd)
-}
-
-// Validation helpers
-
-func validatePluginPackageFile(path string) error {
- if !utils.FileExists(path) {
- return fmt.Errorf("plugin package not found: %s", path)
- }
- if filepath.Ext(path) != pluginPackageExtension {
- return fmt.Errorf("not a valid plugin package: %s (expected %s extension)", path, pluginPackageExtension)
- }
- return nil
-}
-
-func validatePluginDirectory(pluginsDir, pluginName string) (string, error) {
- pluginDir := filepath.Join(pluginsDir, pluginName)
- if !utils.FileExists(pluginDir) {
- return "", fmt.Errorf("plugin not found: %s (path: %s)", pluginName, pluginDir)
- }
- return pluginDir, nil
-}
-
-func resolvePluginPath(pluginDir string) (resolvedPath string, isSymlink bool, err error) {
- // Check if it's a directory or a symlink
- lstat, err := os.Lstat(pluginDir)
- if err != nil {
- return "", false, fmt.Errorf("failed to stat plugin: %w", err)
- }
-
- isSymlink = lstat.Mode()&os.ModeSymlink != 0
-
- if isSymlink {
- // Resolve the symlink target
- targetDir, err := os.Readlink(pluginDir)
- if err != nil {
- return "", true, fmt.Errorf("failed to resolve symlink: %w", err)
- }
-
- // If target is a relative path, make it absolute
- if !filepath.IsAbs(targetDir) {
- targetDir = filepath.Join(filepath.Dir(pluginDir), targetDir)
- }
-
- // Verify the target exists and is a directory
- targetInfo, err := os.Stat(targetDir)
- if err != nil {
- return "", true, fmt.Errorf("failed to access symlink target %s: %w", targetDir, err)
- }
-
- if !targetInfo.IsDir() {
- return "", true, fmt.Errorf("symlink target is not a directory: %s", targetDir)
- }
-
- return targetDir, true, nil
- } else if !lstat.IsDir() {
- return "", false, fmt.Errorf("not a valid plugin directory: %s", pluginDir)
- }
-
- return pluginDir, false, nil
-}
-
-// Package handling helpers
-
-func loadAndValidatePackage(ndpPath string) (*plugins.PluginPackage, error) {
- if err := validatePluginPackageFile(ndpPath); err != nil {
- return nil, err
- }
-
- pkg, err := plugins.LoadPackage(ndpPath)
- if err != nil {
- return nil, fmt.Errorf("failed to load plugin package: %w", err)
- }
-
- return pkg, nil
-}
-
-func extractAndSetupPlugin(ndpPath, targetDir string) error {
- if err := plugins.ExtractPackage(ndpPath, targetDir); err != nil {
- return fmt.Errorf("failed to extract plugin package: %w", err)
- }
-
- ensurePluginDirPermissions(targetDir)
- return nil
-}
-
-// Display helpers
-
-func displayPluginTableRow(w *tabwriter.Writer, discovery plugins.PluginDiscoveryEntry) {
- if discovery.Error != nil {
- // Handle global errors (like directory read failure)
- if discovery.ID == "" {
- log.Error("Failed to read plugins directory", "folder", conf.Server.Plugins.Folder, discovery.Error)
- return
- }
- // Handle individual plugin errors - show them in the table
- fmt.Fprintf(w, "%s\tERROR\tERROR\tERROR\tERROR\t%v\n", discovery.ID, discovery.Error)
- return
- }
-
- // Mark symlinks with an indicator
- nameDisplay := discovery.Manifest.Name
- if discovery.IsSymlink {
- nameDisplay = nameDisplay + " (dev)"
- }
-
- // Convert capabilities to strings
- capabilities := slice.Map(discovery.Manifest.Capabilities, func(cap schema.PluginManifestCapabilitiesElem) string {
- return string(cap)
- })
-
- fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",
- discovery.ID,
- nameDisplay,
- cmp.Or(discovery.Manifest.Author, "-"),
- cmp.Or(discovery.Manifest.Version, "-"),
- strings.Join(capabilities, ", "),
- cmp.Or(discovery.Manifest.Description, "-"))
-}
-
-func displayTypedPermissions(permissions schema.PluginManifestPermissions, indent string) {
- if permissions.Http != nil {
- fmt.Printf("%shttp:\n", indent)
- fmt.Printf("%s Reason: %s\n", indent, permissions.Http.Reason)
- fmt.Printf("%s Allow Local Network: %t\n", indent, permissions.Http.AllowLocalNetwork)
- fmt.Printf("%s Allowed URLs:\n", indent)
- for urlPattern, methodEnums := range permissions.Http.AllowedUrls {
- methods := make([]string, len(methodEnums))
- for i, methodEnum := range methodEnums {
- methods[i] = string(methodEnum)
- }
- fmt.Printf("%s %s: [%s]\n", indent, urlPattern, strings.Join(methods, ", "))
- }
- fmt.Println()
- }
-
- if permissions.Config != nil {
- fmt.Printf("%sconfig:\n", indent)
- fmt.Printf("%s Reason: %s\n", indent, permissions.Config.Reason)
- fmt.Println()
- }
-
- if permissions.Scheduler != nil {
- fmt.Printf("%sscheduler:\n", indent)
- fmt.Printf("%s Reason: %s\n", indent, permissions.Scheduler.Reason)
- fmt.Println()
- }
-
- if permissions.Websocket != nil {
- fmt.Printf("%swebsocket:\n", indent)
- fmt.Printf("%s Reason: %s\n", indent, permissions.Websocket.Reason)
- fmt.Printf("%s Allow Local Network: %t\n", indent, permissions.Websocket.AllowLocalNetwork)
- fmt.Printf("%s Allowed URLs: [%s]\n", indent, strings.Join(permissions.Websocket.AllowedUrls, ", "))
- fmt.Println()
- }
-
- if permissions.Cache != nil {
- fmt.Printf("%scache:\n", indent)
- fmt.Printf("%s Reason: %s\n", indent, permissions.Cache.Reason)
- fmt.Println()
- }
-
- if permissions.Artwork != nil {
- fmt.Printf("%sartwork:\n", indent)
- fmt.Printf("%s Reason: %s\n", indent, permissions.Artwork.Reason)
- fmt.Println()
- }
-
- if permissions.Subsonicapi != nil {
- allowedUsers := "All Users"
- if len(permissions.Subsonicapi.AllowedUsernames) > 0 {
- allowedUsers = strings.Join(permissions.Subsonicapi.AllowedUsernames, ", ")
- }
- fmt.Printf("%ssubsonicapi:\n", indent)
- fmt.Printf("%s Reason: %s\n", indent, permissions.Subsonicapi.Reason)
- fmt.Printf("%s Allow Admins: %t\n", indent, permissions.Subsonicapi.AllowAdmins)
- fmt.Printf("%s Allowed Usernames: [%s]\n", indent, allowedUsers)
- fmt.Println()
- }
-}
-
-func displayPluginDetails(manifest *schema.PluginManifest, fileInfo *pluginFileInfo, permInfo *pluginPermissionInfo) {
- fmt.Println("\nPlugin Information:")
- fmt.Printf(" Name: %s\n", manifest.Name)
- fmt.Printf(" Author: %s\n", manifest.Author)
- fmt.Printf(" Version: %s\n", manifest.Version)
- fmt.Printf(" Description: %s\n", manifest.Description)
-
- fmt.Print(" Capabilities: ")
- capabilities := make([]string, len(manifest.Capabilities))
- for i, cap := range manifest.Capabilities {
- capabilities[i] = string(cap)
- }
- fmt.Print(strings.Join(capabilities, ", "))
- fmt.Println()
-
- // Display manifest permissions using the typed permissions
- fmt.Println(" Required Permissions:")
- displayTypedPermissions(manifest.Permissions, " ")
-
- // Print file information if available
- if fileInfo != nil {
- fmt.Println("Package Information:")
- fmt.Printf(" File: %s\n", fileInfo.path)
- fmt.Printf(" Size: %d bytes (%.2f KB)\n", fileInfo.size, float64(fileInfo.size)/1024)
- fmt.Printf(" SHA-256: %s\n", fileInfo.hash)
- fmt.Printf(" Modified: %s\n", fileInfo.modTime.Format(time.RFC3339))
- }
-
- // Print file permissions information if available
- if permInfo != nil {
- fmt.Println("File Permissions:")
- fmt.Printf(" Plugin Directory: %s (%s)\n", permInfo.dirPath, permInfo.dirMode)
- if permInfo.isSymlink {
- fmt.Printf(" Symlink Target: %s (%s)\n", permInfo.targetPath, permInfo.targetMode)
- }
- fmt.Printf(" Manifest File: %s\n", permInfo.manifestMode)
- if permInfo.wasmMode != "" {
- fmt.Printf(" WASM File: %s\n", permInfo.wasmMode)
- }
- }
-}
-
-type pluginFileInfo struct {
- path string
- size int64
- hash string
- modTime time.Time
-}
-
-type pluginPermissionInfo struct {
- dirPath string
- dirMode string
- isSymlink bool
- targetPath string
- targetMode string
- manifestMode string
- wasmMode string
-}
-
-func getFileInfo(path string) *pluginFileInfo {
- fileInfo, err := os.Stat(path)
- if err != nil {
- log.Error("Failed to get file information", err)
- return nil
- }
-
- return &pluginFileInfo{
- path: path,
- size: fileInfo.Size(),
- hash: calculateSHA256(path),
- modTime: fileInfo.ModTime(),
- }
-}
-
-func getPermissionInfo(pluginDir string) *pluginPermissionInfo {
- // Get plugin directory permissions
- dirInfo, err := os.Lstat(pluginDir)
- if err != nil {
- log.Error("Failed to get plugin directory permissions", err)
- return nil
- }
-
- permInfo := &pluginPermissionInfo{
- dirPath: pluginDir,
- dirMode: dirInfo.Mode().String(),
- }
-
- // Check if it's a symlink
- if dirInfo.Mode()&os.ModeSymlink != 0 {
- permInfo.isSymlink = true
-
- // Get target path and permissions
- targetPath, err := os.Readlink(pluginDir)
- if err == nil {
- if !filepath.IsAbs(targetPath) {
- targetPath = filepath.Join(filepath.Dir(pluginDir), targetPath)
- }
- permInfo.targetPath = targetPath
-
- if targetInfo, err := os.Stat(targetPath); err == nil {
- permInfo.targetMode = targetInfo.Mode().String()
- }
- }
- }
-
- // Get manifest file permissions
- manifestPath := filepath.Join(pluginDir, "manifest.json")
- if manifestInfo, err := os.Stat(manifestPath); err == nil {
- permInfo.manifestMode = manifestInfo.Mode().String()
- }
-
- // Get WASM file permissions (look for .wasm files)
- entries, err := os.ReadDir(pluginDir)
- if err == nil {
- for _, entry := range entries {
- if filepath.Ext(entry.Name()) == ".wasm" {
- wasmPath := filepath.Join(pluginDir, entry.Name())
- if wasmInfo, err := os.Stat(wasmPath); err == nil {
- permInfo.wasmMode = wasmInfo.Mode().String()
- break // Just show the first WASM file found
- }
- }
- }
- }
-
- return permInfo
-}
-
-// Command implementations
-
-func pluginList(cmd *cobra.Command, args []string) {
- discoveries := plugins.DiscoverPlugins(conf.Server.Plugins.Folder)
-
- w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
- fmt.Fprintln(w, "ID\tNAME\tAUTHOR\tVERSION\tCAPABILITIES\tDESCRIPTION")
-
- for _, discovery := range discoveries {
- displayPluginTableRow(w, discovery)
- }
- w.Flush()
-}
-
-func pluginInfo(cmd *cobra.Command, args []string) {
- path := args[0]
- pluginsDir := conf.Server.Plugins.Folder
-
- var manifest *schema.PluginManifest
- var fileInfo *pluginFileInfo
- var permInfo *pluginPermissionInfo
-
- if filepath.Ext(path) == pluginPackageExtension {
- // It's a package file
- pkg, err := loadAndValidatePackage(path)
- if err != nil {
- log.Fatal("Failed to load plugin package", err)
- }
- manifest = pkg.Manifest
- fileInfo = getFileInfo(path)
- // No permission info for package files
- } else {
- // It's a plugin name
- pluginDir, err := validatePluginDirectory(pluginsDir, path)
- if err != nil {
- log.Fatal("Plugin validation failed", err)
- }
-
- manifest, err = plugins.LoadManifest(pluginDir)
- if err != nil {
- log.Fatal("Failed to load plugin manifest", err)
- }
-
- // Get permission info for installed plugins
- permInfo = getPermissionInfo(pluginDir)
- }
-
- displayPluginDetails(manifest, fileInfo, permInfo)
-}
-
-func pluginInstall(cmd *cobra.Command, args []string) {
- ndpPath := args[0]
- pluginsDir := conf.Server.Plugins.Folder
-
- pkg, err := loadAndValidatePackage(ndpPath)
- if err != nil {
- log.Fatal("Package validation failed", err)
- }
-
- // Create target directory based on plugin name
- targetDir := filepath.Join(pluginsDir, pkg.Manifest.Name)
-
- // Check if plugin already exists
- if utils.FileExists(targetDir) {
- log.Fatal("Plugin already installed", "name", pkg.Manifest.Name, "path", targetDir,
- "use", "navidrome plugin update")
- }
-
- if err := extractAndSetupPlugin(ndpPath, targetDir); err != nil {
- log.Fatal("Plugin installation failed", err)
- }
-
- fmt.Printf("Plugin '%s' v%s installed successfully\n", pkg.Manifest.Name, pkg.Manifest.Version)
-}
-
-func pluginRemove(cmd *cobra.Command, args []string) {
- pluginName := args[0]
- pluginsDir := conf.Server.Plugins.Folder
-
- pluginDir, err := validatePluginDirectory(pluginsDir, pluginName)
- if err != nil {
- log.Fatal("Plugin validation failed", err)
- }
-
- _, isSymlink, err := resolvePluginPath(pluginDir)
- if err != nil {
- log.Fatal("Failed to resolve plugin path", err)
- }
-
- if isSymlink {
- // For symlinked plugins (dev mode), just remove the symlink
- if err := os.Remove(pluginDir); err != nil {
- log.Fatal("Failed to remove plugin symlink", "name", pluginName, err)
- }
- fmt.Printf("Development plugin symlink '%s' removed successfully (target directory preserved)\n", pluginName)
- } else {
- // For regular plugins, remove the entire directory
- if err := os.RemoveAll(pluginDir); err != nil {
- log.Fatal("Failed to remove plugin directory", "name", pluginName, err)
- }
- fmt.Printf("Plugin '%s' removed successfully\n", pluginName)
- }
-}
-
-func pluginUpdate(cmd *cobra.Command, args []string) {
- ndpPath := args[0]
- pluginsDir := conf.Server.Plugins.Folder
-
- pkg, err := loadAndValidatePackage(ndpPath)
- if err != nil {
- log.Fatal("Package validation failed", err)
- }
-
- // Check if plugin exists
- targetDir := filepath.Join(pluginsDir, pkg.Manifest.Name)
- if !utils.FileExists(targetDir) {
- log.Fatal("Plugin not found", "name", pkg.Manifest.Name, "path", targetDir,
- "use", "navidrome plugin install")
- }
-
- // Create a backup of the existing plugin
- backupDir := targetDir + ".bak." + time.Now().Format("20060102150405")
- if err := os.Rename(targetDir, backupDir); err != nil {
- log.Fatal("Failed to backup existing plugin", err)
- }
-
- // Extract the new package
- if err := extractAndSetupPlugin(ndpPath, targetDir); err != nil {
- // Restore backup if extraction failed
- os.RemoveAll(targetDir)
- _ = os.Rename(backupDir, targetDir) // Ignore error as we're already in a fatal path
- log.Fatal("Plugin update failed", err)
- }
-
- // Remove the backup
- os.RemoveAll(backupDir)
-
- fmt.Printf("Plugin '%s' updated to v%s successfully\n", pkg.Manifest.Name, pkg.Manifest.Version)
-}
-
-func pluginRefresh(cmd *cobra.Command, args []string) {
- pluginName := args[0]
- pluginsDir := conf.Server.Plugins.Folder
-
- pluginDir, err := validatePluginDirectory(pluginsDir, pluginName)
- if err != nil {
- log.Fatal("Plugin validation failed", err)
- }
-
- resolvedPath, isSymlink, err := resolvePluginPath(pluginDir)
- if err != nil {
- log.Fatal("Failed to resolve plugin path", err)
- }
-
- if isSymlink {
- log.Debug("Processing symlinked plugin", "name", pluginName, "link", pluginDir, "target", resolvedPath)
- }
-
- fmt.Printf("Refreshing plugin '%s'...\n", pluginName)
-
- // Get the plugin manager and refresh
- mgr := GetPluginManager(cmd.Context())
- log.Debug("Scanning plugins directory", "path", pluginsDir)
- mgr.ScanPlugins()
-
- log.Info("Waiting for plugin compilation to complete", "name", pluginName)
-
- // Wait for compilation to complete
- if err := mgr.EnsureCompiled(pluginName); err != nil {
- log.Fatal("Failed to compile refreshed plugin", "name", pluginName, err)
- }
-
- log.Info("Plugin compilation completed successfully", "name", pluginName)
- fmt.Printf("Plugin '%s' refreshed successfully\n", pluginName)
-}
-
-func pluginDev(cmd *cobra.Command, args []string) {
- sourcePath, err := filepath.Abs(args[0])
- if err != nil {
- log.Fatal("Invalid path", "path", args[0], err)
- }
- pluginsDir := conf.Server.Plugins.Folder
-
- // Validate source directory and manifest
- if err := validateDevSource(sourcePath); err != nil {
- log.Fatal("Source validation failed", err)
- }
-
- // Load manifest to get plugin name
- manifest, err := plugins.LoadManifest(sourcePath)
- if err != nil {
- log.Fatal("Failed to load plugin manifest", "path", filepath.Join(sourcePath, "manifest.json"), err)
- }
-
- pluginName := cmp.Or(manifest.Name, filepath.Base(sourcePath))
- targetPath := filepath.Join(pluginsDir, pluginName)
-
- // Handle existing target
- if err := handleExistingTarget(targetPath, sourcePath); err != nil {
- log.Fatal("Failed to handle existing target", err)
- }
-
- // Create target directory if needed
- if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
- log.Fatal("Failed to create plugins directory", "path", filepath.Dir(targetPath), err)
- }
-
- // Create the symlink
- if err := os.Symlink(sourcePath, targetPath); err != nil {
- log.Fatal("Failed to create symlink", "source", sourcePath, "target", targetPath, err)
- }
-
- fmt.Printf("Development symlink created: '%s' -> '%s'\n", targetPath, sourcePath)
- fmt.Println("Plugin can be refreshed with: navidrome plugin refresh", pluginName)
-}
-
-// Utility functions
-
-func validateDevSource(sourcePath string) error {
- sourceInfo, err := os.Stat(sourcePath)
- if err != nil {
- return fmt.Errorf("source folder not found: %s (%w)", sourcePath, err)
- }
- if !sourceInfo.IsDir() {
- return fmt.Errorf("source path is not a directory: %s", sourcePath)
- }
-
- manifestPath := filepath.Join(sourcePath, "manifest.json")
- if !utils.FileExists(manifestPath) {
- return fmt.Errorf("source folder missing manifest.json: %s", sourcePath)
- }
-
- return nil
-}
-
-func handleExistingTarget(targetPath, sourcePath string) error {
- if !utils.FileExists(targetPath) {
- return nil // Nothing to handle
- }
-
- // Check if it's already a symlink to our source
- existingLink, err := os.Readlink(targetPath)
- if err == nil && existingLink == sourcePath {
- fmt.Printf("Symlink already exists and points to the correct source\n")
- return fmt.Errorf("symlink already exists") // This will cause early return in caller
- }
-
- // Handle case where target exists but is not a symlink to our source
- fmt.Printf("Target path '%s' already exists.\n", targetPath)
- fmt.Print("Do you want to replace it? (y/N): ")
- var response string
- _, err = fmt.Scanln(&response)
- if err != nil || strings.ToLower(response) != "y" {
- if err != nil {
- log.Debug("Error reading input, assuming 'no'", err)
- }
- return fmt.Errorf("operation canceled")
- }
-
- // Remove existing target
- if err := os.RemoveAll(targetPath); err != nil {
- return fmt.Errorf("failed to remove existing target %s: %w", targetPath, err)
- }
-
- return nil
-}
-
-func ensurePluginDirPermissions(dir string) {
- if err := os.Chmod(dir, pluginDirPermissions); err != nil {
- log.Error("Failed to set plugin directory permissions", "dir", dir, err)
- }
-
- // Apply permissions to all files in the directory
- entries, err := os.ReadDir(dir)
- if err != nil {
- log.Error("Failed to read plugin directory", "dir", dir, err)
- return
- }
-
- for _, entry := range entries {
- path := filepath.Join(dir, entry.Name())
- info, err := os.Stat(path)
- if err != nil {
- log.Error("Failed to stat file", "path", path, err)
- continue
- }
-
- mode := os.FileMode(pluginFilePermissions) // Files
- if info.IsDir() {
- mode = os.FileMode(pluginDirPermissions) // Directories
- ensurePluginDirPermissions(path) // Recursive
- }
-
- if err := os.Chmod(path, mode); err != nil {
- log.Error("Failed to set file permissions", "path", path, err)
- }
- }
-}
-
-func calculateSHA256(filePath string) string {
- file, err := os.Open(filePath)
- if err != nil {
- log.Error("Failed to open file for hashing", err)
- return "N/A"
- }
- defer file.Close()
-
- hasher := sha256.New()
- if _, err := io.Copy(hasher, file); err != nil {
- log.Error("Failed to calculate hash", err)
- return "N/A"
- }
-
- return hex.EncodeToString(hasher.Sum(nil))
-}
diff --git a/cmd/plugin_test.go b/cmd/plugin_test.go
deleted file mode 100644
index 3a4aefa88..000000000
--- a/cmd/plugin_test.go
+++ /dev/null
@@ -1,193 +0,0 @@
-package cmd
-
-import (
- "io"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/conf/configtest"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
- "github.com/spf13/cobra"
-)
-
-var _ = Describe("Plugin CLI Commands", func() {
- var tempDir string
- var cmd *cobra.Command
- var stdOut *os.File
- var origStdout *os.File
- var outReader *os.File
-
- // Helper to create a test plugin with the given name and details
- createTestPlugin := func(name, author, version string, capabilities []string) string {
- pluginDir := filepath.Join(tempDir, name)
- Expect(os.MkdirAll(pluginDir, 0755)).To(Succeed())
-
- // Create a properly formatted capabilities JSON array
- capabilitiesJSON := `"` + strings.Join(capabilities, `", "`) + `"`
-
- manifest := `{
- "name": "` + name + `",
- "author": "` + author + `",
- "version": "` + version + `",
- "description": "Plugin for testing",
- "website": "https://test.navidrome.org/` + name + `",
- "capabilities": [` + capabilitiesJSON + `],
- "permissions": {}
- }`
-
- Expect(os.WriteFile(filepath.Join(pluginDir, "manifest.json"), []byte(manifest), 0600)).To(Succeed())
-
- // Create a dummy WASM file
- wasmContent := []byte("dummy wasm content for testing")
- Expect(os.WriteFile(filepath.Join(pluginDir, "plugin.wasm"), wasmContent, 0600)).To(Succeed())
-
- return pluginDir
- }
-
- // Helper to execute a command and return captured output
- captureOutput := func(reader io.Reader) string {
- stdOut.Close()
- outputBytes, err := io.ReadAll(reader)
- Expect(err).NotTo(HaveOccurred())
- return string(outputBytes)
- }
-
- BeforeEach(func() {
- DeferCleanup(configtest.SetupConfig())
- tempDir = GinkgoT().TempDir()
-
- // Setup config
- conf.Server.Plugins.Enabled = true
- conf.Server.Plugins.Folder = tempDir
-
- // Create a command for testing
- cmd = &cobra.Command{Use: "test"}
-
- // Setup stdout capture
- origStdout = os.Stdout
- var err error
- outReader, stdOut, err = os.Pipe()
- Expect(err).NotTo(HaveOccurred())
- os.Stdout = stdOut
-
- DeferCleanup(func() {
- os.Stdout = origStdout
- })
- })
-
- AfterEach(func() {
- os.Stdout = origStdout
- if stdOut != nil {
- stdOut.Close()
- }
- if outReader != nil {
- outReader.Close()
- }
- })
-
- Describe("Plugin list command", func() {
- It("should list installed plugins", func() {
- // Create test plugins
- createTestPlugin("plugin1", "Test Author", "1.0.0", []string{"MetadataAgent"})
- createTestPlugin("plugin2", "Another Author", "2.1.0", []string{"Scrobbler"})
-
- // Execute command
- pluginList(cmd, []string{})
-
- // Verify output
- output := captureOutput(outReader)
-
- Expect(output).To(ContainSubstring("plugin1"))
- Expect(output).To(ContainSubstring("Test Author"))
- Expect(output).To(ContainSubstring("1.0.0"))
- Expect(output).To(ContainSubstring("MetadataAgent"))
-
- Expect(output).To(ContainSubstring("plugin2"))
- Expect(output).To(ContainSubstring("Another Author"))
- Expect(output).To(ContainSubstring("2.1.0"))
- Expect(output).To(ContainSubstring("Scrobbler"))
- })
- })
-
- Describe("Plugin info command", func() {
- It("should display information about an installed plugin", func() {
- // Create test plugin with multiple capabilities
- createTestPlugin("test-plugin", "Test Author", "1.0.0",
- []string{"MetadataAgent", "Scrobbler"})
-
- // Execute command
- pluginInfo(cmd, []string{"test-plugin"})
-
- // Verify output
- output := captureOutput(outReader)
-
- Expect(output).To(ContainSubstring("Name: test-plugin"))
- Expect(output).To(ContainSubstring("Author: Test Author"))
- Expect(output).To(ContainSubstring("Version: 1.0.0"))
- Expect(output).To(ContainSubstring("Description: Plugin for testing"))
- Expect(output).To(ContainSubstring("Capabilities: MetadataAgent, Scrobbler"))
- })
- })
-
- Describe("Plugin remove command", func() {
- It("should remove a regular plugin directory", func() {
- // Create test plugin
- pluginDir := createTestPlugin("regular-plugin", "Test Author", "1.0.0",
- []string{"MetadataAgent"})
-
- // Execute command
- pluginRemove(cmd, []string{"regular-plugin"})
-
- // Verify output
- output := captureOutput(outReader)
- Expect(output).To(ContainSubstring("Plugin 'regular-plugin' removed successfully"))
-
- // Verify directory is actually removed
- _, err := os.Stat(pluginDir)
- Expect(os.IsNotExist(err)).To(BeTrue())
- })
-
- It("should remove only the symlink for a development plugin", func() {
- // Create a real source directory
- sourceDir := filepath.Join(GinkgoT().TempDir(), "dev-plugin-source")
- Expect(os.MkdirAll(sourceDir, 0755)).To(Succeed())
-
- manifest := `{
- "name": "dev-plugin",
- "author": "Dev Author",
- "version": "0.1.0",
- "description": "Development plugin for testing",
- "website": "https://test.navidrome.org/dev-plugin",
- "capabilities": ["Scrobbler"],
- "permissions": {}
- }`
- Expect(os.WriteFile(filepath.Join(sourceDir, "manifest.json"), []byte(manifest), 0600)).To(Succeed())
-
- // Create a dummy WASM file
- wasmContent := []byte("dummy wasm content for testing")
- Expect(os.WriteFile(filepath.Join(sourceDir, "plugin.wasm"), wasmContent, 0600)).To(Succeed())
-
- // Create a symlink in the plugins directory
- symlinkPath := filepath.Join(tempDir, "dev-plugin")
- Expect(os.Symlink(sourceDir, symlinkPath)).To(Succeed())
-
- // Execute command
- pluginRemove(cmd, []string{"dev-plugin"})
-
- // Verify output
- output := captureOutput(outReader)
- Expect(output).To(ContainSubstring("Development plugin symlink 'dev-plugin' removed successfully"))
- Expect(output).To(ContainSubstring("target directory preserved"))
-
- // Verify the symlink is removed but source directory exists
- _, err := os.Lstat(symlinkPath)
- Expect(os.IsNotExist(err)).To(BeTrue())
-
- _, err = os.Stat(sourceDir)
- Expect(err).NotTo(HaveOccurred())
- })
- })
-})
diff --git a/cmd/root.go b/cmd/root.go
index 9618b16e6..5fdb591ff 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -9,7 +9,6 @@ import (
"time"
"github.com/go-chi/chi/v5/middleware"
- _ "github.com/navidrome/navidrome/adapters/taglib"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/db"
@@ -22,6 +21,13 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/sync/errgroup"
+
+ // Import adapters to register them
+ _ "github.com/navidrome/navidrome/adapters/deezer"
+ _ "github.com/navidrome/navidrome/adapters/gotaglib"
+ _ "github.com/navidrome/navidrome/adapters/lastfm"
+ _ "github.com/navidrome/navidrome/adapters/listenbrainz"
+ _ "github.com/navidrome/navidrome/adapters/taglib"
)
var (
@@ -189,7 +195,8 @@ func runInitialScan(ctx context.Context) func() error {
if err != nil {
return err
}
- scanNeeded := conf.Server.Scanner.ScanOnStartup || inProgress || fullScanRequired == "1" || pidHasChanged
+ scanOnStartup := conf.Server.Scanner.Enabled && conf.Server.Scanner.ScanOnStartup
+ scanNeeded := scanOnStartup || inProgress || fullScanRequired == "1" || pidHasChanged
time.Sleep(2 * time.Second) // Wait 2 seconds before the initial scan
if scanNeeded {
s := CreateScanner(ctx)
@@ -330,23 +337,20 @@ func startPlaybackServer(ctx context.Context) func() error {
// startPluginManager starts the plugin manager, if configured.
func startPluginManager(ctx context.Context) func() error {
return func() error {
+ manager := GetPluginManager(ctx)
if !conf.Server.Plugins.Enabled {
- log.Debug("Plugins are DISABLED")
+ log.Debug("Plugin system is DISABLED")
return nil
}
log.Info(ctx, "Starting plugin manager")
- // Get the manager instance and scan for plugins
- manager := GetPluginManager(ctx)
- manager.ScanPlugins()
-
- return nil
+ return manager.Start(ctx)
}
}
// TODO: Implement some struct tags to map flags to viper
func init() {
cobra.OnInitialize(func() {
- conf.InitConfig(cfgFile)
+ conf.InitConfig(cfgFile, true)
})
rootCmd.PersistentFlags().StringVarP(&cfgFile, "configfile", "c", "", `config file (default "./navidrome.toml")`)
@@ -374,6 +378,7 @@ func init() {
rootCmd.Flags().Duration("scaninterval", viper.GetDuration("scaninterval"), "how frequently to scan for changes in your music library")
rootCmd.Flags().String("uiloginbackgroundurl", viper.GetString("uiloginbackgroundurl"), "URL to a backaground image used in the Login page")
rootCmd.Flags().Bool("enabletranscodingconfig", viper.GetBool("enabletranscodingconfig"), "enables transcoding configuration in the UI")
+ rootCmd.Flags().Bool("enabletranscodingcancellation", viper.GetBool("enabletranscodingcancellation"), "enables transcoding context cancellation")
rootCmd.Flags().String("transcodingcachesize", viper.GetString("transcodingcachesize"), "size of transcoding cache")
rootCmd.Flags().String("imagecachesize", viper.GetString("imagecachesize"), "size of image (art work) cache. set to 0 to disable cache")
rootCmd.Flags().String("albumplaycountmode", viper.GetString("albumplaycountmode"), "how to compute playcount for albums. absolute (default) or normalized")
@@ -397,6 +402,7 @@ func init() {
_ = viper.BindPFlag("prometheus.metricspath", rootCmd.Flags().Lookup("prometheus.metricspath"))
_ = viper.BindPFlag("enabletranscodingconfig", rootCmd.Flags().Lookup("enabletranscodingconfig"))
+ _ = viper.BindPFlag("enabletranscodingcancellation", rootCmd.Flags().Lookup("enabletranscodingcancellation"))
_ = viper.BindPFlag("transcodingcachesize", rootCmd.Flags().Lookup("transcodingcachesize"))
_ = viper.BindPFlag("imagecachesize", rootCmd.Flags().Lookup("imagecachesize"))
}
diff --git a/cmd/scan.go b/cmd/scan.go
index d37ccd69f..d8a563396 100644
--- a/cmd/scan.go
+++ b/cmd/scan.go
@@ -1,13 +1,18 @@
package cmd
import (
+ "bufio"
"context"
"encoding/gob"
+ "fmt"
"os"
+ "strings"
"github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/scanner"
"github.com/navidrome/navidrome/utils/pl"
@@ -17,11 +22,15 @@ import (
var (
fullScan bool
subprocess bool
+ targets []string
+ targetFile string
)
func init() {
scanCmd.Flags().BoolVarP(&fullScan, "full", "f", false, "check all subfolders, ignoring timestamps")
scanCmd.Flags().BoolVarP(&subprocess, "subprocess", "", false, "run as subprocess (internal use)")
+ scanCmd.Flags().StringArrayVarP(&targets, "target", "t", []string{}, "list of libraryID:folderPath pairs, can be repeated (e.g., \"-t 1:Music/Rock -t 1:Music/Jazz -t 2:Classical\")")
+ scanCmd.Flags().StringVar(&targetFile, "target-file", "", "path to file containing targets (one libraryID:folderPath per line)")
rootCmd.AddCommand(scanCmd)
}
@@ -66,9 +75,27 @@ func runScanner(ctx context.Context) {
sqlDB := db.Db()
defer db.Db().Close()
ds := persistence.New(sqlDB)
- pls := core.NewPlaylists(ds)
+ pls := playlists.NewPlaylists(ds, core.NewImageUploadService())
- progress, err := scanner.CallScan(ctx, ds, pls, fullScan)
+ // Parse targets from command line or file
+ var scanTargets []model.ScanTarget
+ var err error
+
+ if targetFile != "" {
+ scanTargets, err = readTargetsFromFile(targetFile)
+ if err != nil {
+ log.Fatal(ctx, "Failed to read targets from file", err)
+ }
+ log.Info(ctx, "Scanning specific folders from file", "numTargets", len(scanTargets))
+ } else if len(targets) > 0 {
+ scanTargets, err = model.ParseTargets(targets)
+ if err != nil {
+ log.Fatal(ctx, "Failed to parse targets", err)
+ }
+ log.Info(ctx, "Scanning specific folders", "numTargets", len(scanTargets))
+ }
+
+ progress, err := scanner.CallScan(ctx, ds, pls, fullScan, scanTargets)
if err != nil {
log.Fatal(ctx, "Failed to scan", err)
}
@@ -80,3 +107,31 @@ func runScanner(ctx context.Context) {
trackScanInteractively(ctx, progress)
}
}
+
+// readTargetsFromFile reads scan targets from a file, one per line.
+// Each line should be in the format "libraryID:folderPath".
+// Empty lines and lines starting with # are ignored.
+func readTargetsFromFile(filePath string) ([]model.ScanTarget, error) {
+ file, err := os.Open(filePath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open target file: %w", err)
+ }
+ defer file.Close()
+
+ var targetStrings []string
+ scanner := bufio.NewScanner(file)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ // Skip empty lines and comments
+ if line == "" {
+ continue
+ }
+ targetStrings = append(targetStrings, line)
+ }
+
+ if err := scanner.Err(); err != nil {
+ return nil, fmt.Errorf("failed to read target file: %w", err)
+ }
+
+ return model.ParseTargets(targetStrings)
+}
diff --git a/cmd/scan_test.go b/cmd/scan_test.go
new file mode 100644
index 000000000..beeecca19
--- /dev/null
+++ b/cmd/scan_test.go
@@ -0,0 +1,89 @@
+package cmd
+
+import (
+ "os"
+ "path/filepath"
+
+ "github.com/navidrome/navidrome/model"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("readTargetsFromFile", func() {
+ var tempDir string
+
+ BeforeEach(func() {
+ var err error
+ tempDir, err = os.MkdirTemp("", "navidrome-test-")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ AfterEach(func() {
+ os.RemoveAll(tempDir)
+ })
+
+ It("reads valid targets from file", func() {
+ filePath := filepath.Join(tempDir, "targets.txt")
+ content := "1:Music/Rock\n2:Music/Jazz\n3:Classical\n"
+ err := os.WriteFile(filePath, []byte(content), 0600)
+ Expect(err).ToNot(HaveOccurred())
+
+ targets, err := readTargetsFromFile(filePath)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(3))
+ Expect(targets[0]).To(Equal(model.ScanTarget{LibraryID: 1, FolderPath: "Music/Rock"}))
+ Expect(targets[1]).To(Equal(model.ScanTarget{LibraryID: 2, FolderPath: "Music/Jazz"}))
+ Expect(targets[2]).To(Equal(model.ScanTarget{LibraryID: 3, FolderPath: "Classical"}))
+ })
+
+ It("skips empty lines", func() {
+ filePath := filepath.Join(tempDir, "targets.txt")
+ content := "1:Music/Rock\n\n2:Music/Jazz\n\n"
+ err := os.WriteFile(filePath, []byte(content), 0600)
+ Expect(err).ToNot(HaveOccurred())
+
+ targets, err := readTargetsFromFile(filePath)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(2))
+ })
+
+ It("trims whitespace", func() {
+ filePath := filepath.Join(tempDir, "targets.txt")
+ content := " 1:Music/Rock \n\t2:Music/Jazz\t\n"
+ err := os.WriteFile(filePath, []byte(content), 0600)
+ Expect(err).ToNot(HaveOccurred())
+
+ targets, err := readTargetsFromFile(filePath)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(2))
+ Expect(targets[0].FolderPath).To(Equal("Music/Rock"))
+ Expect(targets[1].FolderPath).To(Equal("Music/Jazz"))
+ })
+
+ It("returns error for non-existent file", func() {
+ _, err := readTargetsFromFile("/nonexistent/file.txt")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("failed to open target file"))
+ })
+
+ It("returns error for invalid target format", func() {
+ filePath := filepath.Join(tempDir, "targets.txt")
+ content := "invalid-format\n"
+ err := os.WriteFile(filePath, []byte(content), 0600)
+ Expect(err).ToNot(HaveOccurred())
+
+ _, err = readTargetsFromFile(filePath)
+ Expect(err).To(HaveOccurred())
+ })
+
+ It("handles mixed valid and empty lines", func() {
+ filePath := filepath.Join(tempDir, "targets.txt")
+ content := "\n1:Music/Rock\n\n\n2:Music/Jazz\n\n"
+ err := os.WriteFile(filePath, []byte(content), 0600)
+ Expect(err).ToNot(HaveOccurred())
+
+ targets, err := readTargetsFromFile(filePath)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(2))
+ })
+})
diff --git a/cmd/svc.go b/cmd/svc.go
index e277bd459..89ca08056 100644
--- a/cmd/svc.go
+++ b/cmd/svc.go
@@ -248,6 +248,7 @@ ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}}
TimeoutStopSec=20
RestartSec=120
EnvironmentFile=-/etc/sysconfig/{{.Name}}
+Environment="ND_SYSTEMD_PRIORITY_LOGGING=1"
DevicePolicy=closed
NoNewPrivileges=yes
diff --git a/cmd/user.go b/cmd/user.go
new file mode 100644
index 000000000..1abf157b7
--- /dev/null
+++ b/cmd/user.go
@@ -0,0 +1,477 @@
+package cmd
+
+import (
+ "context"
+ "encoding/csv"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/spf13/cobra"
+ "golang.org/x/term"
+)
+
+var (
+ email string
+ libraryIds []int
+ name string
+
+ removeEmail bool
+ removeName bool
+ setAdmin bool
+ setPassword bool
+ setRegularUser bool
+)
+
+func init() {
+ rootCmd.AddCommand(userRoot)
+
+ userCreateCommand.Flags().StringVarP(&userID, "username", "u", "", "username")
+
+ userCreateCommand.Flags().StringVarP(&email, "email", "e", "", "New user email")
+ userCreateCommand.Flags().IntSliceVarP(&libraryIds, "library-ids", "i", []int{}, "Comma-separated list of library IDs. Set the user's accessible libraries. If empty, the user can access all libraries. This is incompatible with admin, as admin can always access all libraries")
+
+ userCreateCommand.Flags().BoolVarP(&setAdmin, "admin", "a", false, "If set, make the user an admin. This user will have access to every library")
+ userCreateCommand.Flags().StringVar(&name, "name", "", "New user's name (this is separate from username used to log in)")
+
+ _ = userCreateCommand.MarkFlagRequired("username")
+
+ userRoot.AddCommand(userCreateCommand)
+
+ userDeleteCommand.Flags().StringVarP(&userID, "user", "u", "", "username or id")
+ _ = userDeleteCommand.MarkFlagRequired("user")
+ userRoot.AddCommand(userDeleteCommand)
+
+ userEditCommand.Flags().StringVarP(&userID, "user", "u", "", "username or id")
+
+ userEditCommand.Flags().BoolVar(&setAdmin, "set-admin", false, "If set, make the user an admin")
+ userEditCommand.Flags().BoolVar(&setRegularUser, "set-regular", false, "If set, make the user a non-admin")
+ userEditCommand.MarkFlagsMutuallyExclusive("set-admin", "set-regular")
+
+ userEditCommand.Flags().BoolVar(&removeEmail, "remove-email", false, "If set, clear the user's email")
+ userEditCommand.Flags().StringVarP(&email, "email", "e", "", "New user email")
+ userEditCommand.MarkFlagsMutuallyExclusive("email", "remove-email")
+
+ userEditCommand.Flags().BoolVar(&removeName, "remove-name", false, "If set, clear the user's name")
+ userEditCommand.Flags().StringVar(&name, "name", "", "New user name (this is separate from username used to log in)")
+ userEditCommand.MarkFlagsMutuallyExclusive("name", "remove-name")
+
+ userEditCommand.Flags().BoolVar(&setPassword, "set-password", false, "If set, the user's new password will be prompted on the CLI")
+
+ userEditCommand.Flags().IntSliceVarP(&libraryIds, "library-ids", "i", []int{}, "Comma-separated list of library IDs. Set the user's accessible libraries by id")
+
+ _ = userEditCommand.MarkFlagRequired("user")
+ userRoot.AddCommand(userEditCommand)
+
+ userListCommand.Flags().StringVarP(&outputFormat, "format", "f", "csv", "output format [supported values: csv, json]")
+ userRoot.AddCommand(userListCommand)
+}
+
+var (
+ userRoot = &cobra.Command{
+ Use: "user",
+ Short: "Administer users",
+ Long: "Create, delete, list, or update users",
+ }
+
+ userCreateCommand = &cobra.Command{
+ Use: "create",
+ Aliases: []string{"c"},
+ Short: "Create a new user",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCreateUser(cmd.Context())
+ },
+ }
+
+ userDeleteCommand = &cobra.Command{
+ Use: "delete",
+ Aliases: []string{"d"},
+ Short: "Deletes an existing user",
+ Run: func(cmd *cobra.Command, args []string) {
+ runDeleteUser(cmd.Context())
+ },
+ }
+
+ userEditCommand = &cobra.Command{
+ Use: "edit",
+ Aliases: []string{"e"},
+ Short: "Edit a user",
+ Long: "Edit the password, admin status, and/or library access",
+ Run: func(cmd *cobra.Command, args []string) {
+ runUserEdit(cmd.Context())
+ },
+ }
+
+ userListCommand = &cobra.Command{
+ Use: "list",
+ Short: "List users",
+ Run: func(cmd *cobra.Command, args []string) {
+ runUserList(cmd.Context())
+ },
+ }
+)
+
+func promptPassword() string {
+ for {
+ fmt.Print("Enter new password (press enter with no password to cancel): ")
+ // This cast is necessary for some platforms
+ password, err := term.ReadPassword(int(syscall.Stdin)) //nolint:unconvert
+
+ if err != nil {
+ log.Fatal("Error getting password", err)
+ }
+
+ fmt.Print("\nConfirm new password (press enter with no password to cancel): ")
+ confirmation, err := term.ReadPassword(int(syscall.Stdin)) //nolint:unconvert
+
+ if err != nil {
+ log.Fatal("Error getting password confirmation", err)
+ }
+
+ // clear the line.
+ fmt.Println()
+
+ pass := string(password)
+ confirm := string(confirmation)
+
+ if pass == "" {
+ return ""
+ }
+
+ if pass == confirm {
+ return pass
+ }
+
+ fmt.Println("Password and password confirmation do not match")
+ }
+}
+
+func libraryError(libraries model.Libraries) error {
+ ids := make([]int, len(libraries))
+ for idx, library := range libraries {
+ ids[idx] = library.ID
+ }
+ return fmt.Errorf("not all available libraries found. Requested ids: %v, Found libraries: %v", libraryIds, ids)
+}
+
+func runCreateUser(ctx context.Context) {
+ password := promptPassword()
+ if password == "" {
+ log.Fatal("Empty password provided, user creation cancelled")
+ }
+
+ user := model.User{
+ UserName: userID,
+ Email: email,
+ Name: name,
+ IsAdmin: setAdmin,
+ NewPassword: password,
+ }
+
+ if user.Name == "" {
+ user.Name = userID
+ }
+
+ ds, ctx := getAdminContext(ctx)
+
+ err := ds.WithTx(func(tx model.DataStore) error {
+ existingUser, err := tx.User(ctx).FindByUsername(userID)
+ if existingUser != nil {
+ return fmt.Errorf("existing user '%s'", userID)
+ }
+
+ if err != nil && !errors.Is(err, model.ErrNotFound) {
+ return fmt.Errorf("failed to check existing username: %w", err)
+ }
+
+ if len(libraryIds) > 0 && !setAdmin {
+ user.Libraries, err = tx.Library(ctx).GetAll(model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}})
+ if err != nil {
+ return err
+ }
+
+ if len(user.Libraries) != len(libraryIds) {
+ return libraryError(user.Libraries)
+ }
+ } else {
+ user.Libraries, err = tx.Library(ctx).GetAll()
+ if err != nil {
+ return err
+ }
+ }
+
+ err = tx.User(ctx).Put(&user)
+ if err != nil {
+ return err
+ }
+
+ updatedIds := make([]int, len(user.Libraries))
+ for idx, lib := range user.Libraries {
+ updatedIds[idx] = lib.ID
+ }
+
+ err = tx.User(ctx).SetUserLibraries(user.ID, updatedIds)
+ return err
+ })
+
+ if err != nil {
+ log.Fatal(ctx, err)
+ }
+
+ log.Info(ctx, "Successfully created user", "id", user.ID, "username", user.UserName)
+}
+
+func runDeleteUser(ctx context.Context) {
+ ds, ctx := getAdminContext(ctx)
+
+ var err error
+ var user *model.User
+
+ err = ds.WithTx(func(tx model.DataStore) error {
+ count, err := tx.User(ctx).CountAll()
+ if err != nil {
+ return err
+ }
+
+ if count == 1 {
+ return errors.New("refusing to delete the last user")
+ }
+
+ user, err = getUser(ctx, userID, tx)
+ if err != nil {
+ return err
+ }
+
+ return tx.User(ctx).Delete(user.ID)
+ })
+
+ if err != nil {
+ log.Fatal(ctx, "Failed to delete user", err)
+ }
+
+ log.Info(ctx, "Deleted user", "username", user.UserName)
+}
+
+func runUserEdit(ctx context.Context) {
+ ds, ctx := getAdminContext(ctx)
+
+ var err error
+ var user *model.User
+ changes := []string{}
+
+ err = ds.WithTx(func(tx model.DataStore) error {
+ var newLibraries model.Libraries
+
+ user, err = getUser(ctx, userID, tx)
+ if err != nil {
+ return err
+ }
+
+ if len(libraryIds) > 0 && !setAdmin {
+ libraries, err := tx.Library(ctx).GetAll(model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}})
+
+ if err != nil {
+ return err
+ }
+
+ if len(libraries) != len(libraryIds) {
+ return libraryError(libraries)
+ }
+
+ newLibraries = libraries
+ changes = append(changes, "updated library ids")
+ }
+
+ if setAdmin && !user.IsAdmin {
+ libraries, err := tx.Library(ctx).GetAll()
+ if err != nil {
+ return err
+ }
+
+ user.IsAdmin = true
+ user.Libraries = libraries
+ changes = append(changes, "set admin")
+
+ newLibraries = libraries
+ }
+
+ if setRegularUser && user.IsAdmin {
+ user.IsAdmin = false
+ changes = append(changes, "set regular user")
+ }
+
+ if setPassword {
+ password := promptPassword()
+
+ if password != "" {
+ user.NewPassword = password
+ changes = append(changes, "updated password")
+ }
+ }
+
+ if email != "" && email != user.Email {
+ user.Email = email
+ changes = append(changes, "updated email")
+ } else if removeEmail && user.Email != "" {
+ user.Email = ""
+ changes = append(changes, "removed email")
+ }
+
+ if name != "" && name != user.Name {
+ user.Name = name
+ changes = append(changes, "updated name")
+ } else if removeName && user.Name != "" {
+ user.Name = ""
+ changes = append(changes, "removed name")
+ }
+
+ if len(changes) == 0 {
+ return nil
+ }
+
+ err := tx.User(ctx).Put(user)
+ if err != nil {
+ return err
+ }
+
+ if len(newLibraries) > 0 {
+ updatedIds := make([]int, len(newLibraries))
+ for idx, lib := range newLibraries {
+ updatedIds[idx] = lib.ID
+ }
+
+ err := tx.User(ctx).SetUserLibraries(user.ID, updatedIds)
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ log.Fatal(ctx, "Failed to update user", err)
+ }
+
+ if len(changes) == 0 {
+ log.Info(ctx, "No changes for user", "user", user.UserName)
+ } else {
+ log.Info(ctx, "Updated user", "user", user.UserName, "changes", strings.Join(changes, ", "))
+ }
+}
+
+type displayLibrary struct {
+ ID int `json:"id"`
+ Path string `json:"path"`
+}
+
+type displayUser struct {
+ Id string `json:"id"`
+ Username string `json:"username"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Admin bool `json:"admin"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+ LastAccess *time.Time `json:"lastAccess"`
+ LastLogin *time.Time `json:"lastLogin"`
+ Libraries []displayLibrary `json:"libraries"`
+}
+
+func runUserList(ctx context.Context) {
+ if outputFormat != "csv" && outputFormat != "json" {
+ log.Fatal("Invalid output format. Must be one of csv, json", "format", outputFormat)
+ }
+
+ ds, ctx := getAdminContext(ctx)
+
+ users, err := ds.User(ctx).ReadAll()
+ if err != nil {
+ log.Fatal(ctx, "Failed to retrieve users", err)
+ }
+
+ userList := users.(model.Users)
+
+ if outputFormat == "csv" {
+ w := csv.NewWriter(os.Stdout)
+ _ = w.Write([]string{
+ "user id",
+ "username",
+ "user's name",
+ "user email",
+ "admin",
+ "created at",
+ "updated at",
+ "last access",
+ "last login",
+ "libraries",
+ })
+ for _, user := range userList {
+ paths := make([]string, len(user.Libraries))
+
+ for idx, library := range user.Libraries {
+ paths[idx] = fmt.Sprintf("%d:%s", library.ID, library.Path)
+ }
+
+ var lastAccess, lastLogin string
+
+ if user.LastAccessAt != nil {
+ lastAccess = user.LastAccessAt.Format(time.RFC3339Nano)
+ } else {
+ lastAccess = "never"
+ }
+
+ if user.LastLoginAt != nil {
+ lastLogin = user.LastLoginAt.Format(time.RFC3339Nano)
+ } else {
+ lastLogin = "never"
+ }
+
+ _ = w.Write([]string{
+ user.ID,
+ user.UserName,
+ user.Name,
+ user.Email,
+ strconv.FormatBool(user.IsAdmin),
+ user.CreatedAt.Format(time.RFC3339Nano),
+ user.UpdatedAt.Format(time.RFC3339Nano),
+ lastAccess,
+ lastLogin,
+ fmt.Sprintf("'%s'", strings.Join(paths, "|")),
+ })
+ }
+ w.Flush()
+ } else {
+ users := make([]displayUser, len(userList))
+ for idx, user := range userList {
+ paths := make([]displayLibrary, len(user.Libraries))
+
+ for idx, library := range user.Libraries {
+ paths[idx].ID = library.ID
+ paths[idx].Path = library.Path
+ }
+
+ users[idx].Id = user.ID
+ users[idx].Username = user.UserName
+ users[idx].Name = user.Name
+ users[idx].Email = user.Email
+ users[idx].Admin = user.IsAdmin
+ users[idx].CreatedAt = user.CreatedAt
+ users[idx].UpdatedAt = user.UpdatedAt
+ users[idx].LastAccess = user.LastAccessAt
+ users[idx].LastLogin = user.LastLoginAt
+ users[idx].Libraries = paths
+ }
+
+ j, _ := json.Marshal(users)
+ fmt.Printf("%s\n", j)
+ }
+}
diff --git a/cmd/utils.go b/cmd/utils.go
new file mode 100644
index 000000000..81d646cf1
--- /dev/null
+++ b/cmd/utils.go
@@ -0,0 +1,42 @@
+package cmd
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/navidrome/navidrome/core/auth"
+ "github.com/navidrome/navidrome/db"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/persistence"
+)
+
+func getAdminContext(ctx context.Context) (model.DataStore, context.Context) {
+ sqlDB := db.Db()
+ ds := persistence.New(sqlDB)
+ ctx = auth.WithAdminUser(ctx, ds)
+ u, _ := request.UserFrom(ctx)
+ if !u.IsAdmin {
+ log.Fatal(ctx, "There must be at least one admin user to run this command.")
+ }
+ return ds, ctx
+}
+
+func getUser(ctx context.Context, id string, ds model.DataStore) (*model.User, error) {
+ user, err := ds.User(ctx).FindByUsername(id)
+
+ if err != nil && !errors.Is(err, model.ErrNotFound) {
+ return nil, fmt.Errorf("finding user by name: %w", err)
+ }
+
+ if errors.Is(err, model.ErrNotFound) {
+ user, err = ds.User(ctx).Get(id)
+ if err != nil {
+ return nil, fmt.Errorf("finding user by id: %w", err)
+ }
+ }
+
+ return user, nil
+}
diff --git a/cmd/wire_gen.go b/cmd/wire_gen.go
index 187ab488d..5b9fd648f 100644
--- a/cmd/wire_gen.go
+++ b/cmd/wire_gen.go
@@ -1,6 +1,6 @@
// Code generated by Wire. DO NOT EDIT.
-//go:generate go run -mod=mod github.com/google/wire/cmd/wire gen -tags "netgo"
+//go:generate go run -mod=mod github.com/google/wire/cmd/wire gen -tags "netgo sqlite_fts5"
//go:build !wireinject
// +build !wireinject
@@ -9,16 +9,19 @@ package cmd
import (
"context"
"github.com/google/wire"
+ "github.com/navidrome/navidrome/adapters/lastfm"
+ "github.com/navidrome/navidrome/adapters/listenbrainz"
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/agents"
- "github.com/navidrome/navidrome/core/agents/lastfm"
- "github.com/navidrome/navidrome/core/agents/listenbrainz"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/core/lyrics"
"github.com/navidrome/navidrome/core/metrics"
"github.com/navidrome/navidrome/core/playback"
+ "github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/core/scrobbler"
+ "github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
@@ -32,6 +35,10 @@ import (
)
import (
+ _ "github.com/navidrome/navidrome/adapters/deezer"
+ _ "github.com/navidrome/navidrome/adapters/gotaglib"
+ _ "github.com/navidrome/navidrome/adapters/lastfm"
+ _ "github.com/navidrome/navidrome/adapters/listenbrainz"
_ "github.com/navidrome/navidrome/adapters/taglib"
)
@@ -47,9 +54,7 @@ func CreateServer() *server.Server {
sqlDB := db.Db()
dataStore := persistence.New(sqlDB)
broker := events.GetBroker()
- metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
- insights := metrics.GetInstance(dataStore, manager)
+ insights := metrics.GetInstance(dataStore)
serverServer := server.New(dataStore, broker, insights)
return serverServer
}
@@ -58,21 +63,24 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
sqlDB := db.Db()
dataStore := persistence.New(sqlDB)
share := core.NewShare(dataStore)
- playlists := core.NewPlaylists(dataStore)
- metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
- insights := metrics.GetInstance(dataStore, manager)
+ imageUploadService := core.NewImageUploadService()
+ playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
+ insights := metrics.GetInstance(dataStore)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
+ broker := events.GetBroker()
+ metricsMetrics := metrics.GetPrometheusInstance(dataStore)
+ manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
provider := external.NewProvider(dataStore, agentsAgents)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
- broker := events.GetBroker()
- scannerScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlists, metricsMetrics)
- watcher := scanner.GetWatcher(dataStore, scannerScanner)
- library := core.NewLibrary(dataStore, scannerScanner, watcher, broker)
- router := nativeapi.New(dataStore, share, playlists, insights, library)
+ modelScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlistsPlaylists, metricsMetrics)
+ watcher := scanner.GetWatcher(dataStore, modelScanner)
+ library := core.NewLibrary(dataStore, modelScanner, watcher, broker, manager)
+ user := core.NewUser(dataStore, manager)
+ maintenance := core.NewMaintenance(dataStore)
+ router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, imageUploadService)
return router
}
@@ -81,23 +89,26 @@ func CreateSubsonicAPIRouter(ctx context.Context) *subsonic.Router {
dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
+ broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
+ manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
provider := external.NewProvider(dataStore, agentsAgents)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
- transcodingCache := core.GetTranscodingCache()
- mediaStreamer := core.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
+ transcodingCache := stream.GetTranscodingCache()
+ mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
share := core.NewShare(dataStore)
archiver := core.NewArchiver(mediaStreamer, dataStore, share)
players := core.NewPlayers(dataStore)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
- broker := events.GetBroker()
- playlists := core.NewPlaylists(dataStore)
- scannerScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlists, metricsMetrics)
+ imageUploadService := core.NewImageUploadService()
+ playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
+ modelScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlistsPlaylists, metricsMetrics)
playTracker := scrobbler.GetPlayTracker(dataStore, broker, manager)
playbackServer := playback.GetInstance(dataStore)
- router := subsonic.New(dataStore, artworkArtwork, mediaStreamer, archiver, players, provider, scannerScanner, broker, playlists, playTracker, share, playbackServer, metricsMetrics)
+ lyricsLyrics := lyrics.NewLyrics(manager)
+ transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
+ router := subsonic.New(dataStore, artworkArtwork, mediaStreamer, archiver, players, provider, modelScanner, broker, playlistsPlaylists, playTracker, share, playbackServer, metricsMetrics, lyricsLyrics, transcodeDecider)
return router
}
@@ -106,13 +117,14 @@ func CreatePublicRouter() *public.Router {
dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
+ broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
+ manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
provider := external.NewProvider(dataStore, agentsAgents)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
- transcodingCache := core.GetTranscodingCache()
- mediaStreamer := core.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
+ transcodingCache := stream.GetTranscodingCache()
+ mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
share := core.NewShare(dataStore)
archiver := core.NewArchiver(mediaStreamer, dataStore, share)
router := public.New(dataStore, artworkArtwork, mediaStreamer, share, archiver)
@@ -136,9 +148,7 @@ func CreateListenBrainzRouter() *listenbrainz.Router {
func CreateInsights() metrics.Insights {
sqlDB := db.Db()
dataStore := persistence.New(sqlDB)
- metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
- insights := metrics.GetInstance(dataStore, manager)
+ insights := metrics.GetInstance(dataStore)
return insights
}
@@ -149,21 +159,22 @@ func CreatePrometheus() metrics.Metrics {
return metricsMetrics
}
-func CreateScanner(ctx context.Context) scanner.Scanner {
+func CreateScanner(ctx context.Context) model.Scanner {
sqlDB := db.Db()
dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
+ broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
+ manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
provider := external.NewProvider(dataStore, agentsAgents)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
- broker := events.GetBroker()
- playlists := core.NewPlaylists(dataStore)
- scannerScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlists, metricsMetrics)
- return scannerScanner
+ imageUploadService := core.NewImageUploadService()
+ playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
+ modelScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlistsPlaylists, metricsMetrics)
+ return modelScanner
}
func CreateScanWatcher(ctx context.Context) scanner.Watcher {
@@ -171,16 +182,17 @@ func CreateScanWatcher(ctx context.Context) scanner.Watcher {
dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
+ broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
+ manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
provider := external.NewProvider(dataStore, agentsAgents)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
- broker := events.GetBroker()
- playlists := core.NewPlaylists(dataStore)
- scannerScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlists, metricsMetrics)
- watcher := scanner.GetWatcher(dataStore, scannerScanner)
+ imageUploadService := core.NewImageUploadService()
+ playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
+ modelScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlistsPlaylists, metricsMetrics)
+ watcher := scanner.GetWatcher(dataStore, modelScanner)
return watcher
}
@@ -191,19 +203,20 @@ func GetPlaybackServer() playback.PlaybackServer {
return playbackServer
}
-func getPluginManager() plugins.Manager {
+func getPluginManager() *plugins.Manager {
sqlDB := db.Db()
dataStore := persistence.New(sqlDB)
+ broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
- manager := plugins.GetManager(dataStore, metricsMetrics)
+ manager := plugins.GetManager(dataStore, broker, metricsMetrics)
return manager
}
// wire_injectors.go:
-var allProviders = wire.NewSet(core.Set, artwork.Set, server.New, subsonic.New, nativeapi.New, public.New, persistence.New, lastfm.NewRouter, listenbrainz.NewRouter, events.GetBroker, scanner.New, scanner.GetWatcher, plugins.GetManager, metrics.GetPrometheusInstance, db.Db, wire.Bind(new(agents.PluginLoader), new(plugins.Manager)), wire.Bind(new(scrobbler.PluginLoader), new(plugins.Manager)), wire.Bind(new(metrics.PluginLoader), new(plugins.Manager)), wire.Bind(new(core.Scanner), new(scanner.Scanner)), wire.Bind(new(core.Watcher), new(scanner.Watcher)))
+var allProviders = wire.NewSet(core.Set, artwork.Set, server.New, subsonic.New, nativeapi.New, public.New, persistence.New, lastfm.NewRouter, listenbrainz.NewRouter, events.GetBroker, scanner.New, scanner.GetWatcher, metrics.GetPrometheusInstance, db.Db, plugins.GetManager, wire.Bind(new(agents.PluginLoader), new(*plugins.Manager)), wire.Bind(new(scrobbler.PluginLoader), new(*plugins.Manager)), wire.Bind(new(lyrics.PluginLoader), new(*plugins.Manager)), wire.Bind(new(nativeapi.PluginManager), new(*plugins.Manager)), wire.Bind(new(core.PluginUnloader), new(*plugins.Manager)), wire.Bind(new(plugins.PluginMetricsRecorder), new(metrics.Metrics)), wire.Bind(new(core.Watcher), new(scanner.Watcher)))
-func GetPluginManager(ctx context.Context) plugins.Manager {
+func GetPluginManager(ctx context.Context) *plugins.Manager {
manager := getPluginManager()
manager.SetSubsonicRouter(CreateSubsonicAPIRouter(ctx))
return manager
diff --git a/cmd/wire_injectors.go b/cmd/wire_injectors.go
index e8759ac53..d87a8d6d3 100644
--- a/cmd/wire_injectors.go
+++ b/cmd/wire_injectors.go
@@ -6,11 +6,12 @@ import (
"context"
"github.com/google/wire"
+ "github.com/navidrome/navidrome/adapters/lastfm"
+ "github.com/navidrome/navidrome/adapters/listenbrainz"
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/agents"
- "github.com/navidrome/navidrome/core/agents/lastfm"
- "github.com/navidrome/navidrome/core/agents/listenbrainz"
"github.com/navidrome/navidrome/core/artwork"
+ "github.com/navidrome/navidrome/core/lyrics"
"github.com/navidrome/navidrome/core/metrics"
"github.com/navidrome/navidrome/core/playback"
"github.com/navidrome/navidrome/core/scrobbler"
@@ -39,13 +40,15 @@ var allProviders = wire.NewSet(
events.GetBroker,
scanner.New,
scanner.GetWatcher,
- plugins.GetManager,
metrics.GetPrometheusInstance,
db.Db,
- wire.Bind(new(agents.PluginLoader), new(plugins.Manager)),
- wire.Bind(new(scrobbler.PluginLoader), new(plugins.Manager)),
- wire.Bind(new(metrics.PluginLoader), new(plugins.Manager)),
- wire.Bind(new(core.Scanner), new(scanner.Scanner)),
+ plugins.GetManager,
+ wire.Bind(new(agents.PluginLoader), new(*plugins.Manager)),
+ wire.Bind(new(scrobbler.PluginLoader), new(*plugins.Manager)),
+ wire.Bind(new(lyrics.PluginLoader), new(*plugins.Manager)),
+ wire.Bind(new(nativeapi.PluginManager), new(*plugins.Manager)),
+ wire.Bind(new(core.PluginUnloader), new(*plugins.Manager)),
+ wire.Bind(new(plugins.PluginMetricsRecorder), new(metrics.Metrics)),
wire.Bind(new(core.Watcher), new(scanner.Watcher)),
)
@@ -103,7 +106,7 @@ func CreatePrometheus() metrics.Metrics {
))
}
-func CreateScanner(ctx context.Context) scanner.Scanner {
+func CreateScanner(ctx context.Context) model.Scanner {
panic(wire.Build(
allProviders,
))
@@ -121,13 +124,13 @@ func GetPlaybackServer() playback.PlaybackServer {
))
}
-func getPluginManager() plugins.Manager {
+func getPluginManager() *plugins.Manager {
panic(wire.Build(
allProviders,
))
}
-func GetPluginManager(ctx context.Context) plugins.Manager {
+func GetPluginManager(ctx context.Context) *plugins.Manager {
manager := getPluginManager()
manager.SetSubsonicRouter(CreateSubsonicAPIRouter(ctx))
return manager
diff --git a/conf/buildtags/buildtags.go b/conf/buildtags/buildtags.go
deleted file mode 100644
index 5fc125087..000000000
--- a/conf/buildtags/buildtags.go
+++ /dev/null
@@ -1,4 +0,0 @@
-package buildtags
-
-// This file is left intentionally empty. It is used to make sure the package is not empty, in the case all
-// required build tags are disabled.
diff --git a/conf/buildtags/doc.go b/conf/buildtags/doc.go
new file mode 100644
index 000000000..f637b6355
--- /dev/null
+++ b/conf/buildtags/doc.go
@@ -0,0 +1,6 @@
+// Package buildtags provides compile-time enforcement of required build tags.
+//
+// Each file in this package is guarded by a build constraint and exports a variable
+// that main.go references. If a required tag is missing during compilation, the build
+// fails with an "undefined" error, directing the developer to use `make build`.
+package buildtags
diff --git a/conf/buildtags/netgo.go b/conf/buildtags/netgo.go
index 0062ad2bc..407004703 100644
--- a/conf/buildtags/netgo.go
+++ b/conf/buildtags/netgo.go
@@ -2,10 +2,6 @@
package buildtags
-// NOTICE: This file was created to force the inclusion of the `netgo` tag when compiling the project.
-// If the tag is not included, the compilation will fail because this variable won't be defined, and the `main.go`
-// file requires it.
-
-// Why this tag is required? See https://github.com/navidrome/navidrome/issues/700
+// The `netgo` tag is required when compiling the project. See https://github.com/navidrome/navidrome/issues/700
var NETGO = true
diff --git a/conf/buildtags/sqlite_fts5.go b/conf/buildtags/sqlite_fts5.go
new file mode 100644
index 000000000..1476e04cd
--- /dev/null
+++ b/conf/buildtags/sqlite_fts5.go
@@ -0,0 +1,8 @@
+//go:build sqlite_fts5
+
+package buildtags
+
+// FTS5 is required for full-text search. Without this tag, the SQLite driver
+// won't include FTS5 support, causing runtime failures on migrations and search queries.
+
+var SQLITE_FTS5 = true
diff --git a/conf/configuration.go b/conf/configuration.go
index 7292c7dfe..5f74d6db0 100644
--- a/conf/configuration.go
+++ b/conf/configuration.go
@@ -1,11 +1,13 @@
package conf
import (
+ "cmp"
"fmt"
"net/url"
"os"
"path/filepath"
"runtime"
+ "slices"
"strings"
"time"
@@ -14,8 +16,8 @@ import (
"github.com/kr/pretty"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/scheduler"
"github.com/navidrome/navidrome/utils/run"
- "github.com/robfig/cron/v3"
"github.com/spf13/viper"
)
@@ -41,8 +43,10 @@ type configOptions struct {
UIWelcomeMessage string
MaxSidebarPlaylists int
EnableTranscodingConfig bool
+ EnableTranscodingCancellation bool
EnableDownloads bool
EnableExternalServices bool
+ EnableM3UExternalAlbumArt bool
EnableInsightsCollector bool
EnableMediaFileCoverArt bool
TranscodingCacheSize string
@@ -55,7 +59,8 @@ type configOptions struct {
SmartPlaylistRefreshDelay time.Duration
AutoTranscodeDownload bool
DefaultDownsamplingFormat string
- SearchFullString bool
+ Search searchOptions `json:",omitzero"`
+ SimilarSongsMatchThreshold int
RecentlyAddedByModTime bool
PreferSortTags bool
IgnoredArticles string
@@ -64,13 +69,16 @@ type configOptions struct {
MPVPath string
MPVCmdTemplate string
CoverArtPriority string
- CoverJpegQuality int
+ CoverArtQuality int
ArtistArtPriority string
+ ArtistImageFolder string
+ DiscArtPriority string
LyricsPriority string
EnableGravatar bool
EnableFavourites bool
EnableStarRating bool
EnableUserEditing bool
+ EnableCoverArtUpload bool
EnableSharing bool
ShareURL string
DefaultShareExpiration time.Duration
@@ -78,6 +86,7 @@ type configOptions struct {
DefaultTheme string
DefaultLanguage string
DefaultUIVolume int
+ UISearchDebounceMs int
EnableReplayGain bool
EnableCoverAnimation bool
EnableNowPlaying bool
@@ -86,11 +95,9 @@ type configOptions struct {
AuthRequestLimit int
AuthWindowLength time.Duration
PasswordEncryptionKey string
- ReverseProxyUserHeader string
- ReverseProxyWhitelist string
+ ExtAuth extAuthOptions
Plugins pluginsOptions
- PluginConfig map[string]map[string]string
- HTTPSecurityHeaders secureOptions `json:",omitzero"`
+ HTTPHeaders httpHeaderOptions `json:",omitzero"`
Prometheus prometheusOptions `json:",omitzero"`
Scanner scannerOptions `json:",omitzero"`
Jukebox jukeboxOptions `json:",omitzero"`
@@ -99,37 +106,42 @@ type configOptions struct {
Inspect inspectOptions `json:",omitzero"`
Subsonic subsonicOptions `json:",omitzero"`
LastFM lastfmOptions `json:",omitzero"`
- Spotify spotifyOptions `json:",omitzero"`
Deezer deezerOptions `json:",omitzero"`
ListenBrainz listenBrainzOptions `json:",omitzero"`
- Tags map[string]TagConf `json:",omitempty"`
+ EnableScrobbleHistory bool
+ Tags map[string]TagConf `json:",omitempty"`
Agents string
// DevFlags. These are used to enable/disable debugging and incomplete features
- DevLogLevels map[string]string `json:",omitempty"`
- DevLogSourceLine bool
- DevEnableProfiler bool
- DevAutoCreateAdminPassword string
- DevAutoLoginUsername string
- DevActivityPanel bool
- DevActivityPanelUpdateRate time.Duration
- DevSidebarPlaylists bool
- DevShowArtistPage bool
- DevUIShowConfig bool
- DevNewEventStream bool
- DevOffsetOptimize int
- DevArtworkMaxRequests int
- DevArtworkThrottleBacklogLimit int
- DevArtworkThrottleBacklogTimeout time.Duration
- DevArtistInfoTimeToLive time.Duration
- DevAlbumInfoTimeToLive time.Duration
- DevExternalScanner bool
- DevScannerThreads uint
- DevInsightsInitialDelay time.Duration
- DevEnablePlayerInsights bool
- DevEnablePluginsInsights bool
- DevPluginCompilationTimeout time.Duration
- DevExternalArtistFetchMultiplier float64
+ DevLogLevels map[string]string `json:",omitempty"`
+ DevLogSourceLine bool
+ DevEnableProfiler bool
+ DevAutoCreateAdminPassword string
+ DevAutoLoginUsername string
+ DevActivityPanel bool
+ DevActivityPanelUpdateRate time.Duration
+ DevSidebarPlaylists bool
+ DevShowArtistPage bool
+ DevUIShowConfig bool
+ DevNewEventStream bool
+ DevOffsetOptimize int
+ DevArtworkMaxRequests int
+ DevArtworkThrottleBacklogLimit int
+ DevArtworkThrottleBacklogTimeout time.Duration
+ DevArtistInfoTimeToLive time.Duration
+ DevAlbumInfoTimeToLive time.Duration
+ DevExternalScanner bool
+ DevScannerThreads uint
+ DevSelectiveWatcher bool
+ DevInsightsInitialDelay time.Duration
+ DevEnablePlayerInsights bool
+ DevEnablePluginsInsights bool
+ DevPluginCompilationTimeout time.Duration
+ DevExternalArtistFetchMultiplier float64
+ DevOptimizeDB bool
+ DevPreserveUnicodeInExternalCalls bool
+ DevEnableMediaFileProbe bool
+ DevJpegCoverArt bool
}
type scannerOptions struct {
@@ -147,9 +159,12 @@ type scannerOptions struct {
type subsonicOptions struct {
AppendSubtitle bool
+ AppendAlbumVersion bool
ArtistParticipations bool
DefaultReportRealPath bool
+ EnableAverageRating bool
LegacyClients string
+ MinimalClients string
}
type TagConf struct {
@@ -163,34 +178,38 @@ type TagConf struct {
type lastfmOptions struct {
Enabled bool
- ApiKey string
- Secret string
+ ApiKey string //nolint:gosec
+ Secret string //nolint:gosec
Language string
ScrobbleFirstArtistOnly bool
-}
-type spotifyOptions struct {
- ID string
- Secret string
+ // Computed values
+ Languages []string // Computed from Language, split by comma
}
type deezerOptions struct {
- Enabled bool
+ Enabled bool
+ Language string
+
+ // Computed values
+ Languages []string // Computed from Language, split by comma
}
type listenBrainzOptions struct {
- Enabled bool
- BaseURL string
+ Enabled bool
+ BaseURL string
+ ArtistAlgorithm string
+ TrackAlgorithm string
}
-type secureOptions struct {
- CustomFrameOptionsValue string
+type httpHeaderOptions struct {
+ FrameOptions string
}
type prometheusOptions struct {
Enabled bool
MetricsPath string
- Password string
+ Password string //nolint:gosec
}
type AudioDeviceDefinition []string
@@ -221,9 +240,22 @@ type inspectOptions struct {
}
type pluginsOptions struct {
- Enabled bool
- Folder string
- CacheSize string
+ Enabled bool
+ Folder string
+ CacheSize string
+ AutoReload bool
+ LogLevel string
+}
+
+type extAuthOptions struct {
+ TrustedSources string
+ UserHeader string
+ LogoutURL string
+}
+
+type searchOptions struct {
+ Backend string
+ FullString bool
}
var (
@@ -244,6 +276,12 @@ func LoadFromFile(confFile string) {
func Load(noConfigDump bool) {
parseIniFileConfiguration()
+ // Map deprecated options to their new names for backwards compatibility
+ mapDeprecatedOption("ReverseProxyWhitelist", "ExtAuth.TrustedSources")
+ mapDeprecatedOption("ReverseProxyUserHeader", "ExtAuth.UserHeader")
+ mapDeprecatedOption("HTTPSecurityHeaders.CustomFrameOptionsValue", "HTTPHeaders.FrameOptions")
+ mapDeprecatedOption("CoverJpegQuality", "CoverArtQuality")
+
err := viper.Unmarshal(&Server)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "FATAL: Error parsing config:", err)
@@ -265,6 +303,12 @@ func Load(noConfigDump bool) {
os.Exit(1)
}
+ err = os.MkdirAll(filepath.Join(Server.DataFolder, consts.ArtworkFolder), os.ModePerm)
+ if err != nil {
+ _, _ = fmt.Fprintln(os.Stderr, "FATAL: Error creating artwork path:", err)
+ os.Exit(1)
+ }
+
if Server.Plugins.Enabled {
if Server.Plugins.Folder == "" {
Server.Plugins.Folder = filepath.Join(Server.DataFolder, "plugins")
@@ -297,6 +341,12 @@ func Load(noConfigDump bool) {
os.Exit(1)
}
log.SetOutput(out)
+ } else if os.Getenv("ND_SYSTEMD_PRIORITY_LOGGING") != "" && os.Getenv("JOURNAL_STREAM") != "" {
+ // When running under systemd, prepend syslog priority prefixes so
+ // journald assigns the correct severity to each log line.
+ // Note that we have an additional environment variable, as JOURNAL_STREAM
+ // can be present in a systemd environment even if not running as a systemd service
+ log.EnableJournalFormat()
}
log.SetLevelString(Server.LogLevel)
@@ -309,11 +359,14 @@ func Load(noConfigDump bool) {
validateBackupSchedule,
validatePlaylistsPath,
validatePurgeMissingOption,
+ validateURL("ExtAuth.LogoutURL", Server.ExtAuth.LogoutURL),
)
if err != nil {
os.Exit(1)
}
+ Server.Search.Backend = normalizeSearchBackend(Server.Search.Backend)
+
if Server.BaseURL != "" {
u, err := url.Parse(Server.BaseURL)
if err != nil {
@@ -327,9 +380,18 @@ func Load(noConfigDump bool) {
Server.BaseScheme = u.Scheme
}
+ // Log configuration source
+ if Server.ConfigFile != "" {
+ log.Info("Loaded configuration", "file", Server.ConfigFile)
+ } else if hasNDEnvVars() {
+ log.Info("No configuration file found. Loaded configuration only from environment variables")
+ } else {
+ log.Warn("No configuration file found. Using default values. To specify a config file, use the --configfile flag or set the ND_CONFIGFILE environment variable.")
+ }
+
// Print current configuration if log level is Debug
if log.IsGreaterOrEqualTo(log.LevelDebug) && !noConfigDump {
- prettyConf := pretty.Sprintf("Loaded configuration from '%s': %# v", Server.ConfigFile, Server)
+ prettyConf := pretty.Sprintf("Configuration: %# v", Server)
if Server.EnableLogRedacting {
prettyConf = log.Redact(prettyConf)
}
@@ -340,13 +402,28 @@ func Load(noConfigDump bool) {
disableExternalServices()
}
- if Server.Scanner.Extractor != consts.DefaultScannerExtractor {
- log.Warn(fmt.Sprintf("Extractor '%s' is not implemented, using 'taglib'", Server.Scanner.Extractor))
- Server.Scanner.Extractor = consts.DefaultScannerExtractor
- }
- logDeprecatedOptions("Scanner.GenreSeparators")
- logDeprecatedOptions("Scanner.GroupAlbumReleases")
- logDeprecatedOptions("DevEnableBufferedScrobble") // Deprecated: Buffered scrobbling is now always enabled and this option is ignored
+ // Make sure we don't have empty PIDs
+ Server.PID.Album = cmp.Or(Server.PID.Album, consts.DefaultAlbumPID)
+ Server.PID.Track = cmp.Or(Server.PID.Track, consts.DefaultTrackPID)
+
+ // Parse LastFM.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
+ Server.LastFM.Languages = parseLanguages(Server.LastFM.Language)
+
+ // Parse Deezer.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
+ Server.Deezer.Languages = parseLanguages(Server.Deezer.Language)
+
+ // Deprecated options
+ logDeprecatedOptions("Scanner.GenreSeparators", "")
+ logDeprecatedOptions("Scanner.GroupAlbumReleases", "")
+ logDeprecatedOptions("DevEnableBufferedScrobble", "") // Deprecated: Buffered scrobbling is now always enabled and this option is ignored
+ logDeprecatedOptions("SearchFullString", "Search.FullString")
+ logDeprecatedOptions("ReverseProxyWhitelist", "ExtAuth.TrustedSources")
+ logDeprecatedOptions("ReverseProxyUserHeader", "ExtAuth.UserHeader")
+ logDeprecatedOptions("HTTPSecurityHeaders.CustomFrameOptionsValue", "HTTPHeaders.FrameOptions")
+ logDeprecatedOptions("CoverJpegQuality", "CoverArtQuality")
+
+ // Removed options
+ logRemovedOptions("Spotify.ID", "Spotify.Secret")
// Call init hooks
for _, hook := range hooks {
@@ -354,15 +431,46 @@ func Load(noConfigDump bool) {
}
}
-func logDeprecatedOptions(options ...string) {
+func logDeprecatedOptions(oldName, newName string) {
+ envVar := "ND_" + strings.ToUpper(strings.ReplaceAll(oldName, ".", "_"))
+ newEnvVar := "ND_" + strings.ToUpper(strings.ReplaceAll(newName, ".", "_"))
+ logWarning := func(oldName, newName string) {
+ if newName != "" {
+ log.Warn(fmt.Sprintf("Option '%s' is deprecated and will be ignored in a future release. Please use the new '%s'", oldName, newName))
+ } else {
+ log.Warn(fmt.Sprintf("Option '%s' is deprecated and will be ignored in a future release", oldName))
+ }
+ }
+ if os.Getenv(envVar) != "" {
+ logWarning(envVar, newEnvVar)
+ }
+ if viper.InConfig(oldName) {
+ logWarning(oldName, newName)
+ }
+}
+
+// logRemovedOptions checks if the option is set, and if yes, outputs a warning message saying the option is
+// not available anymore
+func logRemovedOptions(options ...string) {
for _, option := range options {
envVar := "ND_" + strings.ToUpper(strings.ReplaceAll(option, ".", "_"))
- if os.Getenv(envVar) != "" {
- log.Warn(fmt.Sprintf("Option '%s' is deprecated and will be ignored in a future release", envVar))
+ logWarning := func(option string) {
+ log.Warn(fmt.Sprintf("Option '%s' is not available anymore and will be ignored. Please remove it from your config", option))
}
if viper.InConfig(option) {
- log.Warn(fmt.Sprintf("Option '%s' is deprecated and will be ignored in a future release", option))
+ logWarning(option)
}
+ if os.Getenv(envVar) != "" {
+ logWarning(envVar)
+ }
+ }
+}
+
+// mapDeprecatedOption is used to provide backwards compatibility for deprecated options. It should be called after
+// the config has been read by viper, but before unmarshalling it into the Config struct.
+func mapDeprecatedOption(legacyName, newName string) {
+ if viper.IsSet(legacyName) {
+ viper.Set(newName, viper.Get(legacyName))
}
}
@@ -372,7 +480,7 @@ func logDeprecatedOptions(options ...string) {
func parseIniFileConfiguration() {
cfgFile := viper.ConfigFileUsed()
if strings.ToLower(filepath.Ext(cfgFile)) == ".ini" {
- var iniConfig map[string]interface{}
+ var iniConfig map[string]any
err := viper.Unmarshal(&iniConfig)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "FATAL: Error parsing config:", err)
@@ -394,8 +502,8 @@ func parseIniFileConfiguration() {
func disableExternalServices() {
log.Info("All external integrations are DISABLED!")
Server.EnableInsightsCollector = false
+ Server.EnableM3UExternalAlbumArt = false
Server.LastFM.Enabled = false
- Server.Spotify.ID = ""
Server.Deezer.Enabled = false
Server.ListenBrainz.Enabled = false
Server.Agents = ""
@@ -405,7 +513,7 @@ func disableExternalServices() {
}
func validatePlaylistsPath() error {
- for _, path := range strings.Split(Server.PlaylistsPath, string(filepath.ListSeparator)) {
+ for path := range strings.SplitSeq(Server.PlaylistsPath, string(filepath.ListSeparator)) {
_, err := doublestar.Match(path, "")
if err != nil {
log.Error("Invalid PlaylistsPath", "path", path, err)
@@ -415,17 +523,27 @@ func validatePlaylistsPath() error {
return nil
}
-func validatePurgeMissingOption() error {
- allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull}
- valid := false
- for _, v := range allowedValues {
- if v == Server.Scanner.PurgeMissing {
- valid = true
- break
+// parseLanguages parses a comma-separated language string into a slice.
+// It trims whitespace from each entry and ensures at least [DefaultInfoLanguage] is returned.
+func parseLanguages(lang string) []string {
+ var languages []string
+ for l := range strings.SplitSeq(lang, ",") {
+ l = strings.TrimSpace(l)
+ if l != "" {
+ languages = append(languages, l)
}
}
+ if len(languages) == 0 {
+ return []string{consts.DefaultInfoLanguage}
+ }
+ return languages
+}
+
+func validatePurgeMissingOption() error {
+ allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull}
+ valid := slices.Contains(allowedValues, Server.Scanner.PurgeMissing)
if !valid {
- err := fmt.Errorf("Invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", Server.Scanner.PurgeMissing, allowedValues)
+ err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", Server.Scanner.PurgeMissing, allowedValues)
log.Error(err.Error())
Server.Scanner.PurgeMissing = consts.PurgeMissingNever
return err
@@ -454,24 +572,66 @@ func validateBackupSchedule() error {
}
func validateSchedule(schedule, field string) (string, error) {
- if _, err := time.ParseDuration(schedule); err == nil {
- schedule = "@every " + schedule
- }
- c := cron.New()
- id, err := c.AddFunc(schedule, func() {})
+ _, err := scheduler.ParseCrontab(schedule)
if err != nil {
log.Error(fmt.Sprintf("Invalid %s. Please read format spec at https://pkg.go.dev/github.com/robfig/cron#hdr-CRON_Expression_Format", field), "schedule", schedule, err)
- } else {
- c.Remove(id)
}
return schedule, err
}
+// validateURL checks if the provided URL is valid and has either http or https scheme.
+// It returns a function that can be used as a hook to validate URLs in the config.
+func validateURL(optionName, optionURL string) func() error {
+ return func() error {
+ if optionURL == "" {
+ return nil
+ }
+ u, err := url.Parse(optionURL)
+ if err != nil {
+ log.Error(fmt.Sprintf("Invalid %s: it could not be parsed", optionName), "url", optionURL, "err", err)
+ return err
+ }
+ if u.Scheme != "http" && u.Scheme != "https" {
+ err := fmt.Errorf("invalid scheme for %s: '%s'. Only 'http' and 'https' are allowed", optionName, u.Scheme)
+ log.Error(err.Error())
+ return err
+ }
+ // Require an absolute URL with a non-empty host and no opaque component.
+ if u.Host == "" || u.Opaque != "" {
+ err := fmt.Errorf("invalid %s: '%s'. A full http(s) URL with a non-empty host is required", optionName, optionURL)
+ log.Error(err.Error())
+ return err
+ }
+ return nil
+ }
+}
+
+func normalizeSearchBackend(value string) string {
+ v := strings.ToLower(strings.TrimSpace(value))
+ switch v {
+ case "fts", "legacy":
+ return v
+ default:
+ log.Error("Invalid Search.Backend value, falling back to 'fts'", "value", value)
+ return "fts"
+ }
+}
+
// AddHook is used to register initialization code that should run as soon as the config is loaded
func AddHook(hook func()) {
hooks = append(hooks, hook)
}
+// hasNDEnvVars checks if any ND_ prefixed environment variables are set (excluding ND_CONFIGFILE)
+func hasNDEnvVars() bool {
+ for _, env := range os.Environ() {
+ if strings.HasPrefix(env, "ND_") && !strings.HasPrefix(env, "ND_CONFIGFILE=") {
+ return true
+ }
+ }
+ return false
+}
+
func setViperDefaults() {
viper.SetDefault("musicfolder", filepath.Join(".", "music"))
viper.SetDefault("cachefolder", "")
@@ -489,6 +649,7 @@ func setViperDefaults() {
viper.SetDefault("uiwelcomemessage", "")
viper.SetDefault("maxsidebarplaylists", consts.DefaultMaxSidebarPlaylists)
viper.SetDefault("enabletranscodingconfig", false)
+ viper.SetDefault("enabletranscodingcancellation", false)
viper.SetDefault("transcodingcachesize", "100MB")
viper.SetDefault("imagecachesize", "100MB")
viper.SetDefault("albumplaycountmode", consts.AlbumPlayCountModeAbsolute)
@@ -499,10 +660,13 @@ func setViperDefaults() {
viper.SetDefault("smartPlaylistRefreshDelay", 5*time.Second)
viper.SetDefault("enabledownloads", true)
viper.SetDefault("enableexternalservices", true)
+ viper.SetDefault("enablem3uexternalalbumart", false)
viper.SetDefault("enablemediafilecoverart", true)
viper.SetDefault("autotranscodedownload", false)
viper.SetDefault("defaultdownsamplingformat", consts.DefaultDownsamplingFormat)
- viper.SetDefault("searchfullstring", false)
+ viper.SetDefault("search.fullstring", false)
+ viper.SetDefault("search.backend", "fts")
+ viper.SetDefault("similarsongsmatchthreshold", 85)
viper.SetDefault("recentlyaddedbymodtime", false)
viper.SetDefault("prefersorttags", false)
viper.SetDefault("ignoredarticles", "The El La Los Las Le Les Os As O A")
@@ -510,8 +674,9 @@ func setViperDefaults() {
viper.SetDefault("ffmpegpath", "")
viper.SetDefault("mpvcmdtemplate", "mpv --audio-device=%d --no-audio-display %f --input-ipc-server=%s")
viper.SetDefault("coverartpriority", "cover.*, folder.*, front.*, embedded, external")
- viper.SetDefault("coverjpegquality", 75)
+ viper.SetDefault("coverartquality", 75)
viper.SetDefault("artistartpriority", "artist.*, album/artist.*, external")
+ viper.SetDefault("discartpriority", "disc*.*, cd*.*, cover.*, folder.*, front.*, discsubtitle, embedded")
viper.SetDefault("lyricspriority", ".lrc,.txt,embedded")
viper.SetDefault("enablegravatar", false)
viper.SetDefault("enablefavourites", true)
@@ -520,9 +685,11 @@ func setViperDefaults() {
viper.SetDefault("defaulttheme", "Dark")
viper.SetDefault("defaultlanguage", "")
viper.SetDefault("defaultuivolume", consts.DefaultUIVolume)
+ viper.SetDefault("uisearchdebouncems", consts.DefaultUISearchDebounceMs)
viper.SetDefault("enablereplaygain", true)
viper.SetDefault("enablecoveranimation", true)
viper.SetDefault("enablenowplaying", true)
+ viper.SetDefault("enablecoverartupload", true)
viper.SetDefault("enablesharing", false)
viper.SetDefault("shareurl", "")
viper.SetDefault("defaultshareexpiration", 8760*time.Hour)
@@ -533,8 +700,9 @@ func setViperDefaults() {
viper.SetDefault("authrequestlimit", 5)
viper.SetDefault("authwindowlength", 20*time.Second)
viper.SetDefault("passwordencryptionkey", "")
- viper.SetDefault("reverseproxyuserheader", "Remote-User")
- viper.SetDefault("reverseproxywhitelist", "")
+ viper.SetDefault("extauth.userheader", "Remote-User")
+ viper.SetDefault("extauth.trustedsources", "")
+ viper.SetDefault("extauth.logouturl", "")
viper.SetDefault("prometheus.enabled", false)
viper.SetDefault("prometheus.metricspath", consts.PrometheusDefaultPath)
viper.SetDefault("prometheus.password", "")
@@ -553,21 +721,26 @@ func setViperDefaults() {
viper.SetDefault("scanner.followsymlinks", true)
viper.SetDefault("scanner.purgemissing", consts.PurgeMissingNever)
viper.SetDefault("subsonic.appendsubtitle", true)
+ viper.SetDefault("subsonic.appendalbumversion", true)
viper.SetDefault("subsonic.artistparticipations", false)
viper.SetDefault("subsonic.defaultreportrealpath", false)
+ viper.SetDefault("subsonic.enableaveragerating", true)
viper.SetDefault("subsonic.legacyclients", "DSub")
- viper.SetDefault("agents", "lastfm,spotify,deezer")
+ viper.SetDefault("subsonic.minimalclients", "SubMusic")
+ viper.SetDefault("agents", "deezer,lastfm,listenbrainz")
viper.SetDefault("lastfm.enabled", true)
- viper.SetDefault("lastfm.language", "en")
+ viper.SetDefault("lastfm.language", consts.DefaultInfoLanguage)
viper.SetDefault("lastfm.apikey", "")
viper.SetDefault("lastfm.secret", "")
viper.SetDefault("lastfm.scrobblefirstartistonly", false)
- viper.SetDefault("spotify.id", "")
- viper.SetDefault("spotify.secret", "")
viper.SetDefault("deezer.enabled", true)
+ viper.SetDefault("deezer.language", consts.DefaultInfoLanguage)
viper.SetDefault("listenbrainz.enabled", true)
- viper.SetDefault("listenbrainz.baseurl", "https://api.listenbrainz.org/1/")
- viper.SetDefault("httpsecurityheaders.customframeoptionsvalue", "DENY")
+ viper.SetDefault("listenbrainz.baseurl", consts.DefaultListenBrainzBaseURL)
+ viper.SetDefault("listenbrainz.artistalgorithm", consts.DefaultListenBrainzArtistAlgorithm)
+ viper.SetDefault("listenbrainz.trackalgorithm", consts.DefaultListenBrainzTrackAlgorithm)
+ viper.SetDefault("enablescrobblehistory", true)
+ viper.SetDefault("httpheaders.frameoptions", "DENY")
viper.SetDefault("backup.path", "")
viper.SetDefault("backup.schedule", "")
viper.SetDefault("backup.count", 0)
@@ -578,8 +751,9 @@ func setViperDefaults() {
viper.SetDefault("inspect.backloglimit", consts.RequestThrottleBacklogLimit)
viper.SetDefault("inspect.backlogtimeout", consts.RequestThrottleBacklogTimeout)
viper.SetDefault("plugins.folder", "")
- viper.SetDefault("plugins.enabled", false)
- viper.SetDefault("plugins.cachesize", "100MB")
+ viper.SetDefault("plugins.enabled", true)
+ viper.SetDefault("plugins.cachesize", "200MB")
+ viper.SetDefault("plugins.autoreload", false)
// DevFlags. These are used to enable/disable debugging and incomplete features
viper.SetDefault("devlogsourceline", false)
@@ -593,27 +767,37 @@ func setViperDefaults() {
viper.SetDefault("devuishowconfig", true)
viper.SetDefault("devneweventstream", true)
viper.SetDefault("devoffsetoptimize", 50000)
- viper.SetDefault("devartworkmaxrequests", max(2, runtime.NumCPU()/3))
+ viper.SetDefault("devartworkmaxrequests", max(4, runtime.NumCPU()))
viper.SetDefault("devartworkthrottlebackloglimit", consts.RequestThrottleBacklogLimit)
viper.SetDefault("devartworkthrottlebacklogtimeout", consts.RequestThrottleBacklogTimeout)
viper.SetDefault("devartistinfotimetolive", consts.ArtistInfoTimeToLive)
viper.SetDefault("devalbuminfotimetolive", consts.AlbumInfoTimeToLive)
viper.SetDefault("devexternalscanner", true)
viper.SetDefault("devscannerthreads", 5)
+ viper.SetDefault("devselectivewatcher", true)
viper.SetDefault("devinsightsinitialdelay", consts.InsightsInitialDelay)
viper.SetDefault("devenableplayerinsights", true)
viper.SetDefault("devenablepluginsinsights", true)
viper.SetDefault("devplugincompilationtimeout", time.Minute)
viper.SetDefault("devexternalartistfetchmultiplier", 1.5)
+ viper.SetDefault("devoptimizedb", true)
+ viper.SetDefault("devpreserveunicodeinexternalcalls", false)
+ viper.SetDefault("devenablemediafileprobe", true)
+ viper.SetDefault("devjpegcoverart", false)
}
func init() {
setViperDefaults()
}
-func InitConfig(cfgFile string) {
+func InitConfig(cfgFile string, loadEnvVars bool) {
codecRegistry := viper.NewCodecRegistry()
- _ = codecRegistry.RegisterCodec("ini", ini.Codec{})
+ _ = codecRegistry.RegisterCodec("ini", ini.Codec{
+ LoadOptions: ini.LoadOptions{
+ UnescapeValueDoubleQuotes: true,
+ UnescapeValueCommentSymbols: true,
+ },
+ })
viper.SetOptions(viper.WithCodecRegistry(codecRegistry))
cfgFile = getConfigFile(cfgFile)
@@ -627,10 +811,12 @@ func InitConfig(cfgFile string) {
}
_ = viper.BindEnv("port")
- viper.SetEnvPrefix("ND")
- replacer := strings.NewReplacer(".", "_")
- viper.SetEnvKeyReplacer(replacer)
- viper.AutomaticEnv()
+ if loadEnvVars {
+ viper.SetEnvPrefix("ND")
+ replacer := strings.NewReplacer(".", "_")
+ viper.SetEnvKeyReplacer(replacer)
+ viper.AutomaticEnv()
+ }
err := viper.ReadInConfig()
if viper.ConfigFileUsed() != "" && err != nil {
@@ -647,7 +833,7 @@ func getConfigFile(cfgFile string) string {
}
cfgFile = os.Getenv("ND_CONFIGFILE")
if cfgFile != "" {
- if _, err := os.Stat(cfgFile); err == nil {
+ if _, err := os.Stat(cfgFile); err == nil { //nolint:gosec
return cfgFile
}
}
diff --git a/conf/configuration_test.go b/conf/configuration_test.go
index 5b54e4975..73fec4196 100644
--- a/conf/configuration_test.go
+++ b/conf/configuration_test.go
@@ -26,12 +26,94 @@ var _ = Describe("Configuration", func() {
conf.ResetConf()
})
+ Describe("ParseLanguages", func() {
+ It("parses single language", func() {
+ Expect(conf.ParseLanguages("en")).To(Equal([]string{"en"}))
+ })
+
+ It("parses multiple comma-separated languages", func() {
+ Expect(conf.ParseLanguages("pt,en")).To(Equal([]string{"pt", "en"}))
+ })
+
+ It("trims whitespace from languages", func() {
+ Expect(conf.ParseLanguages(" pt , en ")).To(Equal([]string{"pt", "en"}))
+ })
+
+ It("returns default 'en' when empty", func() {
+ Expect(conf.ParseLanguages("")).To(Equal([]string{"en"}))
+ })
+
+ It("returns default 'en' when only whitespace", func() {
+ Expect(conf.ParseLanguages(" ")).To(Equal([]string{"en"}))
+ })
+
+ It("handles multiple languages with various spacing", func() {
+ Expect(conf.ParseLanguages("ja, pt, en")).To(Equal([]string{"ja", "pt", "en"}))
+ })
+ })
+
+ Describe("ValidateURL", func() {
+ It("accepts a valid http URL", func() {
+ fn := conf.ValidateURL("TestOption", "http://example.com/path")
+ Expect(fn()).To(Succeed())
+ })
+
+ It("accepts a valid https URL", func() {
+ fn := conf.ValidateURL("TestOption", "https://example.com/path")
+ Expect(fn()).To(Succeed())
+ })
+
+ It("rejects a URL with no scheme", func() {
+ fn := conf.ValidateURL("TestOption", "example.com/path")
+ Expect(fn()).To(MatchError(ContainSubstring("invalid scheme")))
+ })
+
+ It("rejects a URL with an unsupported scheme", func() {
+ fn := conf.ValidateURL("TestOption", "javascript://example.com/path")
+ Expect(fn()).To(MatchError(ContainSubstring("invalid scheme")))
+ })
+
+ It("accepts an empty URL (optional config)", func() {
+ fn := conf.ValidateURL("TestOption", "")
+ Expect(fn()).To(Succeed())
+ })
+
+ It("includes the option name in the error message", func() {
+ fn := conf.ValidateURL("MyOption", "ftp://example.com")
+ Expect(fn()).To(MatchError(ContainSubstring("MyOption")))
+ })
+
+ It("rejects a URL that cannot be parsed", func() {
+ fn := conf.ValidateURL("TestOption", "://invalid")
+ Expect(fn()).To(HaveOccurred())
+ })
+
+ It("rejects a URL without a host", func() {
+ fn := conf.ValidateURL("TestOption", "http:///path")
+ Expect(fn()).To(MatchError(ContainSubstring("non-empty host is required")))
+ })
+ })
+
+ DescribeTable("NormalizeSearchBackend",
+ func(input, expected string) {
+ Expect(conf.NormalizeSearchBackend(input)).To(Equal(expected))
+ },
+ Entry("accepts 'fts'", "fts", "fts"),
+ Entry("accepts 'legacy'", "legacy", "legacy"),
+ Entry("normalizes 'FTS' to lowercase", "FTS", "fts"),
+ Entry("normalizes 'Legacy' to lowercase", "Legacy", "legacy"),
+ Entry("trims whitespace", " fts ", "fts"),
+ Entry("falls back to 'fts' for 'fts5'", "fts5", "fts"),
+ Entry("falls back to 'fts' for unrecognized values", "invalid", "fts"),
+ Entry("falls back to 'fts' for empty string", "", "fts"),
+ )
+
DescribeTable("should load configuration from",
func(format string) {
filename := filepath.Join("testdata", "cfg."+format)
// Initialize config with the test file
- conf.InitConfig(filename)
+ conf.InitConfig(filename, false)
// Load the configuration (with noConfigDump=true)
conf.Load(true)
@@ -39,6 +121,10 @@ var _ = Describe("Configuration", func() {
Expect(conf.Server.MusicFolder).To(Equal(fmt.Sprintf("/%s/music", format)))
Expect(conf.Server.UIWelcomeMessage).To(Equal("Welcome " + format))
Expect(conf.Server.Tags["custom"].Aliases).To(Equal([]string{format, "test"}))
+ Expect(conf.Server.Tags["artist"].Split).To(Equal([]string{";"}))
+
+ // Check deprecated option mapping
+ Expect(conf.Server.ExtAuth.UserHeader).To(Equal("X-Auth-User"))
// The config file used should be the one we created
Expect(conf.Server.ConfigFile).To(Equal(filename))
diff --git a/conf/export_test.go b/conf/export_test.go
index 1b6daf036..d1d1bb3a9 100644
--- a/conf/export_test.go
+++ b/conf/export_test.go
@@ -5,3 +5,9 @@ func ResetConf() {
}
var SetViperDefaults = setViperDefaults
+
+var ParseLanguages = parseLanguages
+
+var ValidateURL = validateURL
+
+var NormalizeSearchBackend = normalizeSearchBackend
diff --git a/conf/testdata/cfg.ini b/conf/testdata/cfg.ini
index cec7d3c70..cc8b2a4a5 100644
--- a/conf/testdata/cfg.ini
+++ b/conf/testdata/cfg.ini
@@ -1,6 +1,8 @@
[default]
MusicFolder = /ini/music
-UIWelcomeMessage = Welcome ini
+UIWelcomeMessage = 'Welcome ini' ; Just a comment to test the LoadOptions
+ReverseProxyUserHeader = 'X-Auth-User'
[Tags]
-Custom.Aliases = ini,test
\ No newline at end of file
+Custom.Aliases = ini,test
+artist.Split = ";" # Should be able to read ; as a separator
\ No newline at end of file
diff --git a/conf/testdata/cfg.json b/conf/testdata/cfg.json
index 37cf74f08..28fb039d2 100644
--- a/conf/testdata/cfg.json
+++ b/conf/testdata/cfg.json
@@ -1,7 +1,11 @@
{
"musicFolder": "/json/music",
"uiWelcomeMessage": "Welcome json",
+ "reverseProxyUserHeader": "X-Auth-User",
"Tags": {
+ "artist": {
+ "split": ";"
+ },
"custom": {
"aliases": [
"json",
diff --git a/conf/testdata/cfg.toml b/conf/testdata/cfg.toml
index 1dc852b18..589e2a100 100644
--- a/conf/testdata/cfg.toml
+++ b/conf/testdata/cfg.toml
@@ -1,5 +1,8 @@
musicFolder = "/toml/music"
uiWelcomeMessage = "Welcome toml"
+ReverseProxyUserHeader = "X-Auth-User"
+
+Tags.artist.Split = ';'
[Tags.custom]
aliases = ["toml", "test"]
diff --git a/conf/testdata/cfg.yaml b/conf/testdata/cfg.yaml
index 38b98d4aa..e44d2ebbb 100644
--- a/conf/testdata/cfg.yaml
+++ b/conf/testdata/cfg.yaml
@@ -1,6 +1,9 @@
musicFolder: "/yaml/music"
uiWelcomeMessage: "Welcome yaml"
+reverseProxyUserHeader: "X-Auth-User"
Tags:
+ artist:
+ split: [";"]
custom:
aliases:
- yaml
diff --git a/consts/consts.go b/consts/consts.go
index fbb2c9429..f1010a872 100644
--- a/consts/consts.go
+++ b/consts/consts.go
@@ -56,6 +56,8 @@ const (
ServerReadHeaderTimeout = 3 * time.Second
+ DefaultInfoLanguage = "en"
+
ArtistInfoTimeToLive = 24 * time.Hour
AlbumInfoTimeToLive = 7 * 24 * time.Hour
UpdateLastAccessFrequency = time.Minute
@@ -63,20 +65,31 @@ const (
I18nFolder = "i18n"
ScanIgnoreFile = ".ndignore"
+ ArtworkFolder = "artwork"
- PlaceholderArtistArt = "artist-placeholder.webp"
- PlaceholderAlbumArt = "album-placeholder.webp"
- PlaceholderAvatar = "logo-192x192.png"
- UICoverArtSize = 300
- DefaultUIVolume = 100
+ PlaceholderArtistArt = "artist-placeholder.webp"
+ PlaceholderAlbumArt = "album-placeholder.webp"
+ PlaceholderAvatar = "logo-192x192.png"
+ DefaultUIVolume = 100
+ DefaultUISearchDebounceMs = 200
DefaultHttpClientTimeOut = 10 * time.Second
+ DefaultListenBrainzBaseURL = "https://api.listenbrainz.org/1/"
+ DefaultListenBrainzArtistAlgorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
+ DefaultListenBrainzTrackAlgorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
+
DefaultScannerExtractor = "taglib"
DefaultWatcherWait = 5 * time.Second
Zwsp = string('\u200b')
)
+const (
+ UICoverArtSize = 600
+)
+
+var CacheWarmerImageSizes = []int{UICoverArtSize}
+
// Prometheus options
const (
PrometheusDefaultPath = "/metrics"
@@ -95,6 +108,13 @@ const (
DefaultCacheCleanUpInterval = 10 * time.Minute
)
+// Entity types
+const (
+ EntityArtist = "artist"
+ EntityPlaylist = "playlist"
+ EntityRadio = "radio"
+)
+
const (
AlbumPlayCountModeAbsolute = "absolute"
AlbumPlayCountModeNormalized = "normalized"
@@ -147,9 +167,17 @@ var (
DefaultBitRate: 256,
Command: "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -c:a aac -f adts -",
},
+ {
+ Name: "flac audio",
+ TargetFormat: "flac",
+ DefaultBitRate: 0,
+ Command: "ffmpeg -i %s -ss %t -map 0:a:0 -v 0 -c:a flac -f flac -",
+ },
}
)
+var HTTPUserAgent = "Navidrome" + "/" + Version
+
var (
VariousArtists = "Various Artists"
// TODO This will be dynamic when using disambiguation
diff --git a/core/agents/README.md b/core/agents/README.md
index 1a3a8e96e..cce62889c 100644
--- a/core/agents/README.md
+++ b/core/agents/README.md
@@ -7,6 +7,6 @@ A new agent must comply with these simple implementation rules:
2) Implement one or more of the `*Retriever()` interfaces. That's where the agent's logic resides.
3) Register itself (in its `init()` function).
-For an agent to be used it needs to be listed in the `Agents` config option (default is `"lastfm,spotify"`). The order dictates the priority of the agents
+For an agent to be used it needs to be listed in the `Agents` config option (default is `"deezer,lastfm"`). The order dictates the priority of the agents
For a simple Agent example, look at the [local_agent](local_agent.go) agent source code.
diff --git a/core/agents/agents.go b/core/agents/agents.go
index 4ec324b71..ead6dacd0 100644
--- a/core/agents/agents.go
+++ b/core/agents/agents.go
@@ -22,6 +22,8 @@ type PluginLoader interface {
LoadMediaAgent(name string) (Interface, bool)
}
+// Agents is a meta-agent that aggregates multiple built-in and plugin agents. It tries each enabled agent in order
+// until one returns valid data.
type Agents struct {
ds model.DataStore
pluginLoader PluginLoader
@@ -64,6 +66,7 @@ func (a *Agents) getEnabledAgentNames() []enabledAgent {
if a.pluginLoader != nil {
availablePlugins = a.pluginLoader.PluginNames("MetadataAgent")
}
+ log.Trace("Available MetadataAgent plugins", "plugins", availablePlugins)
configuredAgents := strings.Split(conf.Server.Agents, ",")
@@ -87,7 +90,7 @@ func (a *Agents) getEnabledAgentNames() []enabledAgent {
} else if isPlugin {
validAgents = append(validAgents, enabledAgent{name: name, isPlugin: true})
} else {
- log.Warn("Unknown agent ignored", "name", name)
+ log.Debug("Unknown agent ignored", "name", name)
}
}
return validAgents
@@ -128,26 +131,14 @@ func (a *Agents) GetArtistMBID(ctx context.Context, id string, name string) (str
case consts.VariousArtistsID:
return "", nil
}
- start := time.Now()
- for _, enabledAgent := range a.getEnabledAgentNames() {
- ag := a.getAgent(enabledAgent)
- if ag == nil {
- continue
- }
- if utils.IsCtxDone(ctx) {
- break
- }
+
+ return callAgentMethod(ctx, a, "GetArtistMBID", func(ag Interface) (string, error) {
retriever, ok := ag.(ArtistMBIDRetriever)
if !ok {
- continue
+ return "", ErrNotFound
}
- mbid, err := retriever.GetArtistMBID(ctx, id, name)
- if mbid != "" && err == nil {
- log.Debug(ctx, "Got MBID", "agent", ag.AgentName(), "artist", name, "mbid", mbid, "elapsed", time.Since(start))
- return mbid, nil
- }
- }
- return "", ErrNotFound
+ return retriever.GetArtistMBID(ctx, id, name)
+ })
}
func (a *Agents) GetArtistURL(ctx context.Context, id, name, mbid string) (string, error) {
@@ -157,26 +148,14 @@ func (a *Agents) GetArtistURL(ctx context.Context, id, name, mbid string) (strin
case consts.VariousArtistsID:
return "", nil
}
- start := time.Now()
- for _, enabledAgent := range a.getEnabledAgentNames() {
- ag := a.getAgent(enabledAgent)
- if ag == nil {
- continue
- }
- if utils.IsCtxDone(ctx) {
- break
- }
+
+ return callAgentMethod(ctx, a, "GetArtistURL", func(ag Interface) (string, error) {
retriever, ok := ag.(ArtistURLRetriever)
if !ok {
- continue
+ return "", ErrNotFound
}
- url, err := retriever.GetArtistURL(ctx, id, name, mbid)
- if url != "" && err == nil {
- log.Debug(ctx, "Got External Url", "agent", ag.AgentName(), "artist", name, "url", url, "elapsed", time.Since(start))
- return url, nil
- }
- }
- return "", ErrNotFound
+ return retriever.GetArtistURL(ctx, id, name, mbid)
+ })
}
func (a *Agents) GetArtistBiography(ctx context.Context, id, name, mbid string) (string, error) {
@@ -186,26 +165,14 @@ func (a *Agents) GetArtistBiography(ctx context.Context, id, name, mbid string)
case consts.VariousArtistsID:
return "", nil
}
- start := time.Now()
- for _, enabledAgent := range a.getEnabledAgentNames() {
- ag := a.getAgent(enabledAgent)
- if ag == nil {
- continue
- }
- if utils.IsCtxDone(ctx) {
- break
- }
+
+ return callAgentMethod(ctx, a, "GetArtistBiography", func(ag Interface) (string, error) {
retriever, ok := ag.(ArtistBiographyRetriever)
if !ok {
- continue
+ return "", ErrNotFound
}
- bio, err := retriever.GetArtistBiography(ctx, id, name, mbid)
- if err == nil {
- log.Debug(ctx, "Got Biography", "agent", ag.AgentName(), "artist", name, "len", len(bio), "elapsed", time.Since(start))
- return bio, nil
- }
- }
- return "", ErrNotFound
+ return retriever.GetArtistBiography(ctx, id, name, mbid)
+ })
}
// GetSimilarArtists returns similar artists by id, name, and/or mbid. Because some artists returned from an enabled
@@ -253,26 +220,14 @@ func (a *Agents) GetArtistImages(ctx context.Context, id, name, mbid string) ([]
case consts.VariousArtistsID:
return nil, nil
}
- start := time.Now()
- for _, enabledAgent := range a.getEnabledAgentNames() {
- ag := a.getAgent(enabledAgent)
- if ag == nil {
- continue
- }
- if utils.IsCtxDone(ctx) {
- break
- }
+
+ return callAgentSliceMethod(ctx, a, "GetArtistImages", func(ag Interface) ([]ExternalImage, error) {
retriever, ok := ag.(ArtistImageRetriever)
if !ok {
- continue
+ return nil, ErrNotFound
}
- images, err := retriever.GetArtistImages(ctx, id, name, mbid)
- if len(images) > 0 && err == nil {
- log.Debug(ctx, "Got Images", "agent", ag.AgentName(), "artist", name, "images", images, "elapsed", time.Since(start))
- return images, nil
- }
- }
- return nil, ErrNotFound
+ return retriever.GetArtistImages(ctx, id, name, mbid)
+ })
}
// GetArtistTopSongs returns top songs by id, name, and/or mbid. Because some songs returned from an enabled
@@ -287,77 +242,127 @@ func (a *Agents) GetArtistTopSongs(ctx context.Context, id, artistName, mbid str
overLimit := int(float64(count) * conf.Server.DevExternalArtistFetchMultiplier)
- start := time.Now()
- for _, enabledAgent := range a.getEnabledAgentNames() {
- ag := a.getAgent(enabledAgent)
- if ag == nil {
- continue
- }
- if utils.IsCtxDone(ctx) {
- break
- }
+ return callAgentSliceMethod(ctx, a, "GetArtistTopSongs", func(ag Interface) ([]Song, error) {
retriever, ok := ag.(ArtistTopSongsRetriever)
if !ok {
- continue
+ return nil, ErrNotFound
}
- songs, err := retriever.GetArtistTopSongs(ctx, id, artistName, mbid, overLimit)
- if len(songs) > 0 && err == nil {
- log.Debug(ctx, "Got Top Songs", "agent", ag.AgentName(), "artist", artistName, "songs", songs, "elapsed", time.Since(start))
- return songs, nil
- }
- }
- return nil, ErrNotFound
+ return retriever.GetArtistTopSongs(ctx, id, artistName, mbid, overLimit)
+ })
}
func (a *Agents) GetAlbumInfo(ctx context.Context, name, artist, mbid string) (*AlbumInfo, error) {
if name == consts.UnknownAlbum {
return nil, ErrNotFound
}
- start := time.Now()
- for _, enabledAgent := range a.getEnabledAgentNames() {
- ag := a.getAgent(enabledAgent)
- if ag == nil {
- continue
- }
- if utils.IsCtxDone(ctx) {
- break
- }
+
+ return callAgentMethod(ctx, a, "GetAlbumInfo", func(ag Interface) (*AlbumInfo, error) {
retriever, ok := ag.(AlbumInfoRetriever)
if !ok {
- continue
+ return nil, ErrNotFound
}
- album, err := retriever.GetAlbumInfo(ctx, name, artist, mbid)
- if err == nil {
- log.Debug(ctx, "Got Album Info", "agent", ag.AgentName(), "album", name, "artist", artist,
- "mbid", mbid, "elapsed", time.Since(start))
- return album, nil
- }
- }
- return nil, ErrNotFound
+ return retriever.GetAlbumInfo(ctx, name, artist, mbid)
+ })
}
func (a *Agents) GetAlbumImages(ctx context.Context, name, artist, mbid string) ([]ExternalImage, error) {
if name == consts.UnknownAlbum {
return nil, ErrNotFound
}
+
+ return callAgentSliceMethod(ctx, a, "GetAlbumImages", func(ag Interface) ([]ExternalImage, error) {
+ retriever, ok := ag.(AlbumImageRetriever)
+ if !ok {
+ return nil, ErrNotFound
+ }
+ return retriever.GetAlbumImages(ctx, name, artist, mbid)
+ })
+}
+
+// GetSimilarSongsByTrack returns similar songs for a given track.
+func (a *Agents) GetSimilarSongsByTrack(ctx context.Context, id, name, artist, mbid string, count int) ([]Song, error) {
+ return callAgentSliceMethod(ctx, a, "GetSimilarSongsByTrack", func(ag Interface) ([]Song, error) {
+ retriever, ok := ag.(SimilarSongsByTrackRetriever)
+ if !ok {
+ return nil, ErrNotFound
+ }
+ return retriever.GetSimilarSongsByTrack(ctx, id, name, artist, mbid, count)
+ })
+}
+
+// GetSimilarSongsByAlbum returns similar songs for a given album.
+func (a *Agents) GetSimilarSongsByAlbum(ctx context.Context, id, name, artist, mbid string, count int) ([]Song, error) {
+ return callAgentSliceMethod(ctx, a, "GetSimilarSongsByAlbum", func(ag Interface) ([]Song, error) {
+ retriever, ok := ag.(SimilarSongsByAlbumRetriever)
+ if !ok {
+ return nil, ErrNotFound
+ }
+ return retriever.GetSimilarSongsByAlbum(ctx, id, name, artist, mbid, count)
+ })
+}
+
+// GetSimilarSongsByArtist returns similar songs for a given artist.
+func (a *Agents) GetSimilarSongsByArtist(ctx context.Context, id, name, mbid string, count int) ([]Song, error) {
+ switch id {
+ case consts.UnknownArtistID:
+ return nil, ErrNotFound
+ case consts.VariousArtistsID:
+ return nil, nil
+ }
+
+ return callAgentSliceMethod(ctx, a, "GetSimilarSongsByArtist", func(ag Interface) ([]Song, error) {
+ retriever, ok := ag.(SimilarSongsByArtistRetriever)
+ if !ok {
+ return nil, ErrNotFound
+ }
+ return retriever.GetSimilarSongsByArtist(ctx, id, name, mbid, count)
+ })
+}
+
+func callAgentMethod[T comparable](ctx context.Context, agents *Agents, methodName string, fn func(Interface) (T, error)) (T, error) {
+ var zero T
start := time.Now()
- for _, enabledAgent := range a.getEnabledAgentNames() {
- ag := a.getAgent(enabledAgent)
+ for _, enabledAgent := range agents.getEnabledAgentNames() {
+ ag := agents.getAgent(enabledAgent)
if ag == nil {
continue
}
if utils.IsCtxDone(ctx) {
break
}
- retriever, ok := ag.(AlbumImageRetriever)
- if !ok {
+ result, err := fn(ag)
+ if err != nil {
+ log.Trace(ctx, "Agent method call error", "method", methodName, "agent", ag.AgentName(), "error", err)
continue
}
- images, err := retriever.GetAlbumImages(ctx, name, artist, mbid)
- if len(images) > 0 && err == nil {
- log.Debug(ctx, "Got Album Images", "agent", ag.AgentName(), "album", name, "artist", artist,
- "mbid", mbid, "elapsed", time.Since(start))
- return images, nil
+
+ if result != zero {
+ log.Debug(ctx, "Got result", "method", methodName, "agent", ag.AgentName(), "elapsed", time.Since(start))
+ return result, nil
+ }
+ }
+ return zero, ErrNotFound
+}
+
+func callAgentSliceMethod[T any](ctx context.Context, agents *Agents, methodName string, fn func(Interface) ([]T, error)) ([]T, error) {
+ start := time.Now()
+ for _, enabledAgent := range agents.getEnabledAgentNames() {
+ ag := agents.getAgent(enabledAgent)
+ if ag == nil {
+ continue
+ }
+ if utils.IsCtxDone(ctx) {
+ break
+ }
+ results, err := fn(ag)
+ if err != nil {
+ log.Trace(ctx, "Agent method call error", "method", methodName, "agent", ag.AgentName(), "error", err)
+ continue
+ }
+
+ if len(results) > 0 {
+ log.Debug(ctx, "Got results", "method", methodName, "agent", ag.AgentName(), "count", len(results), "elapsed", time.Since(start))
+ return results, nil
}
}
return nil, ErrNotFound
@@ -372,3 +377,6 @@ var _ ArtistImageRetriever = (*Agents)(nil)
var _ ArtistTopSongsRetriever = (*Agents)(nil)
var _ AlbumInfoRetriever = (*Agents)(nil)
var _ AlbumImageRetriever = (*Agents)(nil)
+var _ SimilarSongsByTrackRetriever = (*Agents)(nil)
+var _ SimilarSongsByAlbumRetriever = (*Agents)(nil)
+var _ SimilarSongsByArtistRetriever = (*Agents)(nil)
diff --git a/core/agents/agents_test.go b/core/agents/agents_test.go
index 0b7eec282..50285a084 100644
--- a/core/agents/agents_test.go
+++ b/core/agents/agents_test.go
@@ -295,11 +295,77 @@ var _ = Describe("Agents", func() {
Expect(mock.Args).To(BeEmpty())
})
})
+
+ Describe("GetSimilarSongsByTrack", func() {
+ It("returns on first match", func() {
+ Expect(ag.GetSimilarSongsByTrack(ctx, "123", "test song", "test artist", "mb123", 2)).To(Equal([]Song{{
+ Name: "Similar Song",
+ MBID: "mbid555",
+ }}))
+ Expect(mock.Args).To(HaveExactElements("123", "test song", "test artist", "mb123", 2))
+ })
+ It("skips the agent if it returns an error", func() {
+ mock.Err = errors.New("error")
+ _, err := ag.GetSimilarSongsByTrack(ctx, "123", "test song", "test artist", "mb123", 2)
+ Expect(err).To(MatchError(ErrNotFound))
+ Expect(mock.Args).To(HaveExactElements("123", "test song", "test artist", "mb123", 2))
+ })
+ It("interrupts if the context is canceled", func() {
+ cancel()
+ _, err := ag.GetSimilarSongsByTrack(ctx, "123", "test song", "test artist", "mb123", 2)
+ Expect(err).To(MatchError(ErrNotFound))
+ Expect(mock.Args).To(BeEmpty())
+ })
+ })
+
+ Describe("GetSimilarSongsByAlbum", func() {
+ It("returns on first match", func() {
+ Expect(ag.GetSimilarSongsByAlbum(ctx, "123", "test album", "test artist", "mb123", 2)).To(Equal([]Song{{
+ Name: "Album Similar Song",
+ MBID: "mbid666",
+ }}))
+ Expect(mock.Args).To(HaveExactElements("123", "test album", "test artist", "mb123", 2))
+ })
+ It("skips the agent if it returns an error", func() {
+ mock.Err = errors.New("error")
+ _, err := ag.GetSimilarSongsByAlbum(ctx, "123", "test album", "test artist", "mb123", 2)
+ Expect(err).To(MatchError(ErrNotFound))
+ Expect(mock.Args).To(HaveExactElements("123", "test album", "test artist", "mb123", 2))
+ })
+ It("interrupts if the context is canceled", func() {
+ cancel()
+ _, err := ag.GetSimilarSongsByAlbum(ctx, "123", "test album", "test artist", "mb123", 2)
+ Expect(err).To(MatchError(ErrNotFound))
+ Expect(mock.Args).To(BeEmpty())
+ })
+ })
+
+ Describe("GetSimilarSongsByArtist", func() {
+ It("returns on first match", func() {
+ Expect(ag.GetSimilarSongsByArtist(ctx, "123", "test artist", "mb123", 2)).To(Equal([]Song{{
+ Name: "Artist Similar Song",
+ MBID: "mbid777",
+ }}))
+ Expect(mock.Args).To(HaveExactElements("123", "test artist", "mb123", 2))
+ })
+ It("skips the agent if it returns an error", func() {
+ mock.Err = errors.New("error")
+ _, err := ag.GetSimilarSongsByArtist(ctx, "123", "test artist", "mb123", 2)
+ Expect(err).To(MatchError(ErrNotFound))
+ Expect(mock.Args).To(HaveExactElements("123", "test artist", "mb123", 2))
+ })
+ It("interrupts if the context is canceled", func() {
+ cancel()
+ _, err := ag.GetSimilarSongsByArtist(ctx, "123", "test artist", "mb123", 2)
+ Expect(err).To(MatchError(ErrNotFound))
+ Expect(mock.Args).To(BeEmpty())
+ })
+ })
})
})
type mockAgent struct {
- Args []interface{}
+ Args []any
Err error
}
@@ -308,7 +374,7 @@ func (a *mockAgent) AgentName() string {
}
func (a *mockAgent) GetArtistMBID(_ context.Context, id string, name string) (string, error) {
- a.Args = []interface{}{id, name}
+ a.Args = []any{id, name}
if a.Err != nil {
return "", a.Err
}
@@ -316,7 +382,7 @@ func (a *mockAgent) GetArtistMBID(_ context.Context, id string, name string) (st
}
func (a *mockAgent) GetArtistURL(_ context.Context, id, name, mbid string) (string, error) {
- a.Args = []interface{}{id, name, mbid}
+ a.Args = []any{id, name, mbid}
if a.Err != nil {
return "", a.Err
}
@@ -324,7 +390,7 @@ func (a *mockAgent) GetArtistURL(_ context.Context, id, name, mbid string) (stri
}
func (a *mockAgent) GetArtistBiography(_ context.Context, id, name, mbid string) (string, error) {
- a.Args = []interface{}{id, name, mbid}
+ a.Args = []any{id, name, mbid}
if a.Err != nil {
return "", a.Err
}
@@ -332,7 +398,7 @@ func (a *mockAgent) GetArtistBiography(_ context.Context, id, name, mbid string)
}
func (a *mockAgent) GetArtistImages(_ context.Context, id, name, mbid string) ([]ExternalImage, error) {
- a.Args = []interface{}{id, name, mbid}
+ a.Args = []any{id, name, mbid}
if a.Err != nil {
return nil, a.Err
}
@@ -343,7 +409,7 @@ func (a *mockAgent) GetArtistImages(_ context.Context, id, name, mbid string) ([
}
func (a *mockAgent) GetSimilarArtists(_ context.Context, id, name, mbid string, limit int) ([]Artist, error) {
- a.Args = []interface{}{id, name, mbid, limit}
+ a.Args = []any{id, name, mbid, limit}
if a.Err != nil {
return nil, a.Err
}
@@ -354,7 +420,7 @@ func (a *mockAgent) GetSimilarArtists(_ context.Context, id, name, mbid string,
}
func (a *mockAgent) GetArtistTopSongs(_ context.Context, id, artistName, mbid string, count int) ([]Song, error) {
- a.Args = []interface{}{id, artistName, mbid, count}
+ a.Args = []any{id, artistName, mbid, count}
if a.Err != nil {
return nil, a.Err
}
@@ -365,7 +431,7 @@ func (a *mockAgent) GetArtistTopSongs(_ context.Context, id, artistName, mbid st
}
func (a *mockAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid string) (*AlbumInfo, error) {
- a.Args = []interface{}{name, artist, mbid}
+ a.Args = []any{name, artist, mbid}
if a.Err != nil {
return nil, a.Err
}
@@ -377,6 +443,39 @@ func (a *mockAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid string)
}, nil
}
+func (a *mockAgent) GetSimilarSongsByTrack(_ context.Context, id, name, artist, mbid string, count int) ([]Song, error) {
+ a.Args = []any{id, name, artist, mbid, count}
+ if a.Err != nil {
+ return nil, a.Err
+ }
+ return []Song{{
+ Name: "Similar Song",
+ MBID: "mbid555",
+ }}, nil
+}
+
+func (a *mockAgent) GetSimilarSongsByAlbum(_ context.Context, id, name, artist, mbid string, count int) ([]Song, error) {
+ a.Args = []any{id, name, artist, mbid, count}
+ if a.Err != nil {
+ return nil, a.Err
+ }
+ return []Song{{
+ Name: "Album Similar Song",
+ MBID: "mbid666",
+ }}, nil
+}
+
+func (a *mockAgent) GetSimilarSongsByArtist(_ context.Context, id, name, mbid string, count int) ([]Song, error) {
+ a.Args = []any{id, name, mbid, count}
+ if a.Err != nil {
+ return nil, a.Err
+ }
+ return []Song{{
+ Name: "Artist Similar Song",
+ MBID: "mbid777",
+ }}, nil
+}
+
type emptyAgent struct {
Interface
}
@@ -389,12 +488,12 @@ type testImageAgent struct {
Name string
Images []ExternalImage
Err error
- Args []interface{}
+ Args []any
}
func (t *testImageAgent) AgentName() string { return t.Name }
func (t *testImageAgent) GetArtistImages(_ context.Context, id, name, mbid string) ([]ExternalImage, error) {
- t.Args = []interface{}{id, name, mbid}
+ t.Args = []any{id, name, mbid}
return t.Images, t.Err
}
diff --git a/core/agents/deezer/client.go b/core/agents/deezer/client.go
deleted file mode 100644
index e75526d80..000000000
--- a/core/agents/deezer/client.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package deezer
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "strconv"
-
- "github.com/navidrome/navidrome/log"
-)
-
-const apiBaseURL = "https://api.deezer.com"
-
-var (
- ErrNotFound = errors.New("deezer: not found")
-)
-
-type httpDoer interface {
- Do(req *http.Request) (*http.Response, error)
-}
-
-type client struct {
- httpDoer httpDoer
-}
-
-func newClient(hc httpDoer) *client {
- return &client{hc}
-}
-
-func (c *client) searchArtists(ctx context.Context, name string, limit int) ([]Artist, error) {
- params := url.Values{}
- params.Add("q", name)
- params.Add("limit", strconv.Itoa(limit))
- req, err := http.NewRequestWithContext(ctx, "GET", apiBaseURL+"/search/artist", nil)
- if err != nil {
- return nil, err
- }
- req.URL.RawQuery = params.Encode()
-
- var results SearchArtistResults
- err = c.makeRequest(req, &results)
- if err != nil {
- return nil, err
- }
-
- if len(results.Data) == 0 {
- return nil, ErrNotFound
- }
- return results.Data, nil
-}
-
-func (c *client) makeRequest(req *http.Request, response interface{}) error {
- log.Trace(req.Context(), fmt.Sprintf("Sending Deezer %s request", req.Method), "url", req.URL)
- resp, err := c.httpDoer.Do(req)
- if err != nil {
- return err
- }
-
- defer resp.Body.Close()
- data, err := io.ReadAll(resp.Body)
- if err != nil {
- return err
- }
-
- if resp.StatusCode != 200 {
- return c.parseError(data)
- }
-
- return json.Unmarshal(data, response)
-}
-
-func (c *client) parseError(data []byte) error {
- var deezerError Error
- err := json.Unmarshal(data, &deezerError)
- if err != nil {
- return err
- }
- return fmt.Errorf("deezer error(%d): %s", deezerError.Error.Code, deezerError.Error.Message)
-}
diff --git a/core/agents/deezer/client_test.go b/core/agents/deezer/client_test.go
deleted file mode 100644
index 5e47460d4..000000000
--- a/core/agents/deezer/client_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package deezer
-
-import (
- "bytes"
- "context"
- "io"
- "net/http"
- "os"
-
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("client", func() {
- var httpClient *fakeHttpClient
- var client *client
-
- BeforeEach(func() {
- httpClient = &fakeHttpClient{}
- client = newClient(httpClient)
- })
-
- Describe("ArtistImages", func() {
- It("returns artist images from a successful request", func() {
- f, err := os.Open("tests/fixtures/deezer.search.artist.json")
- Expect(err).To(BeNil())
- httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200})
-
- artists, err := client.searchArtists(context.TODO(), "Michael Jackson", 20)
- Expect(err).To(BeNil())
- Expect(artists).To(HaveLen(17))
- Expect(artists[0].Name).To(Equal("Michael Jackson"))
- Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg"))
- })
-
- It("fails if artist was not found", func() {
- httpClient.mock("https://api.deezer.com/search/artist", http.Response{
- StatusCode: 200,
- Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
- })
-
- _, err := client.searchArtists(context.TODO(), "Michael Jackson", 20)
- Expect(err).To(MatchError(ErrNotFound))
- })
- })
-})
-
-type fakeHttpClient struct {
- responses map[string]*http.Response
- lastRequest *http.Request
-}
-
-func (c *fakeHttpClient) mock(url string, response http.Response) {
- if c.responses == nil {
- c.responses = make(map[string]*http.Response)
- }
- c.responses[url] = &response
-}
-
-func (c *fakeHttpClient) Do(req *http.Request) (*http.Response, error) {
- c.lastRequest = req
- u := req.URL
- u.RawQuery = ""
- if resp, ok := c.responses[u.String()]; ok {
- return resp, nil
- }
- panic("URL not mocked: " + u.String())
-}
diff --git a/core/agents/deezer/responses.go b/core/agents/deezer/responses.go
deleted file mode 100644
index 112fe28ec..000000000
--- a/core/agents/deezer/responses.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package deezer
-
-type SearchArtistResults struct {
- Data []Artist `json:"data"`
- Total int `json:"total"`
- Next string `json:"next"`
-}
-
-type Artist struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Link string `json:"link"`
- Picture string `json:"picture"`
- PictureSmall string `json:"picture_small"`
- PictureMedium string `json:"picture_medium"`
- PictureBig string `json:"picture_big"`
- PictureXl string `json:"picture_xl"`
- NbAlbum int `json:"nb_album"`
- NbFan int `json:"nb_fan"`
- Radio bool `json:"radio"`
- Tracklist string `json:"tracklist"`
- Type string `json:"type"`
-}
-
-type Error struct {
- Error struct {
- Type string `json:"type"`
- Message string `json:"message"`
- Code int `json:"code"`
- } `json:"error"`
-}
diff --git a/core/agents/interfaces.go b/core/agents/interfaces.go
index e60c61909..19df91d02 100644
--- a/core/agents/interfaces.go
+++ b/core/agents/interfaces.go
@@ -22,6 +22,7 @@ type AlbumInfo struct {
}
type Artist struct {
+ ID string
Name string
MBID string
}
@@ -32,8 +33,15 @@ type ExternalImage struct {
}
type Song struct {
- Name string
- MBID string
+ ID string
+ Name string
+ MBID string
+ ISRC string
+ Artist string
+ ArtistMBID string
+ Album string
+ AlbumMBID string
+ Duration uint32 // Duration in milliseconds, 0 means unknown
}
var (
@@ -74,6 +82,41 @@ type ArtistTopSongsRetriever interface {
GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]Song, error)
}
+// SimilarSongsByTrackRetriever provides similar songs based on a specific track
+type SimilarSongsByTrackRetriever interface {
+ // GetSimilarSongsByTrack returns songs similar to the given track.
+ // Parameters:
+ // - id: local mediafile ID
+ // - name: track title
+ // - artist: artist name
+ // - mbid: MusicBrainz recording ID (may be empty)
+ // - count: maximum number of results
+ GetSimilarSongsByTrack(ctx context.Context, id, name, artist, mbid string, count int) ([]Song, error)
+}
+
+// SimilarSongsByAlbumRetriever provides similar songs based on an album
+type SimilarSongsByAlbumRetriever interface {
+ // GetSimilarSongsByAlbum returns songs similar to tracks on the given album.
+ // Parameters:
+ // - id: local album ID
+ // - name: album name
+ // - artist: album artist name
+ // - mbid: MusicBrainz release ID (may be empty)
+ // - count: maximum number of results
+ GetSimilarSongsByAlbum(ctx context.Context, id, name, artist, mbid string, count int) ([]Song, error)
+}
+
+// SimilarSongsByArtistRetriever provides similar songs based on an artist
+type SimilarSongsByArtistRetriever interface {
+ // GetSimilarSongsByArtist returns songs similar to the artist's catalog.
+ // Parameters:
+ // - id: local artist ID
+ // - name: artist name
+ // - mbid: MusicBrainz artist ID (may be empty)
+ // - count: maximum number of results
+ GetSimilarSongsByArtist(ctx context.Context, id, name, mbid string, count int) ([]Song, error)
+}
+
var Map map[string]Constructor
func Register(name string, init Constructor) {
diff --git a/core/agents/listenbrainz/agent_test.go b/core/agents/listenbrainz/agent_test.go
deleted file mode 100644
index e99b442de..000000000
--- a/core/agents/listenbrainz/agent_test.go
+++ /dev/null
@@ -1,165 +0,0 @@
-package listenbrainz
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "io"
- "net/http"
- "time"
-
- "github.com/navidrome/navidrome/consts"
- "github.com/navidrome/navidrome/core/scrobbler"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/tests"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
- . "github.com/onsi/gomega/gstruct"
-)
-
-var _ = Describe("listenBrainzAgent", func() {
- var ds model.DataStore
- var ctx context.Context
- var agent *listenBrainzAgent
- var httpClient *tests.FakeHttpClient
- var track *model.MediaFile
-
- BeforeEach(func() {
- ds = &tests.MockDataStore{}
- ctx = context.Background()
- _ = ds.UserProps(ctx).Put("user-1", sessionKeyProperty, "SK-1")
- httpClient = &tests.FakeHttpClient{}
- agent = listenBrainzConstructor(ds)
- agent.client = newClient("http://localhost:8080", httpClient)
- track = &model.MediaFile{
- ID: "123",
- Title: "Track Title",
- Album: "Track Album",
- Artist: "Track Artist",
- TrackNumber: 1,
- MbzRecordingID: "mbz-123",
- MbzAlbumID: "mbz-456",
- MbzReleaseGroupID: "mbz-789",
- Duration: 142.2,
- Participants: map[model.Role]model.ParticipantList{
- model.RoleArtist: []model.Participant{
- {Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}},
- {Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}},
- },
- },
- }
- })
-
- Describe("formatListen", func() {
- It("constructs the listenInfo properly", func() {
- lr := agent.formatListen(track)
- Expect(lr).To(MatchAllFields(Fields{
- "ListenedAt": Equal(0),
- "TrackMetadata": MatchAllFields(Fields{
- "ArtistName": Equal(track.Artist),
- "TrackName": Equal(track.Title),
- "ReleaseName": Equal(track.Album),
- "AdditionalInfo": MatchAllFields(Fields{
- "SubmissionClient": Equal(consts.AppName),
- "SubmissionClientVersion": Equal(consts.Version),
- "TrackNumber": Equal(track.TrackNumber),
- "RecordingMBID": Equal(track.MbzRecordingID),
- "ReleaseMBID": Equal(track.MbzAlbumID),
- "ReleaseGroupMBID": Equal(track.MbzReleaseGroupID),
- "ArtistNames": ConsistOf("Artist 1", "Artist 2"),
- "ArtistMBIDs": ConsistOf("mbz-111", "mbz-222"),
- "DurationMs": Equal(142200),
- }),
- }),
- }))
- })
- })
-
- Describe("NowPlaying", func() {
- It("updates NowPlaying successfully", func() {
- httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
-
- err := agent.NowPlaying(ctx, "user-1", track, 0)
- Expect(err).ToNot(HaveOccurred())
- })
-
- It("returns ErrNotAuthorized if user is not linked", func() {
- err := agent.NowPlaying(ctx, "user-2", track, 0)
- Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
- })
- })
-
- Describe("Scrobble", func() {
- var sc scrobbler.Scrobble
-
- BeforeEach(func() {
- sc = scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}
- })
-
- It("sends a Scrobble successfully", func() {
- httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
-
- err := agent.Scrobble(ctx, "user-1", sc)
- Expect(err).ToNot(HaveOccurred())
- })
-
- It("sets the Timestamp properly", func() {
- httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
-
- err := agent.Scrobble(ctx, "user-1", sc)
- Expect(err).ToNot(HaveOccurred())
-
- decoder := json.NewDecoder(httpClient.SavedRequest.Body)
- var lr listenBrainzRequestBody
- err = decoder.Decode(&lr)
-
- Expect(err).ToNot(HaveOccurred())
- Expect(lr.Payload[0].ListenedAt).To(Equal(int(sc.TimeStamp.Unix())))
- })
-
- It("returns ErrNotAuthorized if user is not linked", func() {
- err := agent.Scrobble(ctx, "user-2", sc)
- Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
- })
-
- It("returns ErrRetryLater on error 503", func() {
- httpClient.Res = http.Response{
- Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)),
- StatusCode: 503,
- }
-
- err := agent.Scrobble(ctx, "user-1", sc)
- Expect(err).To(MatchError(scrobbler.ErrRetryLater))
- })
-
- It("returns ErrRetryLater on error 500", func() {
- httpClient.Res = http.Response{
- Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)),
- StatusCode: 500,
- }
-
- err := agent.Scrobble(ctx, "user-1", sc)
- Expect(err).To(MatchError(scrobbler.ErrRetryLater))
- })
-
- It("returns ErrRetryLater on http errors", func() {
- httpClient.Res = http.Response{
- Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)),
- StatusCode: 500,
- }
-
- err := agent.Scrobble(ctx, "user-1", sc)
- Expect(err).To(MatchError(scrobbler.ErrRetryLater))
- })
-
- It("returns ErrUnrecoverable on other errors", func() {
- httpClient.Res = http.Response{
- Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)),
- StatusCode: 400,
- }
-
- err := agent.Scrobble(ctx, "user-1", sc)
- Expect(err).To(MatchError(scrobbler.ErrUnrecoverable))
- })
- })
-})
diff --git a/core/agents/listenbrainz/client.go b/core/agents/listenbrainz/client.go
deleted file mode 100644
index 168aad549..000000000
--- a/core/agents/listenbrainz/client.go
+++ /dev/null
@@ -1,179 +0,0 @@
-package listenbrainz
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "net/url"
- "path"
-
- "github.com/navidrome/navidrome/log"
-)
-
-type listenBrainzError struct {
- Code int
- Message string
-}
-
-func (e *listenBrainzError) Error() string {
- return fmt.Sprintf("ListenBrainz error(%d): %s", e.Code, e.Message)
-}
-
-type httpDoer interface {
- Do(req *http.Request) (*http.Response, error)
-}
-
-func newClient(baseURL string, hc httpDoer) *client {
- return &client{baseURL, hc}
-}
-
-type client struct {
- baseURL string
- hc httpDoer
-}
-
-type listenBrainzResponse struct {
- Code int `json:"code"`
- Message string `json:"message"`
- Error string `json:"error"`
- Status string `json:"status"`
- Valid bool `json:"valid"`
- UserName string `json:"user_name"`
-}
-
-type listenBrainzRequest struct {
- ApiKey string
- Body listenBrainzRequestBody
-}
-
-type listenBrainzRequestBody struct {
- ListenType listenType `json:"listen_type,omitempty"`
- Payload []listenInfo `json:"payload,omitempty"`
-}
-
-type listenType string
-
-const (
- Single listenType = "single"
- PlayingNow listenType = "playing_now"
-)
-
-type listenInfo struct {
- ListenedAt int `json:"listened_at,omitempty"`
- TrackMetadata trackMetadata `json:"track_metadata,omitempty"`
-}
-
-type trackMetadata struct {
- ArtistName string `json:"artist_name,omitempty"`
- TrackName string `json:"track_name,omitempty"`
- ReleaseName string `json:"release_name,omitempty"`
- AdditionalInfo additionalInfo `json:"additional_info,omitempty"`
-}
-
-type additionalInfo struct {
- SubmissionClient string `json:"submission_client,omitempty"`
- SubmissionClientVersion string `json:"submission_client_version,omitempty"`
- TrackNumber int `json:"tracknumber,omitempty"`
- ArtistNames []string `json:"artist_names,omitempty"`
- ArtistMBIDs []string `json:"artist_mbids,omitempty"`
- RecordingMBID string `json:"recording_mbid,omitempty"`
- ReleaseMBID string `json:"release_mbid,omitempty"`
- ReleaseGroupMBID string `json:"release_group_mbid,omitempty"`
- DurationMs int `json:"duration_ms,omitempty"`
-}
-
-func (c *client) validateToken(ctx context.Context, apiKey string) (*listenBrainzResponse, error) {
- r := &listenBrainzRequest{
- ApiKey: apiKey,
- }
- response, err := c.makeRequest(ctx, http.MethodGet, "validate-token", r)
- if err != nil {
- return nil, err
- }
- return response, nil
-}
-
-func (c *client) updateNowPlaying(ctx context.Context, apiKey string, li listenInfo) error {
- r := &listenBrainzRequest{
- ApiKey: apiKey,
- Body: listenBrainzRequestBody{
- ListenType: PlayingNow,
- Payload: []listenInfo{li},
- },
- }
-
- resp, err := c.makeRequest(ctx, http.MethodPost, "submit-listens", r)
- if err != nil {
- return err
- }
- if resp.Status != "ok" {
- log.Warn(ctx, "ListenBrainz: NowPlaying was not accepted", "status", resp.Status)
- }
- return nil
-}
-
-func (c *client) scrobble(ctx context.Context, apiKey string, li listenInfo) error {
- r := &listenBrainzRequest{
- ApiKey: apiKey,
- Body: listenBrainzRequestBody{
- ListenType: Single,
- Payload: []listenInfo{li},
- },
- }
- resp, err := c.makeRequest(ctx, http.MethodPost, "submit-listens", r)
- if err != nil {
- return err
- }
- if resp.Status != "ok" {
- log.Warn(ctx, "ListenBrainz: Scrobble was not accepted", "status", resp.Status)
- }
- return nil
-}
-
-func (c *client) path(endpoint string) (string, error) {
- u, err := url.Parse(c.baseURL)
- if err != nil {
- return "", err
- }
- u.Path = path.Join(u.Path, endpoint)
- return u.String(), nil
-}
-
-func (c *client) makeRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) {
- b, _ := json.Marshal(r.Body)
- uri, err := c.path(endpoint)
- if err != nil {
- return nil, err
- }
- req, _ := http.NewRequestWithContext(ctx, method, uri, bytes.NewBuffer(b))
- req.Header.Add("Content-Type", "application/json; charset=UTF-8")
-
- if r.ApiKey != "" {
- req.Header.Add("Authorization", fmt.Sprintf("Token %s", r.ApiKey))
- }
-
- log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz %s request", req.Method), "url", req.URL)
- resp, err := c.hc.Do(req)
- if err != nil {
- return nil, err
- }
-
- defer resp.Body.Close()
- decoder := json.NewDecoder(resp.Body)
-
- var response listenBrainzResponse
- jsonErr := decoder.Decode(&response)
- if resp.StatusCode != 200 && jsonErr != nil {
- return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
- }
- if jsonErr != nil {
- return nil, jsonErr
- }
- if response.Code != 0 && response.Code != 200 {
- return &response, &listenBrainzError{Code: response.Code, Message: response.Error}
- }
-
- return &response, nil
-}
diff --git a/core/agents/listenbrainz/client_test.go b/core/agents/listenbrainz/client_test.go
deleted file mode 100644
index 680a7d185..000000000
--- a/core/agents/listenbrainz/client_test.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package listenbrainz
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "io"
- "net/http"
- "os"
-
- "github.com/navidrome/navidrome/tests"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("client", func() {
- var httpClient *tests.FakeHttpClient
- var client *client
- BeforeEach(func() {
- httpClient = &tests.FakeHttpClient{}
- client = newClient("BASE_URL/", httpClient)
- })
-
- Describe("listenBrainzResponse", func() {
- It("parses a response properly", func() {
- var response listenBrainzResponse
- err := json.Unmarshal([]byte(`{"code": 200, "message": "Message", "user_name": "UserName", "valid": true, "status": "ok", "error": "Error"}`), &response)
-
- Expect(err).ToNot(HaveOccurred())
- Expect(response.Code).To(Equal(200))
- Expect(response.Message).To(Equal("Message"))
- Expect(response.UserName).To(Equal("UserName"))
- Expect(response.Valid).To(BeTrue())
- Expect(response.Status).To(Equal("ok"))
- Expect(response.Error).To(Equal("Error"))
- })
- })
-
- Describe("validateToken", func() {
- BeforeEach(func() {
- httpClient.Res = http.Response{
- Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
- StatusCode: 200,
- }
- })
-
- It("formats the request properly", func() {
- _, err := client.validateToken(context.Background(), "LB-TOKEN")
- Expect(err).ToNot(HaveOccurred())
- Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
- Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/validate-token"))
- Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
- Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
- })
-
- It("parses and returns the response", func() {
- res, err := client.validateToken(context.Background(), "LB-TOKEN")
- Expect(err).ToNot(HaveOccurred())
- Expect(res.Valid).To(Equal(true))
- Expect(res.UserName).To(Equal("ListenBrainzUser"))
- })
- })
-
- Context("with listenInfo", func() {
- var li listenInfo
- BeforeEach(func() {
- httpClient.Res = http.Response{
- Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)),
- StatusCode: 200,
- }
- li = listenInfo{
- TrackMetadata: trackMetadata{
- ArtistName: "Track Artist",
- TrackName: "Track Title",
- ReleaseName: "Track Album",
- AdditionalInfo: additionalInfo{
- TrackNumber: 1,
- ArtistNames: []string{"Artist 1", "Artist 2"},
- ArtistMBIDs: []string{"mbz-789", "mbz-012"},
- RecordingMBID: "mbz-123",
- ReleaseMBID: "mbz-456",
- DurationMs: 142200,
- },
- },
- }
- })
-
- Describe("updateNowPlaying", func() {
- It("formats the request properly", func() {
- Expect(client.updateNowPlaying(context.Background(), "LB-TOKEN", li)).To(Succeed())
- Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
- Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
- Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
- Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
-
- body, _ := io.ReadAll(httpClient.SavedRequest.Body)
- f, _ := os.ReadFile("tests/fixtures/listenbrainz.nowplaying.request.json")
- Expect(body).To(MatchJSON(f))
- })
- })
-
- Describe("scrobble", func() {
- BeforeEach(func() {
- li.ListenedAt = 1635000000
- })
-
- It("formats the request properly", func() {
- Expect(client.scrobble(context.Background(), "LB-TOKEN", li)).To(Succeed())
- Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
- Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
- Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
- Expect(httpClient.SavedRequest.Header.Get("Content-Type")).To(Equal("application/json; charset=UTF-8"))
-
- body, _ := io.ReadAll(httpClient.SavedRequest.Body)
- f, _ := os.ReadFile("tests/fixtures/listenbrainz.scrobble.request.json")
- Expect(body).To(MatchJSON(f))
- })
- })
- })
-})
diff --git a/core/agents/spotify/client.go b/core/agents/spotify/client.go
deleted file mode 100644
index 25b1f9ede..000000000
--- a/core/agents/spotify/client.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package spotify
-
-import (
- "context"
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "strconv"
- "strings"
-
- "github.com/navidrome/navidrome/log"
-)
-
-const apiBaseUrl = "https://api.spotify.com/v1/"
-
-var (
- ErrNotFound = errors.New("spotify: not found")
-)
-
-type httpDoer interface {
- Do(req *http.Request) (*http.Response, error)
-}
-
-func newClient(id, secret string, hc httpDoer) *client {
- return &client{id, secret, hc}
-}
-
-type client struct {
- id string
- secret string
- hc httpDoer
-}
-
-func (c *client) searchArtists(ctx context.Context, name string, limit int) ([]Artist, error) {
- token, err := c.authorize(ctx)
- if err != nil {
- return nil, err
- }
-
- params := url.Values{}
- params.Add("type", "artist")
- params.Add("q", name)
- params.Add("offset", "0")
- params.Add("limit", strconv.Itoa(limit))
- req, _ := http.NewRequestWithContext(ctx, "GET", apiBaseUrl+"search", nil)
- req.URL.RawQuery = params.Encode()
- req.Header.Add("Authorization", "Bearer "+token)
-
- var results SearchResults
- err = c.makeRequest(req, &results)
- if err != nil {
- return nil, err
- }
-
- if len(results.Artists.Items) == 0 {
- return nil, ErrNotFound
- }
- return results.Artists.Items, err
-}
-
-func (c *client) authorize(ctx context.Context) (string, error) {
- payload := url.Values{}
- payload.Add("grant_type", "client_credentials")
-
- encodePayload := payload.Encode()
- req, _ := http.NewRequestWithContext(ctx, "POST", "https://accounts.spotify.com/api/token", strings.NewReader(encodePayload))
- req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Add("Content-Length", strconv.Itoa(len(encodePayload)))
- auth := c.id + ":" + c.secret
- req.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
-
- response := map[string]interface{}{}
- err := c.makeRequest(req, &response)
- if err != nil {
- return "", err
- }
-
- if v, ok := response["access_token"]; ok {
- return v.(string), nil
- }
- log.Error(ctx, "Invalid spotify response", "resp", response)
- return "", errors.New("invalid response")
-}
-
-func (c *client) makeRequest(req *http.Request, response interface{}) error {
- log.Trace(req.Context(), fmt.Sprintf("Sending Spotify %s request", req.Method), "url", req.URL)
- resp, err := c.hc.Do(req)
- if err != nil {
- return err
- }
-
- defer resp.Body.Close()
- data, err := io.ReadAll(resp.Body)
- if err != nil {
- return err
- }
-
- if resp.StatusCode != 200 {
- return c.parseError(data)
- }
-
- return json.Unmarshal(data, response)
-}
-
-func (c *client) parseError(data []byte) error {
- var e Error
- err := json.Unmarshal(data, &e)
- if err != nil {
- return err
- }
- return fmt.Errorf("spotify error(%s): %s", e.Code, e.Message)
-}
diff --git a/core/agents/spotify/client_test.go b/core/agents/spotify/client_test.go
deleted file mode 100644
index 2782d2122..000000000
--- a/core/agents/spotify/client_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package spotify
-
-import (
- "bytes"
- "context"
- "io"
- "net/http"
- "os"
-
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("client", func() {
- var httpClient *fakeHttpClient
- var client *client
-
- BeforeEach(func() {
- httpClient = &fakeHttpClient{}
- client = newClient("SPOTIFY_ID", "SPOTIFY_SECRET", httpClient)
- })
-
- Describe("ArtistImages", func() {
- It("returns artist images from a successful request", func() {
- f, _ := os.Open("tests/fixtures/spotify.search.artist.json")
- httpClient.mock("https://api.spotify.com/v1/search", http.Response{Body: f, StatusCode: 200})
- httpClient.mock("https://accounts.spotify.com/api/token", http.Response{
- StatusCode: 200,
- Body: io.NopCloser(bytes.NewBufferString(`{"access_token": "NEW_ACCESS_TOKEN","token_type": "Bearer","expires_in": 3600}`)),
- })
-
- artists, err := client.searchArtists(context.TODO(), "U2", 10)
- Expect(err).To(BeNil())
- Expect(artists).To(HaveLen(20))
- Expect(artists[0].Popularity).To(Equal(82))
-
- images := artists[0].Images
- Expect(images).To(HaveLen(3))
- Expect(images[0].Width).To(Equal(640))
- Expect(images[1].Width).To(Equal(320))
- Expect(images[2].Width).To(Equal(160))
- })
-
- It("fails if artist was not found", func() {
- httpClient.mock("https://api.spotify.com/v1/search", http.Response{
- StatusCode: 200,
- Body: io.NopCloser(bytes.NewBufferString(`{
- "artists" : {
- "href" : "https://api.spotify.com/v1/search?query=dasdasdas%2Cdna&type=artist&offset=0&limit=20",
- "items" : [ ], "limit" : 20, "next" : null, "offset" : 0, "previous" : null, "total" : 0
- }}`)),
- })
- httpClient.mock("https://accounts.spotify.com/api/token", http.Response{
- StatusCode: 200,
- Body: io.NopCloser(bytes.NewBufferString(`{"access_token": "NEW_ACCESS_TOKEN","token_type": "Bearer","expires_in": 3600}`)),
- })
-
- _, err := client.searchArtists(context.TODO(), "U2", 10)
- Expect(err).To(MatchError(ErrNotFound))
- })
-
- It("fails if not able to authorize", func() {
- f, _ := os.Open("tests/fixtures/spotify.search.artist.json")
- httpClient.mock("https://api.spotify.com/v1/search", http.Response{Body: f, StatusCode: 200})
- httpClient.mock("https://accounts.spotify.com/api/token", http.Response{
- StatusCode: 400,
- Body: io.NopCloser(bytes.NewBufferString(`{"error":"invalid_client","error_description":"Invalid client"}`)),
- })
-
- _, err := client.searchArtists(context.TODO(), "U2", 10)
- Expect(err).To(MatchError("spotify error(invalid_client): Invalid client"))
- })
- })
-
- Describe("authorize", func() {
- It("returns an access_token on successful authorization", func() {
- httpClient.mock("https://accounts.spotify.com/api/token", http.Response{
- StatusCode: 200,
- Body: io.NopCloser(bytes.NewBufferString(`{"access_token": "NEW_ACCESS_TOKEN","token_type": "Bearer","expires_in": 3600}`)),
- })
-
- token, err := client.authorize(context.TODO())
- Expect(err).To(BeNil())
- Expect(token).To(Equal("NEW_ACCESS_TOKEN"))
- auth := httpClient.lastRequest.Header.Get("Authorization")
- Expect(auth).To(Equal("Basic U1BPVElGWV9JRDpTUE9USUZZX1NFQ1JFVA=="))
- })
-
- It("fails on unsuccessful authorization", func() {
- httpClient.mock("https://accounts.spotify.com/api/token", http.Response{
- StatusCode: 400,
- Body: io.NopCloser(bytes.NewBufferString(`{"error":"invalid_client","error_description":"Invalid client"}`)),
- })
-
- _, err := client.authorize(context.TODO())
- Expect(err).To(MatchError("spotify error(invalid_client): Invalid client"))
- })
-
- It("fails on invalid JSON response", func() {
- httpClient.mock("https://accounts.spotify.com/api/token", http.Response{
- StatusCode: 200,
- Body: io.NopCloser(bytes.NewBufferString(`{NOT_VALID}`)),
- })
-
- _, err := client.authorize(context.TODO())
- Expect(err).To(MatchError("invalid character 'N' looking for beginning of object key string"))
- })
- })
-})
-
-type fakeHttpClient struct {
- responses map[string]*http.Response
- lastRequest *http.Request
-}
-
-func (c *fakeHttpClient) mock(url string, response http.Response) {
- if c.responses == nil {
- c.responses = make(map[string]*http.Response)
- }
- c.responses[url] = &response
-}
-
-func (c *fakeHttpClient) Do(req *http.Request) (*http.Response, error) {
- c.lastRequest = req
- u := req.URL
- u.RawQuery = ""
- if resp, ok := c.responses[u.String()]; ok {
- return resp, nil
- }
- panic("URL not mocked: " + u.String())
-}
diff --git a/core/agents/spotify/responses.go b/core/agents/spotify/responses.go
deleted file mode 100644
index 21166bf74..000000000
--- a/core/agents/spotify/responses.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package spotify
-
-type SearchResults struct {
- Artists ArtistsResult `json:"artists"`
-}
-
-type ArtistsResult struct {
- HRef string `json:"href"`
- Items []Artist `json:"items"`
-}
-
-type Artist struct {
- Genres []string `json:"genres"`
- HRef string `json:"href"`
- ID string `json:"id"`
- Popularity int `json:"popularity"`
- Images []Image `json:"images"`
- Name string `json:"name"`
-}
-
-type Image struct {
- URL string `json:"url"`
- Width int `json:"width"`
- Height int `json:"height"`
-}
-
-type Error struct {
- Code string `json:"error"`
- Message string `json:"error_description"`
-}
diff --git a/core/agents/spotify/responses_test.go b/core/agents/spotify/responses_test.go
deleted file mode 100644
index 704119816..000000000
--- a/core/agents/spotify/responses_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package spotify
-
-import (
- "encoding/json"
- "os"
-
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Responses", func() {
- Describe("Search type=artist", func() {
- It("parses the artist search result correctly ", func() {
- var resp SearchResults
- body, _ := os.ReadFile("tests/fixtures/spotify.search.artist.json")
- err := json.Unmarshal(body, &resp)
- Expect(err).To(BeNil())
-
- Expect(resp.Artists.Items).To(HaveLen(20))
- u2 := resp.Artists.Items[0]
- Expect(u2.Name).To(Equal("U2"))
- Expect(u2.Genres).To(ContainElements("irish rock", "permanent wave", "rock"))
- Expect(u2.ID).To(Equal("51Blml2LZPmy7TTiAg47vQ"))
- Expect(u2.HRef).To(Equal("https://api.spotify.com/v1/artists/51Blml2LZPmy7TTiAg47vQ"))
- Expect(u2.Images[0].URL).To(Equal("https://i.scdn.co/image/e22d5c0c8139b8439440a69854ed66efae91112d"))
- Expect(u2.Images[0].Width).To(Equal(640))
- Expect(u2.Images[0].Height).To(Equal(640))
- Expect(u2.Images[1].URL).To(Equal("https://i.scdn.co/image/40d6c5c14355cfc127b70da221233315497ec91d"))
- Expect(u2.Images[1].Width).To(Equal(320))
- Expect(u2.Images[1].Height).To(Equal(320))
- Expect(u2.Images[2].URL).To(Equal("https://i.scdn.co/image/7293d6752ae8a64e34adee5086858e408185b534"))
- Expect(u2.Images[2].Width).To(Equal(160))
- Expect(u2.Images[2].Height).To(Equal(160))
- })
- })
-
- Describe("Error", func() {
- It("parses the error response correctly", func() {
- var errorResp Error
- body := []byte(`{"error":"invalid_client","error_description":"Invalid client"}`)
- err := json.Unmarshal(body, &errorResp)
- Expect(err).To(BeNil())
-
- Expect(errorResp.Code).To(Equal("invalid_client"))
- Expect(errorResp.Message).To(Equal("Invalid client"))
- })
- })
-})
diff --git a/core/agents/spotify/spotify.go b/core/agents/spotify/spotify.go
deleted file mode 100644
index 633c32984..000000000
--- a/core/agents/spotify/spotify.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package spotify
-
-import (
- "context"
- "errors"
- "fmt"
- "net/http"
- "sort"
- "strings"
-
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/consts"
- "github.com/navidrome/navidrome/core/agents"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/utils/cache"
- "github.com/xrash/smetrics"
-)
-
-const spotifyAgentName = "spotify"
-
-type spotifyAgent struct {
- ds model.DataStore
- id string
- secret string
- client *client
-}
-
-func spotifyConstructor(ds model.DataStore) agents.Interface {
- if conf.Server.Spotify.ID == "" || conf.Server.Spotify.Secret == "" {
- return nil
- }
- l := &spotifyAgent{
- ds: ds,
- id: conf.Server.Spotify.ID,
- secret: conf.Server.Spotify.Secret,
- }
- hc := &http.Client{
- Timeout: consts.DefaultHttpClientTimeOut,
- }
- chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
- l.client = newClient(l.id, l.secret, chc)
- return l
-}
-
-func (s *spotifyAgent) AgentName() string {
- return spotifyAgentName
-}
-
-func (s *spotifyAgent) GetArtistImages(ctx context.Context, id, name, mbid string) ([]agents.ExternalImage, error) {
- a, err := s.searchArtist(ctx, name)
- if err != nil {
- if errors.Is(err, model.ErrNotFound) {
- log.Warn(ctx, "Artist not found in Spotify", "artist", name)
- } else {
- log.Error(ctx, "Error calling Spotify", "artist", name, err)
- }
- return nil, err
- }
-
- var res []agents.ExternalImage
- for _, img := range a.Images {
- res = append(res, agents.ExternalImage{
- URL: img.URL,
- Size: img.Width,
- })
- }
- return res, nil
-}
-
-func (s *spotifyAgent) searchArtist(ctx context.Context, name string) (*Artist, error) {
- artists, err := s.client.searchArtists(ctx, name, 40)
- if err != nil || len(artists) == 0 {
- return nil, model.ErrNotFound
- }
- name = strings.ToLower(name)
-
- // Sort results, prioritizing artists with images, with similar names and with high popularity, in this order
- sort.Slice(artists, func(i, j int) bool {
- ai := fmt.Sprintf("%-5t-%03d-%04d", len(artists[i].Images) == 0, smetrics.WagnerFischer(name, strings.ToLower(artists[i].Name), 1, 1, 2), 1000-artists[i].Popularity)
- aj := fmt.Sprintf("%-5t-%03d-%04d", len(artists[j].Images) == 0, smetrics.WagnerFischer(name, strings.ToLower(artists[j].Name), 1, 1, 2), 1000-artists[j].Popularity)
- return ai < aj
- })
-
- // If the first one has the same name, that's the one
- if strings.ToLower(artists[0].Name) != name {
- return nil, model.ErrNotFound
- }
- return &artists[0], err
-}
-
-func init() {
- conf.AddHook(func() {
- agents.Register(spotifyAgentName, spotifyConstructor)
- })
-}
diff --git a/core/archiver.go b/core/archiver.go
index 63459816e..8305c4f6c 100644
--- a/core/archiver.go
+++ b/core/archiver.go
@@ -10,6 +10,7 @@ import (
"strings"
"github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/slice"
@@ -22,13 +23,13 @@ type Archiver interface {
ZipPlaylist(ctx context.Context, id string, format string, bitrate int, w io.Writer) error
}
-func NewArchiver(ms MediaStreamer, ds model.DataStore, shares Share) Archiver {
+func NewArchiver(ms stream.MediaStreamer, ds model.DataStore, shares Share) Archiver {
return &archiver{ds: ds, ms: ms, shares: shares}
}
type archiver struct {
ds model.DataStore
- ms MediaStreamer
+ ms stream.MediaStreamer
shares Share
}
@@ -176,7 +177,7 @@ func (a *archiver) addFileToZip(ctx context.Context, z *zip.Writer, mf model.Med
var r io.ReadCloser
if format != "raw" && format != "" {
- r, err = a.ms.DoStream(ctx, &mf, format, bitrate, 0)
+ r, err = a.ms.NewStream(ctx, &mf, stream.Request{Format: format, BitRate: bitrate})
} else {
r, err = os.Open(path)
}
diff --git a/core/archiver_test.go b/core/archiver_test.go
index 37c4ef9ab..4f7aed278 100644
--- a/core/archiver_test.go
+++ b/core/archiver_test.go
@@ -9,6 +9,7 @@ import (
"github.com/Masterminds/squirrel"
"github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@@ -44,7 +45,7 @@ var _ = Describe("Archiver", func() {
}}).Return(mfs, nil)
ds.On("MediaFile", mock.Anything).Return(mfRepo)
- ms.On("DoStream", mock.Anything, mock.Anything, "mp3", 128, 0).Return(io.NopCloser(strings.NewReader("test")), nil).Times(3)
+ ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(3)
out := new(bytes.Buffer)
err := arch.ZipAlbum(context.Background(), "1", "mp3", 128, out)
@@ -73,7 +74,7 @@ var _ = Describe("Archiver", func() {
}}).Return(mfs, nil)
ds.On("MediaFile", mock.Anything).Return(mfRepo)
- ms.On("DoStream", mock.Anything, mock.Anything, "mp3", 128, 0).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
+ ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
out := new(bytes.Buffer)
err := arch.ZipArtist(context.Background(), "1", "mp3", 128, out)
@@ -104,7 +105,7 @@ var _ = Describe("Archiver", func() {
}
sh.On("Load", mock.Anything, "1").Return(share, nil)
- ms.On("DoStream", mock.Anything, mock.Anything, "mp3", 128, 0).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
+ ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
out := new(bytes.Buffer)
err := arch.ZipShare(context.Background(), "1", out)
@@ -136,7 +137,7 @@ var _ = Describe("Archiver", func() {
plRepo := &mockPlaylistRepository{}
plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil)
ds.On("Playlist", mock.Anything).Return(plRepo)
- ms.On("DoStream", mock.Anything, mock.Anything, "mp3", 128, 0).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
+ ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
out := new(bytes.Buffer)
err := arch.ZipPlaylist(context.Background(), "1", "mp3", 128, out)
@@ -214,15 +215,15 @@ func (m *mockPlaylistRepository) GetWithTracks(id string, refreshSmartPlaylists,
type mockMediaStreamer struct {
mock.Mock
- core.MediaStreamer
+ stream.MediaStreamer
}
-func (m *mockMediaStreamer) DoStream(ctx context.Context, mf *model.MediaFile, reqFormat string, reqBitRate int, reqOffset int) (*core.Stream, error) {
- args := m.Called(ctx, mf, reqFormat, reqBitRate, reqOffset)
+func (m *mockMediaStreamer) NewStream(ctx context.Context, mf *model.MediaFile, req stream.Request) (*stream.Stream, error) {
+ args := m.Called(ctx, mf, req)
if args.Error(1) != nil {
return nil, args.Error(1)
}
- return &core.Stream{ReadCloser: args.Get(0).(io.ReadCloser)}, nil
+ return &stream.Stream{ReadCloser: args.Get(0).(io.ReadCloser)}, nil
}
type mockShare struct {
diff --git a/core/artwork/animation.go b/core/artwork/animation.go
new file mode 100644
index 000000000..07f493eb4
--- /dev/null
+++ b/core/artwork/animation.go
@@ -0,0 +1,120 @@
+package artwork
+
+import (
+ "bytes"
+ "encoding/binary"
+)
+
+// isAnimatedGIF checks for multiple image descriptor blocks (0x2C) in a GIF file.
+// Animated GIFs use GIF89a and contain multiple image blocks.
+func isAnimatedGIF(data []byte) bool {
+ // GIF header: "GIF87a" or "GIF89a"
+ if !bytes.HasPrefix(data, []byte("GIF")) {
+ return false
+ }
+
+ // Skip header (6 bytes) + logical screen descriptor (7 bytes)
+ pos := 13
+ if pos >= len(data) {
+ return false
+ }
+
+ // Skip Global Color Table if present (bit 7 of packed byte at offset 10)
+ if len(data) > 10 && data[10]&0x80 != 0 {
+ // GCT size = 3 * 2^(N+1) where N = bits 0-2 of packed byte
+ gctSize := 3 * (1 << ((data[10] & 0x07) + 1))
+ pos += gctSize
+ }
+
+ frameCount := 0
+ for pos < len(data) {
+ switch data[pos] {
+ case 0x2C: // Image Descriptor - marks a frame
+ frameCount++
+ if frameCount > 1 {
+ return true
+ }
+ pos++ // skip introducer
+ if pos+8 >= len(data) {
+ return false
+ }
+ pos += 8 // skip x, y, w, h (each 2 bytes)
+ packed := data[pos]
+ pos++ // skip packed byte
+ // Skip Local Color Table if present
+ if packed&0x80 != 0 {
+ lctSize := 3 * (1 << ((packed & 0x07) + 1))
+ pos += lctSize
+ }
+ // Skip LZW minimum code size
+ pos++
+ // Skip sub-blocks
+ pos = skipGIFSubBlocks(data, pos)
+ case 0x21: // Extension block
+ pos++ // skip introducer
+ if pos >= len(data) {
+ return false
+ }
+ pos++ // skip extension label
+ // Skip sub-blocks
+ pos = skipGIFSubBlocks(data, pos)
+ case 0x3B: // Trailer
+ return false
+ default:
+ // Unknown block, bail
+ return false
+ }
+ }
+ return false
+}
+
+// skipGIFSubBlocks advances past a sequence of GIF sub-blocks (terminated by a zero-length block).
+func skipGIFSubBlocks(data []byte, pos int) int {
+ for pos < len(data) {
+ blockSize := int(data[pos])
+ pos++ // skip size byte
+ if blockSize == 0 {
+ break
+ }
+ pos += blockSize
+ }
+ return pos
+}
+
+// isAnimatedWebP checks for ANMF (animation frame) chunks in a WebP RIFF container.
+func isAnimatedWebP(data []byte) bool {
+ // WebP header: "RIFF" + 4 bytes size + "WEBP"
+ if !bytes.HasPrefix(data, []byte("RIFF")) || len(data) < 12 {
+ return false
+ }
+ if !bytes.Equal(data[8:12], []byte("WEBP")) {
+ return false
+ }
+ // Scan for ANMF chunk identifier
+ return bytes.Contains(data[12:], []byte("ANMF"))
+}
+
+// isAnimatedPNG checks for the acTL (animation control) chunk in a PNG file.
+// APNG files contain an acTL chunk that is not present in static PNGs.
+func isAnimatedPNG(data []byte) bool {
+ // PNG signature: 8 bytes
+ pngSig := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}
+ if !bytes.HasPrefix(data, pngSig) {
+ return false
+ }
+
+ // Scan chunks for "acTL" (animation control)
+ pos := uint64(8)
+ dataLen := uint64(len(data))
+ for pos+8 <= dataLen {
+ chunkLen := uint64(binary.BigEndian.Uint32(data[pos : pos+4]))
+ chunkType := string(data[pos+4 : pos+8])
+
+ if chunkType == "acTL" {
+ return true
+ }
+ // Move to next chunk: 4 (length) + 4 (type) + chunkLen (data) + 4 (CRC)
+ pos += 12 + chunkLen
+ }
+ return false
+}
diff --git a/core/artwork/animation_test.go b/core/artwork/animation_test.go
new file mode 100644
index 000000000..9000a8511
--- /dev/null
+++ b/core/artwork/animation_test.go
@@ -0,0 +1,161 @@
+package artwork
+
+import (
+ "bytes"
+ "encoding/binary"
+ "image"
+ "image/color"
+ "image/gif"
+ "image/png"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Animation detection", func() {
+ Describe("isAnimatedGIF", func() {
+ It("detects an animated GIF with multiple frames", func() {
+ Expect(isAnimatedGIF(createAnimatedGIF(2))).To(BeTrue())
+ })
+
+ It("detects an animated GIF with many frames", func() {
+ Expect(isAnimatedGIF(createAnimatedGIF(5))).To(BeTrue())
+ })
+
+ It("does not flag a static GIF (single frame)", func() {
+ Expect(isAnimatedGIF(createAnimatedGIF(1))).To(BeFalse())
+ })
+
+ It("returns false for non-GIF data", func() {
+ Expect(isAnimatedGIF(nil)).To(BeFalse())
+ Expect(isAnimatedGIF([]byte{0xFF, 0xD8})).To(BeFalse())
+ })
+ })
+
+ Describe("isAnimatedWebP", func() {
+ It("detects an animated WebP with ANMF chunk", func() {
+ Expect(isAnimatedWebP(createAnimatedWebPBytes())).To(BeTrue())
+ })
+
+ It("does not flag a static WebP (no ANMF chunk)", func() {
+ Expect(isAnimatedWebP(createStaticWebPBytes())).To(BeFalse())
+ })
+
+ It("returns false for non-WebP data", func() {
+ Expect(isAnimatedWebP(nil)).To(BeFalse())
+ Expect(isAnimatedWebP([]byte{0xFF, 0xD8})).To(BeFalse())
+ })
+ })
+
+ Describe("isAnimatedPNG", func() {
+ It("detects an APNG with acTL chunk", func() {
+ Expect(isAnimatedPNG(createAPNGBytes())).To(BeTrue())
+ })
+
+ It("does not flag a static PNG (no acTL chunk)", func() {
+ Expect(isAnimatedPNG(createStaticPNGBytes())).To(BeFalse())
+ })
+
+ It("returns false for non-PNG data", func() {
+ Expect(isAnimatedPNG(nil)).To(BeFalse())
+ Expect(isAnimatedPNG([]byte{0xFF, 0xD8})).To(BeFalse())
+ })
+ })
+})
+
+// createAnimatedGIF creates a minimal animated GIF with the given number of frames.
+func createAnimatedGIF(frames int) []byte {
+ g := &gif.GIF{
+ LoopCount: 0,
+ }
+ for range frames {
+ img := image.NewPaletted(image.Rect(0, 0, 2, 2), color.Palette{color.Black, color.White})
+ g.Image = append(g.Image, img)
+ g.Delay = append(g.Delay, 10)
+ }
+ var buf bytes.Buffer
+ err := gif.EncodeAll(&buf, g)
+ if err != nil {
+ panic(err)
+ }
+ return buf.Bytes()
+}
+
+// writeUint32LE appends a little-endian uint32 to the buffer.
+func writeUint32LE(buf *bytes.Buffer, v uint32) {
+ b := make([]byte, 4)
+ binary.LittleEndian.PutUint32(b, v)
+ buf.Write(b)
+}
+
+// writeUint32BE appends a big-endian uint32 to the buffer.
+func writeUint32BE(buf *bytes.Buffer, v uint32) {
+ b := make([]byte, 4)
+ binary.BigEndian.PutUint32(b, v)
+ buf.Write(b)
+}
+
+// createAnimatedWebPBytes creates a minimal RIFF/WEBP container with an ANMF chunk.
+func createAnimatedWebPBytes() []byte {
+ var buf bytes.Buffer
+ buf.WriteString("RIFF")
+ writeUint32LE(&buf, 100) // file size placeholder
+ buf.WriteString("WEBP")
+ // VP8X chunk (extended format, required for animation)
+ buf.WriteString("VP8X")
+ writeUint32LE(&buf, 10)
+ buf.Write(make([]byte, 10))
+ // ANIM chunk (animation parameters)
+ buf.WriteString("ANIM")
+ writeUint32LE(&buf, 6)
+ buf.Write(make([]byte, 6))
+ // ANMF chunk (animation frame)
+ buf.WriteString("ANMF")
+ writeUint32LE(&buf, 16)
+ buf.Write(make([]byte, 16))
+ return buf.Bytes()
+}
+
+// createStaticWebPBytes creates a minimal RIFF/WEBP container without ANMF chunks.
+func createStaticWebPBytes() []byte {
+ var buf bytes.Buffer
+ buf.WriteString("RIFF")
+ writeUint32LE(&buf, 20) // file size
+ buf.WriteString("WEBP")
+ // VP8 chunk (simple lossy format)
+ buf.WriteString("VP8 ")
+ writeUint32LE(&buf, 4)
+ buf.Write(make([]byte, 4))
+ return buf.Bytes()
+}
+
+// createAPNGBytes creates a minimal PNG with an acTL chunk (making it APNG).
+func createAPNGBytes() []byte {
+ // Start with a real PNG
+ staticPNG := createStaticPNGBytes()
+
+ // Insert an acTL chunk after the IHDR chunk.
+ // PNG structure: signature (8) + IHDR chunk (4 len + 4 type + 13 data + 4 crc = 25)
+ ihdrEnd := 8 + 25
+ var buf bytes.Buffer
+ buf.Write(staticPNG[:ihdrEnd])
+ // Write acTL chunk: length=8, type="acTL", data=num_frames(4)+num_plays(4), CRC=4
+ writeUint32BE(&buf, 8) // chunk data length
+ buf.WriteString("acTL")
+ writeUint32BE(&buf, 2) // num_frames
+ writeUint32BE(&buf, 0) // num_plays (0 = infinite)
+ writeUint32BE(&buf, 0) // CRC placeholder
+ buf.Write(staticPNG[ihdrEnd:])
+ return buf.Bytes()
+}
+
+// createStaticPNGBytes creates a minimal valid static PNG.
+func createStaticPNGBytes() []byte {
+ img := image.NewRGBA(image.Rect(0, 0, 2, 2))
+ var buf bytes.Buffer
+ err := png.Encode(&buf, img)
+ if err != nil {
+ panic(err)
+ }
+ return buf.Bytes()
+}
diff --git a/core/artwork/artwork.go b/core/artwork/artwork.go
index 2e92b24c8..b8c395c12 100644
--- a/core/artwork/artwork.go
+++ b/core/artwork/artwork.go
@@ -122,6 +122,10 @@ func (a *artwork) getArtworkReader(ctx context.Context, artID model.ArtworkID, s
artReader, err = newMediafileArtworkReader(ctx, a, artID)
case model.KindPlaylistArtwork:
artReader, err = newPlaylistArtworkReader(ctx, a, artID)
+ case model.KindDiscArtwork:
+ artReader, err = newDiscArtworkReader(ctx, a, artID)
+ case model.KindRadioArtwork:
+ artReader, err = newRadioArtworkReader(ctx, a, artID)
default:
return nil, ErrUnavailable
}
diff --git a/core/artwork/artwork_internal_test.go b/core/artwork/artwork_internal_test.go
index cfb7850bd..4b2359898 100644
--- a/core/artwork/artwork_internal_test.go
+++ b/core/artwork/artwork_internal_test.go
@@ -7,9 +7,12 @@ import (
"image/jpeg"
"image/png"
"io"
+
"os"
"path/filepath"
+ _ "github.com/gen2brain/webp"
+
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
@@ -25,7 +28,7 @@ var _ = Describe("Artwork", func() {
var ffmpeg *tests.MockFFmpeg
var folderRepo *fakeFolderRepo
ctx := log.NewContext(context.TODO())
- var alOnlyEmbed, alEmbedNotFound, alOnlyExternal, alExternalNotFound, alMultipleCovers model.Album
+ var alOnlyEmbed, alEmbedNotFound, alOnlyExternal, alExternalNotFound, alMultipleCovers, alSingleDisc model.Album
var arMultipleCovers model.Artist
var mfWithEmbed, mfAnotherWithEmbed, mfWithoutEmbed, mfCorruptedCover model.MediaFile
@@ -41,8 +44,9 @@ var _ = Describe("Artwork", func() {
}
alOnlyEmbed = model.Album{ID: "222", Name: "Only embed", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}}
alEmbedNotFound = model.Album{ID: "333", Name: "Embed not found", EmbedArtPath: "tests/fixtures/NON_EXISTENT.mp3", FolderIDs: []string{"f1"}}
- alOnlyExternal = model.Album{ID: "444", Name: "Only external", FolderIDs: []string{"f1"}}
+ alOnlyExternal = model.Album{ID: "444", Name: "Only external", FolderIDs: []string{"f1"}, Discs: model.Discs{1: "", 2: ""}}
alExternalNotFound = model.Album{ID: "555", Name: "External not found", FolderIDs: []string{"f2"}}
+ alSingleDisc = model.Album{ID: "888", Name: "Single disc", FolderIDs: []string{"f1"}, Discs: model.Discs{1: ""}}
arMultipleCovers = model.Artist{ID: "777", Name: "All options"}
alMultipleCovers = model.Album{
ID: "666",
@@ -190,6 +194,7 @@ var _ = Describe("Artwork", func() {
ds.Album(ctx).(*tests.MockAlbumRepo).SetData(model.Albums{
alOnlyEmbed,
alOnlyExternal,
+ alSingleDisc,
})
ds.MediaFile(ctx).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
mfWithEmbed,
@@ -233,8 +238,137 @@ var _ = Describe("Artwork", func() {
Expect(err).ToNot(HaveOccurred())
Expect(path).To(Equal("al-444_0"))
})
+ It("falls back to disc cover art when media file has a disc number on a multi-disc album", func() {
+ mfWithDisc := model.MediaFile{ID: "46", Path: "tests/fixtures/test.ogg", AlbumID: "444", DiscNumber: 2}
+ Expect(ds.MediaFile(ctx).(*tests.MockMediaFileRepo).Put(&mfWithDisc)).To(Succeed())
+
+ aw, err := newMediafileArtworkReader(ctx, aw, model.MustParseArtworkID("mf-"+mfWithDisc.ID))
+ Expect(err).ToNot(HaveOccurred())
+ _, path, err := aw.Reader(ctx)
+ Expect(err).ToNot(HaveOccurred())
+ // Should fall back to disc art, which itself falls back to album art
+ Expect(path).To(Equal("dc-444:2_0"))
+ })
+ It("falls back to album cover art for single-disc albums even with a disc number", func() {
+ mfOnSingleDisc := model.MediaFile{ID: "47", Path: "tests/fixtures/test.ogg", AlbumID: "888", DiscNumber: 1}
+ Expect(ds.MediaFile(ctx).(*tests.MockMediaFileRepo).Put(&mfOnSingleDisc)).To(Succeed())
+
+ aw, err := newMediafileArtworkReader(ctx, aw, model.MustParseArtworkID("mf-"+mfOnSingleDisc.ID))
+ Expect(err).ToNot(HaveOccurred())
+ _, path, err := aw.Reader(ctx)
+ Expect(err).ToNot(HaveOccurred())
+ // Single-disc album should skip disc art and go straight to album art
+ Expect(path).To(Equal("al-888_0"))
+ })
})
})
+ Describe("playlistArtworkReader", func() {
+ Describe("findPlaylistSidecarPath", func() {
+ It("discovers sidecar image next to playlist file", func() {
+ tmpDir := GinkgoT().TempDir()
+ plsPath := filepath.Join(tmpDir, "MyPlaylist.m3u")
+ imgPath := filepath.Join(tmpDir, "MyPlaylist.jpg")
+ Expect(os.WriteFile(plsPath, []byte("#EXTM3U\n"), 0600)).To(Succeed())
+ Expect(os.WriteFile(imgPath, []byte("fake image"), 0600)).To(Succeed())
+
+ result := findPlaylistSidecarPath(GinkgoT().Context(), plsPath)
+ Expect(result).To(Equal(imgPath))
+ })
+
+ It("returns empty string when no sidecar image exists", func() {
+ tmpDir := GinkgoT().TempDir()
+ plsPath := filepath.Join(tmpDir, "MyPlaylist.m3u")
+ Expect(os.WriteFile(plsPath, []byte("#EXTM3U\n"), 0600)).To(Succeed())
+
+ result := findPlaylistSidecarPath(GinkgoT().Context(), plsPath)
+ Expect(result).To(BeEmpty())
+ })
+
+ It("returns empty string when playlist has no path", func() {
+ result := findPlaylistSidecarPath(GinkgoT().Context(), "")
+ Expect(result).To(BeEmpty())
+ })
+
+ It("finds sidecar with different case base name", func() {
+ tmpDir := GinkgoT().TempDir()
+ plsPath := filepath.Join(tmpDir, "myplaylist.m3u")
+ imgPath := filepath.Join(tmpDir, "MyPlaylist.jpg")
+ Expect(os.WriteFile(plsPath, []byte("#EXTM3U\n"), 0600)).To(Succeed())
+ Expect(os.WriteFile(imgPath, []byte("fake image"), 0600)).To(Succeed())
+
+ result := findPlaylistSidecarPath(GinkgoT().Context(), plsPath)
+ Expect(result).To(Equal(imgPath))
+ })
+ })
+
+ Describe("fromPlaylistExternalImage", func() {
+ It("opens local path from ExternalImageURL", func() {
+ tmpDir := GinkgoT().TempDir()
+ imgPath := filepath.Join(tmpDir, "cover.jpg")
+ Expect(os.WriteFile(imgPath, []byte("external image data"), 0600)).To(Succeed())
+
+ reader := &playlistArtworkReader{
+ pl: model.Playlist{ExternalImageURL: imgPath},
+ }
+ r, path, err := reader.fromPlaylistExternalImage(ctx)()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+ data, _ := io.ReadAll(r)
+ Expect(string(data)).To(Equal("external image data"))
+ r.Close()
+ })
+
+ It("returns nil when ExternalImageURL is empty", func() {
+ reader := &playlistArtworkReader{
+ pl: model.Playlist{ExternalImageURL: ""},
+ }
+ r, path, err := reader.fromPlaylistExternalImage(ctx)()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).To(BeNil())
+ Expect(path).To(BeEmpty())
+ })
+
+ It("returns error when local file does not exist", func() {
+ reader := &playlistArtworkReader{
+ pl: model.Playlist{ExternalImageURL: "/non/existent/path/cover.jpg"},
+ }
+ r, _, err := reader.fromPlaylistExternalImage(ctx)()
+ Expect(err).To(HaveOccurred())
+ Expect(r).To(BeNil())
+ })
+
+ It("skips HTTP URL when EnableM3UExternalAlbumArt is false", func() {
+ conf.Server.EnableM3UExternalAlbumArt = false
+
+ reader := &playlistArtworkReader{
+ pl: model.Playlist{ExternalImageURL: "https://example.com/cover.jpg"},
+ }
+ r, path, err := reader.fromPlaylistExternalImage(ctx)()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).To(BeNil())
+ Expect(path).To(BeEmpty())
+ })
+
+ It("still opens local path when EnableM3UExternalAlbumArt is false", func() {
+ conf.Server.EnableM3UExternalAlbumArt = false
+
+ tmpDir := GinkgoT().TempDir()
+ imgPath := filepath.Join(tmpDir, "cover.jpg")
+ Expect(os.WriteFile(imgPath, []byte("local image"), 0600)).To(Succeed())
+
+ reader := &playlistArtworkReader{
+ pl: model.Playlist{ExternalImageURL: imgPath},
+ }
+ r, path, err := reader.fromPlaylistExternalImage(ctx)()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+ r.Close()
+ })
+ })
+ })
+
Describe("resizedArtworkReader", func() {
BeforeEach(func() {
folderRepo.result = []model.Folder{{
@@ -246,24 +380,24 @@ var _ = Describe("Artwork", func() {
})
})
When("Square is false", func() {
- It("returns a PNG if original image is a PNG", func() {
+ It("returns WebP even if original image is a PNG", func() {
conf.Server.CoverArtPriority = "front.png"
r, _, err := aw.Get(context.Background(), alMultipleCovers.CoverArtID(), 15, false)
Expect(err).ToNot(HaveOccurred())
img, format, err := image.Decode(r)
Expect(err).ToNot(HaveOccurred())
- Expect(format).To(Equal("png"))
+ Expect(format).To(Equal("webp"))
Expect(img.Bounds().Size().X).To(Equal(15))
Expect(img.Bounds().Size().Y).To(Equal(15))
})
- It("returns a JPEG if original image is not a PNG", func() {
+ It("returns WebP if original image is not a PNG", func() {
conf.Server.CoverArtPriority = "cover.jpg"
r, _, err := aw.Get(context.Background(), alMultipleCovers.CoverArtID(), 200, false)
Expect(err).ToNot(HaveOccurred())
img, format, err := image.Decode(r)
- Expect(format).To(Equal("jpeg"))
+ Expect(format).To(Equal("webp"))
Expect(err).ToNot(HaveOccurred())
Expect(img.Bounds().Size().X).To(Equal(200))
Expect(img.Bounds().Size().Y).To(Equal(200))
@@ -273,9 +407,9 @@ var _ = Describe("Artwork", func() {
var alCover model.Album
DescribeTable("resize",
- func(format string, landscape bool, size int) {
- coverFileName := "cover." + format
- dirName := createImage(format, landscape, size)
+ func(srcFormat string, expectedFormat string, landscape bool, size int) {
+ coverFileName := "cover." + srcFormat
+ dirName := createImage(srcFormat, landscape, size)
alCover = model.Album{
ID: "444",
Name: "Only external",
@@ -292,16 +426,97 @@ var _ = Describe("Artwork", func() {
img, format, err := image.Decode(r)
Expect(err).ToNot(HaveOccurred())
- Expect(format).To(Equal("png"))
+ Expect(format).To(Equal(expectedFormat))
Expect(img.Bounds().Size().X).To(Equal(size))
Expect(img.Bounds().Size().Y).To(Equal(size))
},
- Entry("portrait png image", "png", false, 200),
- Entry("landscape png image", "png", true, 200),
- Entry("portrait jpg image", "jpg", false, 200),
- Entry("landscape jpg image", "jpg", true, 200),
+ Entry("portrait png image", "png", "webp", false, 200),
+ Entry("landscape png image", "png", "webp", true, 200),
+ Entry("portrait jpg image", "jpg", "webp", false, 200),
+ Entry("landscape jpg image", "jpg", "webp", true, 200),
)
})
+ When("DevJpegCoverArt is true and square is false", func() {
+ BeforeEach(func() {
+ conf.Server.DevJpegCoverArt = true
+ })
+ It("returns JPEG even if original image is a PNG", func() {
+ conf.Server.CoverArtPriority = "front.png"
+ r, _, err := aw.Get(context.Background(), alMultipleCovers.CoverArtID(), 15, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ img, format, err := image.Decode(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(format).To(Equal("jpeg"))
+ Expect(img.Bounds().Size().X).To(Equal(15))
+ Expect(img.Bounds().Size().Y).To(Equal(15))
+ })
+ It("returns JPEG if original image is a JPG", func() {
+ conf.Server.CoverArtPriority = "cover.jpg"
+ r, _, err := aw.Get(context.Background(), alMultipleCovers.CoverArtID(), 200, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ img, format, err := image.Decode(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(format).To(Equal("jpeg"))
+ Expect(img.Bounds().Size().X).To(Equal(200))
+ Expect(img.Bounds().Size().Y).To(Equal(200))
+ })
+ })
+ When("DevJpegCoverArt is true and square is true", func() {
+ var alCover model.Album
+
+ BeforeEach(func() {
+ conf.Server.DevJpegCoverArt = true
+ })
+ It("returns PNG for square mode", func() {
+ dirName := createImage("png", false, 200)
+ alCover = model.Album{
+ ID: "444",
+ Name: "Only external",
+ FolderIDs: []string{"tmp"},
+ }
+ folderRepo.result = []model.Folder{{Path: dirName, ImageFiles: []string{"cover.png"}}}
+ ds.Album(ctx).(*tests.MockAlbumRepo).SetData(model.Albums{alCover})
+
+ conf.Server.CoverArtPriority = "cover.png"
+ r, _, err := aw.Get(context.Background(), alCover.CoverArtID(), 200, true)
+ Expect(err).ToNot(HaveOccurred())
+
+ img, format, err := image.Decode(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(format).To(Equal("png"))
+ Expect(img.Bounds().Size().X).To(Equal(200))
+ Expect(img.Bounds().Size().Y).To(Equal(200))
+ })
+ })
+ When("Requested size is larger than original", func() {
+ It("clamps size to original dimensions", func() {
+ conf.Server.CoverArtPriority = "front.png"
+ // front.png is 16x16, requesting 99999 should return at original size
+ r, _, err := aw.Get(context.Background(), alMultipleCovers.CoverArtID(), 99999, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ img, _, err := image.Decode(r)
+ Expect(err).ToNot(HaveOccurred())
+ // Should be clamped to original size (16), not 99999
+ Expect(img.Bounds().Size().X).To(Equal(16))
+ Expect(img.Bounds().Size().Y).To(Equal(16))
+ })
+
+ It("clamps square size to original dimensions", func() {
+ conf.Server.CoverArtPriority = "front.png"
+ // front.png is 16x16, requesting 99999 with square should return 16x16 square
+ r, _, err := aw.Get(context.Background(), alMultipleCovers.CoverArtID(), 99999, true)
+ Expect(err).ToNot(HaveOccurred())
+
+ img, _, err := image.Decode(r)
+ Expect(err).ToNot(HaveOccurred())
+ // Should be clamped to original size (16), not 99999
+ Expect(img.Bounds().Size().X).To(Equal(16))
+ Expect(img.Bounds().Size().Y).To(Equal(16))
+ })
+ })
})
})
diff --git a/core/artwork/benchmark_decode_test.go b/core/artwork/benchmark_decode_test.go
new file mode 100644
index 000000000..cfbfe5605
--- /dev/null
+++ b/core/artwork/benchmark_decode_test.go
@@ -0,0 +1,37 @@
+package artwork
+
+import (
+ "bytes"
+ "fmt"
+ "image"
+ _ "image/jpeg"
+ _ "image/png"
+ "testing"
+)
+
+func BenchmarkImageDecode(b *testing.B) {
+ sizes := []int{300, 1000, 3000}
+ formats := []struct {
+ name string
+ gen func(tb testing.TB, w, h int) []byte
+ }{
+ {"jpeg", func(tb testing.TB, w, h int) []byte { return generateJPEG(tb, w, h, 75) }},
+ {"png", func(tb testing.TB, w, h int) []byte { return generatePNG(tb, w, h) }},
+ }
+
+ for _, format := range formats {
+ for _, size := range sizes {
+ data := format.gen(b, size, size)
+ b.Run(fmt.Sprintf("%s/%dx%d", format.name, size, size), func(b *testing.B) {
+ b.SetBytes(int64(len(data)))
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ _, _, err := image.Decode(bytes.NewReader(data))
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+ }
+ }
+}
diff --git a/core/artwork/benchmark_e2e_test.go b/core/artwork/benchmark_e2e_test.go
new file mode 100644
index 000000000..c27964018
--- /dev/null
+++ b/core/artwork/benchmark_e2e_test.go
@@ -0,0 +1,189 @@
+package artwork
+
+import (
+ "context"
+ "fmt"
+ "image/jpeg"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ "github.com/navidrome/navidrome/utils/cache"
+)
+
+// setupE2EBenchmark creates an artwork instance with a real album cover image on disk,
+// backed by either a real file cache or disabled cache depending on cacheSize.
+// Note: This benchmarks artwork.Get() directly (not the full HTTP handler), which covers
+// the critical path (source selection, decode, resize, encode, cache). This is a deliberate
+// spec deviation — the full HTTP round-trip benchmark requires significant infrastructure
+// (DB, scanner, fake filesystem) and can be added later if HTTP overhead proves significant.
+//
+// Depends on fakeFolderRepo defined in reader_artist_test.go (same package, compiled together).
+func setupE2EBenchmark(b *testing.B, cacheSize string) (Artwork, model.ArtworkID, func()) {
+ b.Helper()
+ cleanup := configtest.SetupConfig()
+ b.Cleanup(cleanup)
+
+ tmpDir, err := os.MkdirTemp("", "artwork-bench-*")
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ // Create a realistic cover image on disk
+ coverPath := filepath.Join(tmpDir, "cover.jpg")
+ coverImg := generateGradientImage(1000, 1000)
+ f, err := os.Create(coverPath)
+ if err != nil {
+ b.Fatal(err)
+ }
+ if err := jpeg.Encode(f, coverImg, &jpeg.Options{Quality: 90}); err != nil {
+ f.Close()
+ b.Fatal(err)
+ }
+ f.Close()
+
+ // Configure cache
+ conf.Server.ImageCacheSize = cacheSize
+ conf.Server.CacheFolder = tmpDir
+ conf.Server.CoverArtQuality = 75
+ conf.Server.CoverArtPriority = "cover.*"
+
+ // Set up mock data store with album pointing to our cover.
+ // Set UpdatedAt so CoverArtID().LastUpdate is consistent across calls.
+ album := model.Album{
+ ID: "bench-album-1",
+ Name: "Benchmark Album",
+ FolderIDs: []string{"f1"},
+ UpdatedAt: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC),
+ }
+ folderRepo := &fakeFolderRepo{
+ result: []model.Folder{{
+ Path: tmpDir,
+ ImageFiles: []string{"cover.jpg"},
+ }},
+ }
+ ds := &tests.MockDataStore{
+ MockedTranscoding: &tests.MockTranscodingRepo{},
+ MockedFolder: folderRepo,
+ }
+ ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{album})
+
+ artID := album.CoverArtID()
+
+ imgCache := cache.NewFileCache("BenchImage", cacheSize, "bench-images", 0,
+ func(ctx context.Context, arg cache.Item) (io.Reader, error) {
+ r, _, err := arg.(artworkReader).Reader(ctx)
+ return r, err
+ })
+
+ // Wait for cache init if enabled
+ if cacheSize != "0" {
+ for !imgCache.Available(context.Background()) && !imgCache.Disabled(context.Background()) {
+ runtime.Gosched() // Yield to allow background init goroutine to run
+ }
+ }
+
+ ffmpeg := tests.NewMockFFmpeg("fallback content")
+ aw := NewArtwork(ds, imgCache, ffmpeg, nil)
+
+ cleanupAll := func() {
+ os.RemoveAll(tmpDir)
+ }
+ return aw, artID, cleanupAll
+}
+
+func BenchmarkArtworkGetE2E(b *testing.B) {
+ cacheConfigs := []struct {
+ name string
+ cacheSize string
+ }{
+ {"no_cache", "0"},
+ {"with_cache", "100MB"},
+ }
+ sizes := []int{0, 300}
+
+ for _, cc := range cacheConfigs {
+ for _, size := range sizes {
+ b.Run(fmt.Sprintf("%s/size_%d", cc.name, size), func(b *testing.B) {
+ aw, artID, cleanup := setupE2EBenchmark(b, cc.cacheSize)
+ defer cleanup()
+
+ // Warm the cache on first call if cache is enabled
+ if cc.cacheSize != "0" {
+ r, _, err := aw.Get(context.Background(), artID, size, size > 0)
+ if err != nil {
+ b.Fatal(err)
+ }
+ _, _ = io.ReadAll(r)
+ r.Close()
+ }
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ r, _, err := aw.Get(context.Background(), artID, size, size > 0)
+ if err != nil {
+ b.Fatal(err)
+ }
+ _, _ = io.ReadAll(r)
+ r.Close()
+ }
+ })
+ }
+ }
+}
+
+func BenchmarkArtworkGetE2EConcurrent(b *testing.B) {
+ cacheConfigs := []struct {
+ name string
+ cacheSize string
+ }{
+ {"no_cache", "0"},
+ {"with_cache", "100MB"},
+ }
+ concurrencyLevels := []int{10, 50}
+
+ for _, cc := range cacheConfigs {
+ for _, n := range concurrencyLevels {
+ b.Run(fmt.Sprintf("%s/goroutines_%d", cc.name, n), func(b *testing.B) {
+ aw, artID, cleanup := setupE2EBenchmark(b, cc.cacheSize)
+ defer cleanup()
+
+ // Warm cache
+ if cc.cacheSize != "0" {
+ r, _, _ := aw.Get(context.Background(), artID, 300, true)
+ if r != nil {
+ _, _ = io.ReadAll(r)
+ r.Close()
+ }
+ }
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ var wg sync.WaitGroup
+ wg.Add(n)
+ for g := 0; g < n; g++ {
+ go func() {
+ defer wg.Done()
+ r, _, err := aw.Get(context.Background(), artID, 300, true)
+ if err != nil {
+ b.Error(err)
+ return
+ }
+ _, _ = io.ReadAll(r)
+ r.Close()
+ }()
+ }
+ wg.Wait()
+ }
+ })
+ }
+ }
+}
diff --git a/core/artwork/benchmark_encode_test.go b/core/artwork/benchmark_encode_test.go
new file mode 100644
index 000000000..d8ab858f5
--- /dev/null
+++ b/core/artwork/benchmark_encode_test.go
@@ -0,0 +1,40 @@
+package artwork
+
+import (
+ "bytes"
+ "fmt"
+ "image/jpeg"
+ "image/png"
+ "testing"
+)
+
+func BenchmarkImageEncode(b *testing.B) {
+ img := generateGradientImage(300, 300)
+
+ jpegQualities := []int{60, 75, 90}
+ for _, q := range jpegQualities {
+ b.Run(fmt.Sprintf("jpeg/q%d/300x300", q), func(b *testing.B) {
+ var buf bytes.Buffer
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: q}); err != nil {
+ b.Fatal(err)
+ }
+ }
+ b.ReportMetric(float64(buf.Len()), "bytes")
+ })
+ }
+
+ b.Run("png/300x300", func(b *testing.B) {
+ var buf bytes.Buffer
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ if err := png.Encode(&buf, img); err != nil {
+ b.Fatal(err)
+ }
+ }
+ b.ReportMetric(float64(buf.Len()), "bytes")
+ })
+}
diff --git a/core/artwork/benchmark_helpers_test.go b/core/artwork/benchmark_helpers_test.go
new file mode 100644
index 000000000..60990bb8b
--- /dev/null
+++ b/core/artwork/benchmark_helpers_test.go
@@ -0,0 +1,47 @@
+package artwork
+
+import (
+ "bytes"
+ "image"
+ "image/color"
+ "image/jpeg"
+ "image/png"
+ "testing"
+)
+
+// generateJPEG creates a JPEG image of the given dimensions with a gradient pattern.
+// The gradient ensures the image has realistic entropy (not trivially compressible).
+func generateJPEG(t testing.TB, width, height, quality int) []byte {
+ t.Helper()
+ img := generateGradientImage(width, height)
+ var buf bytes.Buffer
+ if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// generatePNG creates a PNG image of the given dimensions with a gradient pattern.
+func generatePNG(t testing.TB, width, height int) []byte {
+ t.Helper()
+ img := generateGradientImage(width, height)
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, img); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// generateGradientImage creates an RGBA image with a diagonal gradient pattern.
+func generateGradientImage(width, height int) *image.RGBA {
+ img := image.NewRGBA(image.Rect(0, 0, width, height))
+ for y := 0; y < height; y++ {
+ for x := 0; x < width; x++ {
+ r := uint8((x * 255) / width)
+ g := uint8((y * 255) / height)
+ b := uint8(((x + y) * 255) / (width + height))
+ img.Set(x, y, color.RGBA{R: r, G: g, B: b, A: 255})
+ }
+ }
+ return img
+}
diff --git a/core/artwork/benchmark_pipeline_test.go b/core/artwork/benchmark_pipeline_test.go
new file mode 100644
index 000000000..23d5954df
--- /dev/null
+++ b/core/artwork/benchmark_pipeline_test.go
@@ -0,0 +1,50 @@
+package artwork
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+)
+
+func BenchmarkResizeFullPipeline(b *testing.B) {
+ cleanup := configtest.SetupConfig()
+ b.Cleanup(cleanup)
+ conf.Server.CoverArtQuality = 75
+
+ sourceSizes := []int{1000, 3000}
+ targetSize := 300
+
+ for _, srcSize := range sourceSizes {
+ jpegData := generateJPEG(b, srcSize, srcSize, 90)
+
+ b.Run(fmt.Sprintf("jpeg/%dx%d_to_%d", srcSize, srcSize, targetSize), func(b *testing.B) {
+ b.SetBytes(int64(len(jpegData)))
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ result, _, err := resizeStaticImage(jpegData, targetSize, false)
+ if err != nil {
+ b.Fatal(err)
+ }
+ if result == nil {
+ b.Fatal("expected non-nil resized image")
+ }
+ }
+ })
+
+ b.Run(fmt.Sprintf("jpeg/%dx%d_to_%d_square", srcSize, srcSize, targetSize), func(b *testing.B) {
+ b.SetBytes(int64(len(jpegData)))
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ result, _, err := resizeStaticImage(jpegData, targetSize, true)
+ if err != nil {
+ b.Fatal(err)
+ }
+ if result == nil {
+ b.Fatal("expected non-nil resized image")
+ }
+ }
+ })
+ }
+}
diff --git a/core/artwork/benchmark_tag_test.go b/core/artwork/benchmark_tag_test.go
new file mode 100644
index 000000000..fd649beab
--- /dev/null
+++ b/core/artwork/benchmark_tag_test.go
@@ -0,0 +1,38 @@
+package artwork
+
+import (
+ "path/filepath"
+ "runtime"
+ "testing"
+
+ "go.senan.xyz/taglib"
+)
+
+func BenchmarkTagExtraction(b *testing.B) {
+ // Ensure working directory is the project root (tests.Init not called with -run='^$')
+ _, file, _, ok := runtime.Caller(0)
+ if !ok {
+ b.Fatal("runtime.Caller failed")
+ }
+ appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..", ".."))
+
+ // Use existing test fixture with embedded artwork
+ testFile := filepath.Join(appPath, "tests/fixtures/artist/an-album/test.mp3")
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ f, err := taglib.OpenReadOnly(testFile, taglib.WithReadStyle(taglib.ReadStyleFast))
+ if err != nil {
+ b.Fatal(err)
+ }
+ images := f.Properties().Images
+ if len(images) == 0 {
+ b.Fatal("no images found in test file")
+ }
+ data, err := f.Image(0)
+ if err != nil || len(data) == 0 {
+ b.Fatal("failed to extract image data")
+ }
+ f.Close()
+ }
+}
diff --git a/core/artwork/cache_warmer.go b/core/artwork/cache_warmer.go
index 909d299d8..bd1359b74 100644
--- a/core/artwork/cache_warmer.go
+++ b/core/artwork/cache_warmer.go
@@ -132,7 +132,7 @@ func (a *cacheWarmer) waitSignal(ctx context.Context, timeout time.Duration) {
func (a *cacheWarmer) processBatch(ctx context.Context, batch []model.ArtworkID) {
log.Trace(ctx, "PreCaching a new batch of artwork", "batchSize", len(batch))
input := pl.FromSlice(ctx, batch)
- errs := pl.Sink(ctx, 2, input, a.doCacheImage)
+ errs := pl.Sink(ctx, 4, input, a.doCacheImage)
for err := range errs {
log.Debug(ctx, "Error warming cache", err)
}
@@ -142,13 +142,13 @@ func (a *cacheWarmer) doCacheImage(ctx context.Context, id model.ArtworkID) erro
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
- r, _, err := a.artwork.Get(ctx, id, consts.UICoverArtSize, true)
- if err != nil {
- return fmt.Errorf("caching id='%s': %w", id, err)
- }
- defer r.Close()
- _, err = io.Copy(io.Discard, r)
- if err != nil {
+ for _, size := range consts.CacheWarmerImageSizes {
+ r, _, err := a.artwork.Get(ctx, id, size, true)
+ if err != nil {
+ return fmt.Errorf("caching id='%s', size=%d: %w", id, size, err)
+ }
+ _, err = io.Copy(io.Discard, r)
+ r.Close()
return err
}
return nil
diff --git a/core/artwork/cache_warmer_test.go b/core/artwork/cache_warmer_test.go
index 4125d6de0..9798ea8d6 100644
--- a/core/artwork/cache_warmer_test.go
+++ b/core/artwork/cache_warmer_test.go
@@ -6,11 +6,13 @@ import (
"fmt"
"io"
"strings"
+ "sync"
"sync/atomic"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/cache"
. "github.com/onsi/ginkgo/v2"
@@ -90,6 +92,7 @@ var _ = Describe("CacheWarmer", func() {
})
It("deduplicates items in buffer", func() {
+ fc.SetReady(false) // Make cache unavailable so items stay in buffer
cw := NewCacheWarmer(aw, fc).(*cacheWarmer)
cw.PreCache(model.MustParseArtworkID("al-1"))
cw.PreCache(model.MustParseArtworkID("al-1"))
@@ -142,7 +145,7 @@ var _ = Describe("CacheWarmer", func() {
It("processes items in batches", func() {
cw := NewCacheWarmer(aw, fc).(*cacheWarmer)
- for i := 0; i < 5; i++ {
+ for i := range 5 {
cw.PreCache(model.MustParseArtworkID(fmt.Sprintf("al-%d", i)))
}
@@ -172,20 +175,42 @@ var _ = Describe("CacheWarmer", func() {
return len(cw.buffer)
}).Should(Equal(0))
})
+
+ It("pre-caches UICoverArtSize", func() {
+ cw := NewCacheWarmer(aw, fc).(*cacheWarmer)
+ cw.PreCache(model.MustParseArtworkID("al-1"))
+
+ Eventually(func() []int {
+ return aw.getCachedSizes()
+ }).Should(ContainElements(consts.UICoverArtSize))
+ })
})
})
type mockArtwork struct {
- err error
+ err error
+ mu sync.Mutex
+ cachedSizes []int
}
func (m *mockArtwork) Get(ctx context.Context, artID model.ArtworkID, size int, square bool) (io.ReadCloser, time.Time, error) {
if m.err != nil {
return nil, time.Time{}, m.err
}
+ m.mu.Lock()
+ m.cachedSizes = append(m.cachedSizes, size)
+ m.mu.Unlock()
return io.NopCloser(strings.NewReader("test")), time.Now(), nil
}
+func (m *mockArtwork) getCachedSizes() []int {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ result := make([]int, len(m.cachedSizes))
+ copy(result, m.cachedSizes)
+ return result
+}
+
func (m *mockArtwork) GetOrPlaceholder(ctx context.Context, id string, size int, square bool) (io.ReadCloser, time.Time, error) {
return m.Get(ctx, model.ArtworkID{}, size, square)
}
diff --git a/core/artwork/reader_album.go b/core/artwork/reader_album.go
index 55d8b4352..6de1d31d1 100644
--- a/core/artwork/reader_album.go
+++ b/core/artwork/reader_album.go
@@ -1,8 +1,10 @@
package artwork
import (
+ "cmp"
"context"
"crypto/md5"
+ "errors"
"fmt"
"io"
"path/filepath"
@@ -15,7 +17,9 @@ import (
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/utils/natural"
)
type albumArtworkReader struct {
@@ -55,10 +59,11 @@ func newAlbumArtworkReader(ctx context.Context, artwork *artwork, artID model.Ar
}
func (a *albumArtworkReader) Key() string {
- var hash [16]byte
+ hashInput := conf.Server.CoverArtPriority
if conf.Server.EnableExternalServices {
- hash = md5.Sum([]byte(conf.Server.Agents + conf.Server.CoverArtPriority))
+ hashInput += conf.Server.Agents
}
+ hash := md5.Sum([]byte(hashInput))
return fmt.Sprintf(
"%s.%x.%t",
a.cacheKey.Key(),
@@ -77,7 +82,7 @@ func (a *albumArtworkReader) Reader(ctx context.Context) (io.ReadCloser, string,
func (a *albumArtworkReader) fromCoverArtPriority(ctx context.Context, ffmpeg ffmpeg.FFmpeg, priority string) []sourceFunc {
var ff []sourceFunc
- for _, pattern := range strings.Split(strings.ToLower(priority), ",") {
+ for pattern := range strings.SplitSeq(strings.ToLower(priority), ",") {
pattern = strings.TrimSpace(pattern)
switch {
case pattern == "embedded":
@@ -101,6 +106,28 @@ func loadAlbumFoldersPaths(ctx context.Context, ds model.DataStore, albums ...mo
if err != nil {
return nil, nil, nil, err
}
+
+ folderIDSet := make(map[string]bool, len(folderIDs))
+ for _, id := range folderIDs {
+ folderIDSet[id] = true
+ }
+
+ // For multi-disc albums (2+ folders), check if all folders share a common parent
+ // that is not already included. This finds cover art in the album root folder
+ // (e.g., "Artist/Album/cover.jpg" when tracks are in "Artist/Album/CD1/" and "Artist/Album/CD2/").
+ // We skip single-folder albums to avoid pulling images from the artist folder.
+ if commonParentID := commonParentFolder(folders, folderIDSet); commonParentID != "" {
+ parentFolder, err := ds.Folder(ctx).Get(commonParentID)
+ if errors.Is(err, model.ErrNotFound) {
+ log.Warn(ctx, "Parent folder not found for album cover art lookup", "parentID", commonParentID)
+ } else if err != nil {
+ return nil, nil, nil, err
+ }
+ if parentFolder != nil {
+ folders = append(folders, *parentFolder)
+ }
+ }
+
var paths []string
var imgFiles []string
var updatedAt time.Time
@@ -116,8 +143,48 @@ func loadAlbumFoldersPaths(ctx context.Context, ds model.DataStore, albums ...mo
}
// Sort image files to ensure consistent selection of cover art
- // This prioritizes files from lower-numbered disc folders by sorting the paths
- slices.Sort(imgFiles)
+ // This prioritizes files without numeric suffixes (e.g., cover.jpg over cover.1.jpg)
+ // by comparing base filenames without extensions
+ slices.SortFunc(imgFiles, compareImageFiles)
return paths, imgFiles, &updatedAt, nil
}
+
+// commonParentFolder returns the shared parent folder ID when all folders have the
+// same parent and that parent is not already in folderIDSet. Returns "" otherwise.
+func commonParentFolder(folders []model.Folder, folderIDSet map[string]bool) string {
+ if len(folders) < 2 {
+ return ""
+ }
+ parentID := folders[0].ParentID
+ if parentID == "" || folderIDSet[parentID] {
+ return ""
+ }
+ for _, f := range folders[1:] {
+ if f.ParentID != parentID {
+ return ""
+ }
+ }
+ return parentID
+}
+
+// compareImageFiles compares two image file paths for sorting.
+// It extracts the base filename (without extension) and compares case-insensitively.
+// This ensures that "cover.jpg" sorts before "cover.1.jpg" since "cover" < "cover.1".
+// Note: This function is called O(n log n) times during sorting, but in practice albums
+// typically have only 1-20 image files, making the repeated string operations negligible.
+func compareImageFiles(a, b string) int {
+ // Case-insensitive comparison
+ a = strings.ToLower(a)
+ b = strings.ToLower(b)
+
+ // Extract base filenames without extensions
+ baseA := strings.TrimSuffix(filepath.Base(a), filepath.Ext(a))
+ baseB := strings.TrimSuffix(filepath.Base(b), filepath.Ext(b))
+
+ // Compare base names first, then full paths if equal
+ return cmp.Or(
+ natural.Compare(baseA, baseB),
+ natural.Compare(a, b),
+ )
+}
diff --git a/core/artwork/reader_album_test.go b/core/artwork/reader_album_test.go
index 2665632b9..a8a0eae3e 100644
--- a/core/artwork/reader_album_test.go
+++ b/core/artwork/reader_album_test.go
@@ -2,6 +2,7 @@ package artwork
import (
"context"
+ "errors"
"path/filepath"
"time"
@@ -27,26 +28,7 @@ var _ = Describe("Album Artwork Reader", func() {
expectedAt = now.Add(5 * time.Minute)
// Set up the test folders with image files
- repo = &fakeFolderRepo{
- result: []model.Folder{
- {
- Path: "Artist/Album/Disc1",
- ImagesUpdatedAt: expectedAt,
- ImageFiles: []string{"cover.jpg", "back.jpg"},
- },
- {
- Path: "Artist/Album/Disc2",
- ImagesUpdatedAt: now,
- ImageFiles: []string{"cover.jpg"},
- },
- {
- Path: "Artist/Album/Disc10",
- ImagesUpdatedAt: now,
- ImageFiles: []string{"cover.jpg"},
- },
- },
- err: nil,
- }
+ repo = &fakeFolderRepo{}
ds = &fakeDataStore{
folderRepo: repo,
}
@@ -58,19 +40,258 @@ var _ = Describe("Album Artwork Reader", func() {
})
It("returns sorted image files", func() {
+ repo.result = []model.Folder{
+ {
+ Path: "Artist/Album/Disc1",
+ ImagesUpdatedAt: expectedAt,
+ ImageFiles: []string{"cover.jpg", "back.jpg", "cover.1.jpg"},
+ },
+ {
+ Path: "Artist/Album/Disc2",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.jpg"},
+ },
+ {
+ Path: "Artist/Album/Disc10",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.jpg"},
+ },
+ }
+
_, imgFiles, imagesUpdatedAt, err := loadAlbumFoldersPaths(ctx, ds, album)
Expect(err).ToNot(HaveOccurred())
Expect(*imagesUpdatedAt).To(Equal(expectedAt))
- // Check that image files are sorted alphabetically
- Expect(imgFiles).To(HaveLen(4))
+ // Check that image files are sorted by base name (without extension)
+ Expect(imgFiles).To(HaveLen(5))
- // The files should be sorted by full path
+ // Files should be sorted by base filename without extension, then by full path
+ // "back" < "cover", so back.jpg comes first
+ // Then all cover.jpg files, sorted by path
Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist/Album/Disc1/back.jpg")))
Expect(imgFiles[1]).To(Equal(filepath.FromSlash("Artist/Album/Disc1/cover.jpg")))
- Expect(imgFiles[2]).To(Equal(filepath.FromSlash("Artist/Album/Disc10/cover.jpg")))
- Expect(imgFiles[3]).To(Equal(filepath.FromSlash("Artist/Album/Disc2/cover.jpg")))
+ Expect(imgFiles[2]).To(Equal(filepath.FromSlash("Artist/Album/Disc2/cover.jpg")))
+ Expect(imgFiles[3]).To(Equal(filepath.FromSlash("Artist/Album/Disc10/cover.jpg")))
+ Expect(imgFiles[4]).To(Equal(filepath.FromSlash("Artist/Album/Disc1/cover.1.jpg")))
+ })
+
+ It("prioritizes files without numeric suffixes", func() {
+ // Test case for issue #4683: cover.jpg should come before cover.1.jpg
+ repo.result = []model.Folder{
+ {
+ Path: "Artist/Album",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.1.jpg", "cover.jpg", "cover.2.jpg"},
+ },
+ }
+
+ _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgFiles).To(HaveLen(3))
+
+ // cover.jpg should come first because "cover" < "cover.1" < "cover.2"
+ Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist/Album/cover.jpg")))
+ Expect(imgFiles[1]).To(Equal(filepath.FromSlash("Artist/Album/cover.1.jpg")))
+ Expect(imgFiles[2]).To(Equal(filepath.FromSlash("Artist/Album/cover.2.jpg")))
+ })
+
+ It("handles case-insensitive sorting", func() {
+ // Test that Cover.jpg and cover.jpg are treated as equivalent
+ repo.result = []model.Folder{
+ {
+ Path: "Artist/Album",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"Folder.jpg", "cover.jpg", "BACK.jpg"},
+ },
+ }
+
+ _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgFiles).To(HaveLen(3))
+
+ // Files should be sorted case-insensitively: BACK, cover, Folder
+ Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist/Album/BACK.jpg")))
+ Expect(imgFiles[1]).To(Equal(filepath.FromSlash("Artist/Album/cover.jpg")))
+ Expect(imgFiles[2]).To(Equal(filepath.FromSlash("Artist/Album/Folder.jpg")))
+ })
+
+ It("includes images from parent folder for multi-disc albums", func() {
+ // Simulates: Artist/Album/cover.jpg with tracks in Artist/Album/CD1/ and Artist/Album/CD2/
+ repo.result = []model.Folder{
+ {
+ ID: "folder1",
+ Path: "Artist/Album",
+ Name: "CD1",
+ ParentID: "parentFolder",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{},
+ },
+ {
+ ID: "folder2",
+ Path: "Artist/Album",
+ Name: "CD2",
+ ParentID: "parentFolder",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{},
+ },
+ }
+ repo.parentResult = &model.Folder{
+ ID: "parentFolder",
+ Path: "Artist",
+ Name: "Album",
+ ImagesUpdatedAt: expectedAt,
+ ImageFiles: []string{"cover.jpg", "back.jpg"},
+ }
+
+ _, imgFiles, imagesUpdatedAt, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(*imagesUpdatedAt).To(Equal(expectedAt))
+ Expect(imgFiles).To(HaveLen(2))
+ Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist/Album/back.jpg")))
+ Expect(imgFiles[1]).To(Equal(filepath.FromSlash("Artist/Album/cover.jpg")))
+ })
+
+ It("does not query parent when parent ID is already in album folders", func() {
+ // When the parent folder is already one of the album's folders, skip it
+ repo.result = []model.Folder{
+ {
+ ID: "folder1",
+ Path: "Artist",
+ Name: "Album",
+ ParentID: "folder2",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.jpg"},
+ },
+ {
+ ID: "folder2",
+ Path: "",
+ Name: "Artist",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{},
+ },
+ }
+
+ _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgFiles).To(HaveLen(1))
+ Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist/Album/cover.jpg")))
+ // Get should not have been called (parent already in folder set)
+ Expect(repo.getCallCount).To(Equal(0))
+ })
+
+ It("does not query parent when folders have different parents", func() {
+ // When album folders span different parents, don't search any parent
+ repo.result = []model.Folder{
+ {
+ ID: "folder1",
+ Path: "Artist1/Album",
+ Name: "part1",
+ ParentID: "parentA",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.jpg"},
+ },
+ {
+ ID: "folder2",
+ Path: "Artist2/Album",
+ Name: "part2",
+ ParentID: "parentB",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{},
+ },
+ }
+
+ _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgFiles).To(HaveLen(1))
+ Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist1/Album/part1/cover.jpg")))
+ // Get should not have been called (different parents)
+ Expect(repo.getCallCount).To(Equal(0))
+ })
+
+ It("does not query parent for single-folder albums", func() {
+ // A single-folder album's parent is typically the artist folder,
+ // which should not be searched for cover art
+ repo.result = []model.Folder{
+ {
+ ID: "folder1",
+ Path: "Artist",
+ Name: "Album",
+ ParentID: "artistFolder",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.jpg"},
+ },
+ }
+
+ _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgFiles).To(HaveLen(1))
+ Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist/Album/cover.jpg")))
+ // Get should not have been called (single folder, no parent lookup)
+ Expect(repo.getCallCount).To(Equal(0))
+ })
+
+ It("propagates non-ErrNotFound errors from parent folder lookup", func() {
+ repo.result = []model.Folder{
+ {
+ ID: "folder1",
+ Path: "Artist/Album",
+ Name: "CD1",
+ ParentID: "parentFolder",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.jpg"},
+ },
+ {
+ ID: "folder2",
+ Path: "Artist/Album",
+ Name: "CD2",
+ ParentID: "parentFolder",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{},
+ },
+ }
+ repo.getErr = errors.New("db connection failed")
+
+ _, _, _, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).To(MatchError("db connection failed"))
+ Expect(repo.getCallCount).To(Equal(1))
+ })
+
+ It("continues gracefully when parent folder is not found", func() {
+ // Parent folder may have been deleted; should log a warning and continue
+ repo.result = []model.Folder{
+ {
+ ID: "folder1",
+ Path: "Artist/Album",
+ Name: "CD1",
+ ParentID: "missingParent",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{"cover.jpg"},
+ },
+ {
+ ID: "folder2",
+ Path: "Artist/Album",
+ Name: "CD2",
+ ParentID: "missingParent",
+ ImagesUpdatedAt: now,
+ ImageFiles: []string{},
+ },
+ }
+ // parentResult is nil, so Get will return ErrNotFound
+
+ _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgFiles).To(HaveLen(1))
+ Expect(imgFiles[0]).To(Equal(filepath.FromSlash("Artist/Album/CD1/cover.jpg")))
+ Expect(repo.getCallCount).To(Equal(1))
})
})
})
diff --git a/core/artwork/reader_artist.go b/core/artwork/reader_artist.go
index cb029a16e..96ba08b8f 100644
--- a/core/artwork/reader_artist.go
+++ b/core/artwork/reader_artist.go
@@ -8,6 +8,7 @@ import (
"io/fs"
"os"
"path/filepath"
+ "slices"
"strings"
"time"
@@ -28,11 +29,12 @@ const (
type artistReader struct {
cacheKey
- a *artwork
- provider external.Provider
- artist model.Artist
- artistFolder string
- imgFiles []string
+ a *artwork
+ provider external.Provider
+ artist model.Artist
+ artistFolder string
+ imgFiles []string
+ imgFolderImgPath string // cached path from ArtistImageFolder lookup
}
func newArtistArtworkReader(ctx context.Context, artwork *artwork, artID model.ArtworkID, provider external.Provider) (*artistReader, error) {
@@ -70,15 +72,26 @@ func newArtistArtworkReader(ctx context.Context, artwork *artwork, artID model.A
//a.cacheKey.lastUpdate = ar.ExternalInfoUpdatedAt
a.cacheKey.lastUpdate = *imagesUpdatedAt
+ if ar.UpdatedAt != nil && ar.UpdatedAt.After(a.cacheKey.lastUpdate) {
+ a.cacheKey.lastUpdate = *ar.UpdatedAt
+ }
if artistFolderLastUpdate.After(a.cacheKey.lastUpdate) {
a.cacheKey.lastUpdate = artistFolderLastUpdate
}
+ if conf.Server.ArtistImageFolder != "" && strings.Contains(strings.ToLower(conf.Server.ArtistArtPriority), "image-folder") {
+ a.imgFolderImgPath = findImageInArtistFolder(conf.Server.ArtistImageFolder, ar.MbzArtistID, ar.Name)
+ if a.imgFolderImgPath != "" {
+ if info, err := os.Stat(a.imgFolderImgPath); err == nil && info.ModTime().After(a.cacheKey.lastUpdate) {
+ a.cacheKey.lastUpdate = info.ModTime()
+ }
+ }
+ }
a.cacheKey.artID = artID
return a, nil
}
func (a *artistReader) Key() string {
- hash := md5.Sum([]byte(conf.Server.Agents + conf.Server.Spotify.ID))
+ hash := md5.Sum([]byte(conf.Server.Agents))
return fmt.Sprintf(
"%s.%t.%x",
a.cacheKey.Key(),
@@ -92,17 +105,24 @@ func (a *artistReader) LastUpdated() time.Time {
}
func (a *artistReader) Reader(ctx context.Context) (io.ReadCloser, string, error) {
- var ff = a.fromArtistArtPriority(ctx, conf.Server.ArtistArtPriority)
+ ff := []sourceFunc{a.fromArtistUploadedImage()}
+ ff = append(ff, a.fromArtistArtPriority(ctx, conf.Server.ArtistArtPriority)...)
return selectImageReader(ctx, a.artID, ff...)
}
+func (a *artistReader) fromArtistUploadedImage() sourceFunc {
+ return fromLocalFile(a.artist.UploadedImagePath())
+}
+
func (a *artistReader) fromArtistArtPriority(ctx context.Context, priority string) []sourceFunc {
var ff []sourceFunc
- for _, pattern := range strings.Split(strings.ToLower(priority), ",") {
+ for pattern := range strings.SplitSeq(strings.ToLower(priority), ",") {
pattern = strings.TrimSpace(pattern)
switch {
case pattern == "external":
ff = append(ff, fromArtistExternalSource(ctx, a.artist, a.provider))
+ case pattern == "image-folder":
+ ff = append(ff, a.fromArtistImageFolder(ctx))
case strings.HasPrefix(pattern, "album/"):
ff = append(ff, fromExternalFile(ctx, a.imgFiles, strings.TrimPrefix(pattern, "album/")))
default:
@@ -115,7 +135,7 @@ func (a *artistReader) fromArtistArtPriority(ctx context.Context, priority strin
func fromArtistFolder(ctx context.Context, artistFolder string, pattern string) sourceFunc {
return func() (io.ReadCloser, string, error) {
current := artistFolder
- for i := 0; i < maxArtistFolderTraversalDepth; i++ {
+ for range maxArtistFolderTraversalDepth {
if reader, path, err := findImageInFolder(ctx, current, pattern); err == nil {
return reader, path, nil
}
@@ -139,11 +159,22 @@ func findImageInFolder(ctx context.Context, folder, pattern string) (io.ReadClos
return nil, "", err
}
+ // Filter to valid image files
+ var imagePaths []string
for _, m := range matches {
if !model.IsImageFile(m) {
continue
}
- filePath := filepath.Join(folder, m)
+ imagePaths = append(imagePaths, m)
+ }
+
+ // Sort image files by prioritizing base filenames without numeric
+ // suffixes (e.g., artist.jpg before artist.1.jpg)
+ slices.SortFunc(imagePaths, compareImageFiles)
+
+ // Try to open files in sorted order
+ for _, p := range imagePaths {
+ filePath := filepath.Join(folder, p)
f, err := os.Open(filePath)
if err != nil {
log.Warn(ctx, "Could not open cover art file", "file", filePath, err)
@@ -184,3 +215,51 @@ func loadArtistFolder(ctx context.Context, ds model.DataStore, albums model.Albu
}
return folderPath, folders[0].ImagesUpdatedAt, nil
}
+
+func (a *artistReader) fromArtistImageFolder(ctx context.Context) sourceFunc {
+ return func() (io.ReadCloser, string, error) {
+ folder := conf.Server.ArtistImageFolder
+ if folder == "" {
+ return nil, "", nil
+ }
+ // Use cached path from newArtistArtworkReader if available,
+ // avoiding a second directory scan.
+ path := a.imgFolderImgPath
+ if path == "" {
+ path = findImageInArtistFolder(folder, a.artist.MbzArtistID, a.artist.Name)
+ }
+ if path == "" {
+ return nil, "", fmt.Errorf("no image found for artist %q in %s", a.artist.Name, folder)
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, "", err
+ }
+ return f, path, nil
+ }
+}
+
+// findImageInArtistFolder scans a folder for an image file matching the artist's MBID or name
+// (case-insensitive). Returns the full path, or empty string if not found.
+func findImageInArtistFolder(folder, mbzArtistID, artistName string) string {
+ entries, err := os.ReadDir(folder)
+ if err != nil {
+ return ""
+ }
+ for _, candidate := range []string{mbzArtistID, artistName} {
+ if candidate == "" {
+ continue
+ }
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ name := entry.Name()
+ base := strings.TrimSuffix(name, filepath.Ext(name))
+ if strings.EqualFold(base, candidate) && model.IsImageFile(name) {
+ return filepath.Join(folder, name)
+ }
+ }
+ }
+ return ""
+}
diff --git a/core/artwork/reader_artist_test.go b/core/artwork/reader_artist_test.go
index 527b0849f..5e2066aeb 100644
--- a/core/artwork/reader_artist_test.go
+++ b/core/artwork/reader_artist_test.go
@@ -8,6 +8,8 @@ import (
"path/filepath"
"time"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2"
@@ -240,24 +242,79 @@ var _ = Describe("artistArtworkReader", func() {
Expect(os.MkdirAll(artistDir, 0755)).To(Succeed())
// Create multiple matching files
- Expect(os.WriteFile(filepath.Join(artistDir, "artist.jpg"), []byte("jpg image"), 0600)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(artistDir, "artist.abc"), []byte("text file"), 0600)).To(Succeed())
Expect(os.WriteFile(filepath.Join(artistDir, "artist.png"), []byte("png image"), 0600)).To(Succeed())
- Expect(os.WriteFile(filepath.Join(artistDir, "artist.txt"), []byte("text file"), 0600)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(artistDir, "artist.jpg"), []byte("jpg image"), 0600)).To(Succeed())
testFunc = fromArtistFolder(ctx, artistDir, "artist.*")
})
- It("returns the first valid image file", func() {
+ It("returns the first valid image file in sorted order", func() {
reader, path, err := testFunc()
Expect(err).ToNot(HaveOccurred())
Expect(reader).ToNot(BeNil())
- // Should return an image file, not the text file
- Expect(path).To(SatisfyAny(
- ContainSubstring("artist.jpg"),
- ContainSubstring("artist.png"),
- ))
- Expect(path).ToNot(ContainSubstring("artist.txt"))
+ // Should return an image file,
+ // Files are sorted: jpg comes before png alphabetically.
+ // .abc comes first, but it's not an image.
+ Expect(path).To(ContainSubstring("artist.jpg"))
+ reader.Close()
+ })
+ })
+
+ When("prioritizing files without numeric suffixes", func() {
+ BeforeEach(func() {
+ // Test case for issue #4683: artist.jpg should come before artist.1.jpg
+ artistDir := filepath.Join(tempDir, "artist")
+ Expect(os.MkdirAll(artistDir, 0755)).To(Succeed())
+
+ // Create multiple matches with and without numeric suffixes
+ Expect(os.WriteFile(filepath.Join(artistDir, "artist.1.jpg"), []byte("artist 1"), 0600)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(artistDir, "artist.jpg"), []byte("artist main"), 0600)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(artistDir, "artist.2.jpg"), []byte("artist 2"), 0600)).To(Succeed())
+
+ testFunc = fromArtistFolder(ctx, artistDir, "artist.*")
+ })
+
+ It("returns artist.jpg before artist.1.jpg and artist.2.jpg", func() {
+ reader, path, err := testFunc()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(reader).ToNot(BeNil())
+ Expect(path).To(ContainSubstring("artist.jpg"))
+
+ // Verify it's the main file, not a numbered variant
+ data, err := io.ReadAll(reader)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("artist main"))
+ reader.Close()
+ })
+ })
+
+ When("handling case-insensitive sorting", func() {
+ BeforeEach(func() {
+ // Test case to ensure case-insensitive natural sorting
+ artistDir := filepath.Join(tempDir, "artist")
+ Expect(os.MkdirAll(artistDir, 0755)).To(Succeed())
+
+ // Create files with mixed case names
+ Expect(os.WriteFile(filepath.Join(artistDir, "Folder.jpg"), []byte("folder"), 0600)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(artistDir, "artist.jpg"), []byte("artist"), 0600)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(artistDir, "BACK.jpg"), []byte("back"), 0600)).To(Succeed())
+
+ testFunc = fromArtistFolder(ctx, artistDir, "*.*")
+ })
+
+ It("sorts case-insensitively", func() {
+ reader, path, err := testFunc()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(reader).ToNot(BeNil())
+
+ // Should return artist.jpg first (case-insensitive: "artist" < "back" < "folder")
+ Expect(path).To(ContainSubstring("artist.jpg"))
+
+ data, err := io.ReadAll(reader)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("artist"))
reader.Close()
})
})
@@ -358,18 +415,283 @@ var _ = Describe("artistArtworkReader", func() {
})
})
})
+
+ Describe("fromArtistUploadedImage", func() {
+ var (
+ tempDir string
+ reader *artistReader
+ )
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ tempDir = GinkgoT().TempDir()
+ conf.Server.DataFolder = tempDir
+
+ // Create the artwork/artist directory
+ Expect(os.MkdirAll(filepath.Join(tempDir, "artwork", "artist"), 0755)).To(Succeed())
+
+ reader = &artistReader{}
+ })
+
+ When("artist has an uploaded image", func() {
+ It("returns the uploaded image", func() {
+ imgPath := filepath.Join(tempDir, "artwork", "artist", "ar-1_test.jpg")
+ Expect(os.WriteFile(imgPath, []byte("uploaded artist image"), 0600)).To(Succeed())
+
+ reader.artist = model.Artist{ID: "ar-1", UploadedImage: "ar-1_test.jpg"}
+ sf := reader.fromArtistUploadedImage()
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+
+ data, err := io.ReadAll(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("uploaded artist image"))
+ r.Close()
+ })
+ })
+
+ When("artist has no uploaded image", func() {
+ It("returns nil reader (falls through)", func() {
+ reader.artist = model.Artist{ID: "ar-1"}
+ sf := reader.fromArtistUploadedImage()
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).To(BeNil())
+ Expect(path).To(BeEmpty())
+ })
+ })
+ })
+
+ Describe("fromArtistImageFolder", func() {
+ var (
+ ctx context.Context
+ tempDir string
+ ar *artistReader
+ )
+
+ BeforeEach(func() {
+ ctx = context.Background()
+ DeferCleanup(configtest.SetupConfig())
+ tempDir = GinkgoT().TempDir()
+ ar = &artistReader{}
+ })
+
+ When("ArtistImageFolder is not configured", func() {
+ It("returns nil (skips)", func() {
+ conf.Server.ArtistImageFolder = ""
+ ar.artist = model.Artist{Name: "Test Artist"}
+ sf := ar.fromArtistImageFolder(ctx)
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).To(BeNil())
+ Expect(path).To(BeEmpty())
+ })
+ })
+
+ When("image exists matching MBID", func() {
+ It("finds the image by MBID", func() {
+ conf.Server.ArtistImageFolder = tempDir
+ mbid := "f27ec8db-af05-4f36-916e-3d57f91ecf5e"
+ imgPath := filepath.Join(tempDir, mbid+".jpg")
+ Expect(os.WriteFile(imgPath, []byte("mbid image"), 0600)).To(Succeed())
+
+ ar.artist = model.Artist{Name: "Test Artist", MbzArtistID: mbid}
+ sf := ar.fromArtistImageFolder(ctx)
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+
+ data, err := io.ReadAll(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("mbid image"))
+ r.Close()
+ })
+ })
+
+ When("MBID match is case-insensitive", func() {
+ It("finds the image regardless of case", func() {
+ conf.Server.ArtistImageFolder = tempDir
+ mbid := "F27EC8DB-AF05-4F36-916E-3D57F91ECF5E"
+ imgPath := filepath.Join(tempDir, "f27ec8db-af05-4f36-916e-3d57f91ecf5e.png")
+ Expect(os.WriteFile(imgPath, []byte("mbid case image"), 0600)).To(Succeed())
+
+ ar.artist = model.Artist{Name: "Test Artist", MbzArtistID: mbid}
+ sf := ar.fromArtistImageFolder(ctx)
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+ r.Close()
+ })
+ })
+
+ When("no MBID file exists but artist name file does", func() {
+ It("falls back to artist name match", func() {
+ conf.Server.ArtistImageFolder = tempDir
+ imgPath := filepath.Join(tempDir, "Test Artist.jpg")
+ Expect(os.WriteFile(imgPath, []byte("name image"), 0600)).To(Succeed())
+
+ ar.artist = model.Artist{Name: "Test Artist", MbzArtistID: "nonexistent-mbid"}
+ sf := ar.fromArtistImageFolder(ctx)
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+
+ data, err := io.ReadAll(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("name image"))
+ r.Close()
+ })
+ })
+
+ When("artist name match is case-insensitive", func() {
+ It("matches regardless of case", func() {
+ conf.Server.ArtistImageFolder = tempDir
+ imgPath := filepath.Join(tempDir, "test artist.jpg")
+ Expect(os.WriteFile(imgPath, []byte("case insensitive"), 0600)).To(Succeed())
+
+ ar.artist = model.Artist{Name: "Test Artist"}
+ sf := ar.fromArtistImageFolder(ctx)
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+ r.Close()
+ })
+ })
+
+ When("both MBID and name files exist", func() {
+ It("prefers MBID over name match", func() {
+ conf.Server.ArtistImageFolder = tempDir
+ mbid := "f27ec8db-af05-4f36-916e-3d57f91ecf5e"
+ mbidPath := filepath.Join(tempDir, mbid+".jpg")
+ namePath := filepath.Join(tempDir, "Test Artist.jpg")
+ Expect(os.WriteFile(mbidPath, []byte("mbid image"), 0600)).To(Succeed())
+ Expect(os.WriteFile(namePath, []byte("name image"), 0600)).To(Succeed())
+
+ ar.artist = model.Artist{Name: "Test Artist", MbzArtistID: mbid}
+ sf := ar.fromArtistImageFolder(ctx)
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(mbidPath))
+
+ data, err := io.ReadAll(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("mbid image"))
+ r.Close()
+ })
+ })
+
+ When("no matching image found", func() {
+ It("returns an error", func() {
+ conf.Server.ArtistImageFolder = tempDir
+ // Create an unrelated file
+ Expect(os.WriteFile(filepath.Join(tempDir, "other.jpg"), []byte("other"), 0600)).To(Succeed())
+
+ ar.artist = model.Artist{Name: "Test Artist"}
+ sf := ar.fromArtistImageFolder(ctx)
+ r, _, err := sf()
+ Expect(err).To(HaveOccurred())
+ Expect(r).To(BeNil())
+ Expect(err.Error()).To(ContainSubstring("no image found"))
+ })
+ })
+
+ When("cached imgFolderImgPath is set", func() {
+ It("uses cached path instead of scanning", func() {
+ conf.Server.ArtistImageFolder = tempDir
+ imgPath := filepath.Join(tempDir, "cached.jpg")
+ Expect(os.WriteFile(imgPath, []byte("cached image"), 0600)).To(Succeed())
+
+ ar.artist = model.Artist{Name: "Test Artist"}
+ ar.imgFolderImgPath = imgPath
+ sf := ar.fromArtistImageFolder(ctx)
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+
+ data, err := io.ReadAll(r)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("cached image"))
+ r.Close()
+ })
+ })
+ })
+
+ Describe("findImageInArtistFolder", func() {
+ var tempDir string
+
+ BeforeEach(func() {
+ tempDir = GinkgoT().TempDir()
+ })
+
+ When("matching file exists by MBID", func() {
+ It("returns the file path", func() {
+ mbid := "f27ec8db-af05-4f36-916e-3d57f91ecf5e"
+ imgPath := filepath.Join(tempDir, mbid+".jpg")
+ Expect(os.WriteFile(imgPath, []byte("image"), 0600)).To(Succeed())
+
+ path := findImageInArtistFolder(tempDir, mbid, "Test")
+ Expect(path).To(Equal(imgPath))
+ })
+ })
+
+ When("matching file exists by name", func() {
+ It("returns the file path", func() {
+ imgPath := filepath.Join(tempDir, "Test Artist.png")
+ Expect(os.WriteFile(imgPath, []byte("image"), 0600)).To(Succeed())
+
+ path := findImageInArtistFolder(tempDir, "", "Test Artist")
+ Expect(path).To(Equal(imgPath))
+ })
+ })
+
+ When("no matching file exists", func() {
+ It("returns empty string", func() {
+ path := findImageInArtistFolder(tempDir, "", "Unknown Artist")
+ Expect(path).To(BeEmpty())
+ })
+ })
+
+ When("folder does not exist", func() {
+ It("returns empty string", func() {
+ path := findImageInArtistFolder("/nonexistent/path", "", "Test")
+ Expect(path).To(BeEmpty())
+ })
+ })
+ })
})
type fakeFolderRepo struct {
model.FolderRepository
- result []model.Folder
- err error
+ result []model.Folder
+ parentResult *model.Folder
+ getErr error
+ getCallCount int
+ err error
}
func (f *fakeFolderRepo) GetAll(...model.QueryOptions) ([]model.Folder, error) {
return f.result, f.err
}
+func (f *fakeFolderRepo) Get(id string) (*model.Folder, error) {
+ f.getCallCount++
+ if f.getErr != nil {
+ return nil, f.getErr
+ }
+ if f.parentResult != nil {
+ return f.parentResult, nil
+ }
+ return nil, model.ErrNotFound
+}
+
type fakeDataStore struct {
model.DataStore
folderRepo *fakeFolderRepo
diff --git a/core/artwork/reader_disc.go b/core/artwork/reader_disc.go
new file mode 100644
index 000000000..7548f76d2
--- /dev/null
+++ b/core/artwork/reader_disc.go
@@ -0,0 +1,268 @@
+package artwork
+
+import (
+ "context"
+ "crypto/md5"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+)
+
+type discArtworkReader struct {
+ cacheKey
+ a *artwork
+ album model.Album
+ discNumber int
+ imgFiles []string
+ discFolders map[string]bool
+ isMultiFolder bool
+ firstTrackPath string
+ updatedAt *time.Time
+}
+
+func newDiscArtworkReader(ctx context.Context, a *artwork, artID model.ArtworkID) (*discArtworkReader, error) {
+ albumID, discNumber, err := model.ParseDiscArtworkID(artID.ID)
+ if err != nil {
+ return nil, fmt.Errorf("invalid disc artwork id '%s': %w", artID.ID, err)
+ }
+
+ al, err := a.ds.Album(ctx).Get(albumID)
+ if err != nil {
+ return nil, err
+ }
+
+ _, imgFiles, imagesUpdatedAt, err := loadAlbumFoldersPaths(ctx, a.ds, *al)
+ if err != nil {
+ return nil, err
+ }
+
+ // Query mediafiles for this album + disc to find folder associations and first track
+ mfs, err := a.ds.MediaFile(ctx).GetAll(model.QueryOptions{
+ Sort: "track_number",
+ Order: "ASC",
+ Filters: squirrel.Eq{"album_id": albumID, "disc_number": discNumber},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // Build disc folder set and find first track
+ discFolders := make(map[string]bool)
+ var firstTrackPath string
+ allFolderIDs := make(map[string]bool)
+ for _, mf := range mfs {
+ allFolderIDs[mf.FolderID] = true
+ if firstTrackPath == "" {
+ firstTrackPath = mf.Path
+ }
+ }
+
+ // Resolve folder IDs to absolute paths
+ if len(allFolderIDs) > 0 {
+ folderIDs := make([]string, 0, len(allFolderIDs))
+ for id := range allFolderIDs {
+ folderIDs = append(folderIDs, id)
+ }
+ folders, err := a.ds.Folder(ctx).GetAll(model.QueryOptions{
+ Filters: squirrel.Eq{"folder.id": folderIDs},
+ })
+ if err != nil {
+ return nil, err
+ }
+ for _, f := range folders {
+ discFolders[f.AbsolutePath()] = true
+ }
+ }
+
+ isMultiFolder := len(al.FolderIDs) > 1
+
+ r := &discArtworkReader{
+ a: a,
+ album: *al,
+ discNumber: discNumber,
+ imgFiles: imgFiles,
+ discFolders: discFolders,
+ isMultiFolder: isMultiFolder,
+ firstTrackPath: core.AbsolutePath(ctx, a.ds, al.LibraryID, firstTrackPath),
+ updatedAt: imagesUpdatedAt,
+ }
+ r.cacheKey.artID = artID
+ if r.updatedAt != nil && r.updatedAt.After(al.UpdatedAt) {
+ r.cacheKey.lastUpdate = *r.updatedAt
+ } else {
+ r.cacheKey.lastUpdate = al.UpdatedAt
+ }
+ return r, nil
+}
+
+func (d *discArtworkReader) Key() string {
+ hash := md5.Sum([]byte(conf.Server.DiscArtPriority))
+ return fmt.Sprintf(
+ "%s.%x",
+ d.cacheKey.Key(),
+ hash,
+ )
+}
+
+func (d *discArtworkReader) LastUpdated() time.Time {
+ return d.album.UpdatedAt
+}
+
+func (d *discArtworkReader) Reader(ctx context.Context) (io.ReadCloser, string, error) {
+ var ff = d.fromDiscArtPriority(ctx, d.a.ffmpeg, conf.Server.DiscArtPriority)
+ // Fallback to album cover art
+ albumArtID := model.NewArtworkID(model.KindAlbumArtwork, d.album.ID, &d.album.UpdatedAt)
+ ff = append(ff, fromAlbum(ctx, d.a, albumArtID))
+ return selectImageReader(ctx, d.cacheKey.artID, ff...)
+}
+
+func (d *discArtworkReader) fromDiscArtPriority(ctx context.Context, ffmpeg ffmpeg.FFmpeg, priority string) []sourceFunc {
+ var ff []sourceFunc
+ for pattern := range strings.SplitSeq(strings.ToLower(priority), ",") {
+ pattern = strings.TrimSpace(pattern)
+ switch {
+ case pattern == "embedded":
+ ff = append(ff, fromTag(ctx, d.firstTrackPath), fromFFmpegTag(ctx, ffmpeg, d.firstTrackPath))
+ case pattern == "external":
+ // Not supported for disc art, silently ignore
+ case pattern == "discsubtitle":
+ if subtitle := strings.TrimSpace(d.album.Discs[d.discNumber]); subtitle != "" {
+ ff = append(ff, d.fromDiscSubtitle(ctx, subtitle))
+ }
+ case len(d.imgFiles) > 0:
+ ff = append(ff, d.fromExternalFile(ctx, pattern))
+ }
+ }
+ return ff
+}
+
+// fromDiscSubtitle returns a sourceFunc that matches image files whose stem
+// (filename without extension) equals the disc subtitle (case-insensitive).
+func (d *discArtworkReader) fromDiscSubtitle(ctx context.Context, subtitle string) sourceFunc {
+ return func() (io.ReadCloser, string, error) {
+ for _, file := range d.imgFiles {
+ _, name := filepath.Split(file)
+ stem := strings.TrimSuffix(name, filepath.Ext(name))
+ if !strings.EqualFold(stem, subtitle) {
+ continue
+ }
+ f, err := os.Open(file)
+ if err != nil {
+ log.Warn(ctx, "Could not open disc art file", "file", file, err)
+ continue
+ }
+ return f, file, nil
+ }
+ return nil, "", fmt.Errorf("disc %d: no image file matching subtitle %q", d.discNumber, subtitle)
+ }
+}
+
+// extractDiscNumber extracts a disc number from a filename based on a glob pattern.
+// It finds the portion of the filename that the wildcard matched and parses leading
+// digits as the disc number. Returns (0, false) if the pattern doesn't match or
+// no leading digits are found in the wildcard portion.
+func extractDiscNumber(pattern, filename string) (int, bool) {
+ filename = strings.ToLower(filename)
+ pattern = strings.ToLower(pattern)
+
+ matched, err := filepath.Match(pattern, filename)
+ if err != nil || !matched {
+ return 0, false
+ }
+
+ // Find the prefix before the first '*' in the pattern
+ starIdx := strings.IndexByte(pattern, '*')
+ if starIdx < 0 {
+ return 0, false
+ }
+ prefix := pattern[:starIdx]
+
+ // Strip the prefix from the filename to get the wildcard-matched portion
+ if !strings.HasPrefix(filename, prefix) {
+ return 0, false
+ }
+ remainder := filename[len(prefix):]
+
+ // Extract leading ASCII digits from the remainder
+ var digits []byte
+ for _, r := range remainder {
+ if r >= '0' && r <= '9' {
+ digits = append(digits, byte(r))
+ } else {
+ break
+ }
+ }
+
+ if len(digits) == 0 {
+ return 0, false
+ }
+
+ num, err := strconv.Atoi(string(digits))
+ if err != nil {
+ return 0, false
+ }
+ return num, true
+}
+
+// fromExternalFile returns a sourceFunc that matches image files against a glob
+// pattern with disc-number-aware filtering.
+//
+// Matching rules:
+// - If a disc number can be extracted from the filename, the file matches only if
+// the number equals the target disc number.
+// - If no number is found and this is a multi-folder album, the file matches if
+// it's in a folder containing tracks for this disc.
+// - If no number is found and this is a single-folder album, the file is skipped
+// (ambiguous).
+func (d *discArtworkReader) fromExternalFile(ctx context.Context, pattern string) sourceFunc {
+ return func() (io.ReadCloser, string, error) {
+ for _, file := range d.imgFiles {
+ _, name := filepath.Split(file)
+ match, err := filepath.Match(pattern, strings.ToLower(name))
+ if err != nil {
+ log.Warn(ctx, "Error matching disc art file to pattern", "pattern", pattern, "file", file)
+ continue
+ }
+ if !match {
+ continue
+ }
+
+ // Try to extract disc number from filename
+ num, hasNum := extractDiscNumber(pattern, name)
+ if hasNum {
+ // File has a disc number — must match target disc
+ if num != d.discNumber {
+ continue
+ }
+ } else if d.isMultiFolder {
+ // No number, multi-folder: match by folder association
+ dir := filepath.Dir(file)
+ if !d.discFolders[dir] {
+ continue
+ }
+ } else {
+ // No number, single-folder: ambiguous, skip
+ continue
+ }
+
+ f, err := os.Open(file)
+ if err != nil {
+ log.Warn(ctx, "Could not open disc art file", "file", file, err)
+ continue
+ }
+ return f, file, nil
+ }
+ return nil, "", fmt.Errorf("disc %d: pattern '%s' not matched by files", d.discNumber, pattern)
+ }
+}
diff --git a/core/artwork/reader_disc_test.go b/core/artwork/reader_disc_test.go
new file mode 100644
index 000000000..f8193e24e
--- /dev/null
+++ b/core/artwork/reader_disc_test.go
@@ -0,0 +1,285 @@
+package artwork
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+
+ "github.com/navidrome/navidrome/model"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Disc Artwork Reader", func() {
+ Describe("extractDiscNumber", func() {
+ DescribeTable("extracts disc number from filename based on glob pattern",
+ func(pattern, filename string, expectedNum int, expectedOk bool) {
+ num, ok := extractDiscNumber(pattern, filename)
+ Expect(ok).To(Equal(expectedOk))
+ if expectedOk {
+ Expect(num).To(Equal(expectedNum))
+ }
+ },
+ // Standard disc patterns
+ Entry("disc1.jpg", "disc*.*", "disc1.jpg", 1, true),
+ Entry("disc2.png", "disc*.*", "disc2.png", 2, true),
+ Entry("disc01.jpg", "disc*.*", "disc01.jpg", 1, true),
+ Entry("disc02.png", "disc*.*", "disc02.png", 2, true),
+ Entry("disc10.jpg", "disc*.*", "disc10.jpg", 10, true),
+
+ // CD patterns
+ Entry("cd1.jpg", "cd*.*", "cd1.jpg", 1, true),
+ Entry("cd02.png", "cd*.*", "cd02.png", 2, true),
+
+ // No number in filename
+ Entry("disc.jpg has no number", "disc*.*", "disc.jpg", 0, false),
+ Entry("cd.jpg has no number", "cd*.*", "cd.jpg", 0, false),
+
+ // Extra text after number
+ Entry("disc2-bonus.jpg", "disc*.*", "disc2-bonus.jpg", 2, true),
+ Entry("disc01_front.png", "disc*.*", "disc01_front.png", 1, true),
+
+ // Case insensitive (filename already lowered by caller)
+ Entry("Disc1.jpg lowered", "disc*.*", "disc1.jpg", 1, true),
+
+ // Pattern doesn't match
+ Entry("cover.jpg doesn't match disc*.*", "disc*.*", "cover.jpg", 0, false),
+
+ // Pattern with no wildcard before dot
+ Entry("front1.jpg with front*.*", "front*.*", "front1.jpg", 1, true),
+ )
+ })
+
+ Describe("fromExternalFile", func() {
+ var (
+ ctx context.Context
+ tmpDir string
+ )
+
+ BeforeEach(func() {
+ ctx = context.Background()
+ tmpDir = GinkgoT().TempDir()
+ })
+
+ createFile := func(path string) string {
+ fullPath := filepath.Join(tmpDir, filepath.FromSlash(path))
+ Expect(os.MkdirAll(filepath.Dir(fullPath), 0755)).To(Succeed())
+ Expect(os.WriteFile(fullPath, []byte("image data"), 0600)).To(Succeed())
+ return fullPath
+ }
+
+ It("matches file with disc number in single-folder album", func() {
+ f1 := createFile("album/disc1.jpg")
+ f2 := createFile("album/disc2.jpg")
+ reader := &discArtworkReader{
+ discNumber: 1,
+ imgFiles: []string{f1, f2},
+ discFolders: map[string]bool{filepath.Join(tmpDir, "album"): true},
+ }
+
+ sf := reader.fromExternalFile(ctx, "disc*.*")
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ r.Close()
+ Expect(path).To(Equal(f1))
+ })
+
+ It("skips file without number in single-folder album", func() {
+ f1 := createFile("album/disc.jpg")
+ reader := &discArtworkReader{
+ discNumber: 1,
+ imgFiles: []string{f1},
+ discFolders: map[string]bool{filepath.Join(tmpDir, "album"): true},
+ }
+
+ sf := reader.fromExternalFile(ctx, "disc*.*")
+ r, _, _ := sf()
+ Expect(r).To(BeNil())
+ })
+
+ It("matches file without number in multi-folder album by folder", func() {
+ f1 := createFile("album/cd1/disc.jpg")
+ f2 := createFile("album/cd2/disc.jpg")
+ reader := &discArtworkReader{
+ discNumber: 1,
+ imgFiles: []string{f1, f2},
+ discFolders: map[string]bool{filepath.Join(tmpDir, "album", "cd1"): true},
+ isMultiFolder: true,
+ }
+
+ sf := reader.fromExternalFile(ctx, "disc*.*")
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ r.Close()
+ Expect(path).To(Equal(f1))
+ })
+
+ It("prefers disc number over folder when number is present", func() {
+ // disc2.jpg in cd1 folder should match disc 2, not disc 1
+ f1 := createFile("album/cd1/disc2.jpg")
+ reader := &discArtworkReader{
+ discNumber: 2,
+ imgFiles: []string{f1},
+ discFolders: map[string]bool{filepath.Join(tmpDir, "album", "cd1"): true},
+ isMultiFolder: true,
+ }
+
+ sf := reader.fromExternalFile(ctx, "disc*.*")
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ r.Close()
+ Expect(path).To(Equal(f1))
+ })
+
+ It("does not match disc2.jpg when looking for disc 1", func() {
+ f1 := createFile("album/disc2.jpg")
+ reader := &discArtworkReader{
+ discNumber: 1,
+ imgFiles: []string{f1},
+ discFolders: map[string]bool{filepath.Join(tmpDir, "album"): true},
+ }
+
+ sf := reader.fromExternalFile(ctx, "disc*.*")
+ r, _, _ := sf()
+ Expect(r).To(BeNil())
+ })
+ })
+
+ Describe("fromDiscSubtitle", func() {
+ var (
+ ctx context.Context
+ tmpDir string
+ )
+
+ BeforeEach(func() {
+ ctx = context.Background()
+ tmpDir = GinkgoT().TempDir()
+ })
+
+ createFile := func(path string) string {
+ fullPath := filepath.Join(tmpDir, filepath.FromSlash(path))
+ Expect(os.MkdirAll(filepath.Dir(fullPath), 0755)).To(Succeed())
+ Expect(os.WriteFile(fullPath, []byte("image data"), 0600)).To(Succeed())
+ return fullPath
+ }
+
+ It("matches image file whose stem equals the disc subtitle (case-insensitive)", func() {
+ f1 := createFile("album/The Blue Disc.jpg")
+ reader := &discArtworkReader{
+ discNumber: 1,
+ imgFiles: []string{f1},
+ }
+
+ sf := reader.fromDiscSubtitle(ctx, "The Blue Disc")
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ r.Close()
+ Expect(path).To(Equal(f1))
+ })
+
+ It("matches case-insensitively", func() {
+ f1 := createFile("album/bonus tracks.png")
+ reader := &discArtworkReader{
+ discNumber: 2,
+ imgFiles: []string{f1},
+ }
+
+ sf := reader.fromDiscSubtitle(ctx, "Bonus Tracks")
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ r.Close()
+ Expect(path).To(Equal(f1))
+ })
+
+ It("returns error when no matching file found", func() {
+ f1 := createFile("album/cover.jpg")
+ reader := &discArtworkReader{
+ discNumber: 1,
+ imgFiles: []string{f1},
+ }
+
+ sf := reader.fromDiscSubtitle(ctx, "The Blue Disc")
+ _, _, err := sf()
+ Expect(err).To(HaveOccurred())
+ })
+
+ It("matches first file when multiple extensions exist", func() {
+ f1 := createFile("album/The Blue Disc.jpg")
+ f2 := createFile("album/The Blue Disc.png")
+ reader := &discArtworkReader{
+ discNumber: 1,
+ imgFiles: []string{f1, f2},
+ }
+
+ sf := reader.fromDiscSubtitle(ctx, "The Blue Disc")
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ r.Close()
+ Expect(path).To(Equal(f1))
+ })
+ })
+
+ Describe("discArtworkReader", func() {
+ Describe("fromDiscArtPriority", func() {
+ var reader *discArtworkReader
+
+ BeforeEach(func() {
+ reader = &discArtworkReader{
+ discNumber: 2,
+ isMultiFolder: true,
+ discFolders: map[string]bool{"/music/album/cd2": true},
+ imgFiles: []string{
+ "/music/album/cd1/disc.jpg",
+ "/music/album/cd2/disc.jpg",
+ "/music/album/cd2/disc2.jpg",
+ },
+ firstTrackPath: "/music/album/cd2/track1.flac",
+ }
+ })
+
+ It("returns source funcs for glob patterns", func() {
+ ff := reader.fromDiscArtPriority(context.Background(), nil, "disc*.*")
+ Expect(ff).To(HaveLen(1))
+ })
+
+ It("returns source funcs for embedded pattern", func() {
+ ff := reader.fromDiscArtPriority(context.Background(), nil, "embedded")
+ Expect(ff).To(HaveLen(2)) // fromTag + fromFFmpegTag
+ })
+
+ It("handles multiple comma-separated patterns", func() {
+ ff := reader.fromDiscArtPriority(context.Background(), nil, "disc*.*, cd*.*, embedded")
+ Expect(ff).To(HaveLen(4)) // disc*.* + cd*.* + fromTag + fromFFmpegTag
+ })
+
+ It("ignores 'external' pattern silently", func() {
+ ff := reader.fromDiscArtPriority(context.Background(), nil, "external")
+ Expect(ff).To(HaveLen(0))
+ })
+
+ It("returns no source funcs when imgFiles is empty and pattern is not embedded", func() {
+ reader.imgFiles = nil
+ ff := reader.fromDiscArtPriority(context.Background(), nil, "disc*.*")
+ Expect(ff).To(HaveLen(0))
+ })
+
+ It("returns source func for discsubtitle pattern", func() {
+ reader.album = model.Album{Discs: model.Discs{2: "Bonus Tracks"}}
+ ff := reader.fromDiscArtPriority(context.Background(), nil, "discsubtitle")
+ Expect(ff).To(HaveLen(1))
+ })
+
+ It("returns no source func for discsubtitle when disc has no subtitle", func() {
+ reader.album = model.Album{Discs: model.Discs{2: ""}}
+ ff := reader.fromDiscArtPriority(context.Background(), nil, "discsubtitle")
+ Expect(ff).To(HaveLen(0))
+ })
+ })
+ })
+})
diff --git a/core/artwork/reader_mediafile.go b/core/artwork/reader_mediafile.go
index c72d9543d..cf25c8f5d 100644
--- a/core/artwork/reader_mediafile.go
+++ b/core/artwork/reader_mediafile.go
@@ -26,16 +26,22 @@ func newMediafileArtworkReader(ctx context.Context, artwork *artwork, artID mode
if err != nil {
return nil, err
}
+ _, _, imagesUpdatedAt, err := loadAlbumFoldersPaths(ctx, artwork.ds, *al)
+ if err != nil {
+ return nil, err
+ }
a := &mediafileArtworkReader{
a: artwork,
mediafile: *mf,
album: *al,
}
a.cacheKey.artID = artID
- if al.UpdatedAt.After(mf.UpdatedAt) {
+ a.cacheKey.lastUpdate = mf.UpdatedAt
+ if al.UpdatedAt.After(a.cacheKey.lastUpdate) {
a.cacheKey.lastUpdate = al.UpdatedAt
- } else {
- a.cacheKey.lastUpdate = mf.UpdatedAt
+ }
+ if imagesUpdatedAt != nil && imagesUpdatedAt.After(a.cacheKey.lastUpdate) {
+ a.cacheKey.lastUpdate = *imagesUpdatedAt
}
return a, nil
}
@@ -60,6 +66,12 @@ func (a *mediafileArtworkReader) Reader(ctx context.Context) (io.ReadCloser, str
fromFFmpegTag(ctx, a.a.ffmpeg, path),
}
}
- ff = append(ff, fromAlbum(ctx, a.a, a.mediafile.AlbumCoverArtID()))
+ // For multi-disc albums, fall back to disc artwork first; for single-disc albums,
+ // skip disc resolution (it would just fall through to album art anyway).
+ if len(a.album.Discs) > 1 {
+ ff = append(ff, fromAlbum(ctx, a.a, a.mediafile.DiscCoverArtID()))
+ } else {
+ ff = append(ff, fromAlbum(ctx, a.a, a.mediafile.AlbumCoverArtID()))
+ }
return selectImageReader(ctx, a.artID, ff...)
}
diff --git a/core/artwork/reader_playlist.go b/core/artwork/reader_playlist.go
index a9f289ad8..09707843d 100644
--- a/core/artwork/reader_playlist.go
+++ b/core/artwork/reader_playlist.go
@@ -8,12 +8,17 @@ import (
"image/draw"
"image/png"
"io"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
"time"
- "github.com/disintegration/imaging"
+ "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/slice"
+ xdraw "golang.org/x/image/draw"
)
type playlistArtworkReader struct {
@@ -35,6 +40,24 @@ func newPlaylistArtworkReader(ctx context.Context, artwork *artwork, artID model
}
a.cacheKey.artID = artID
a.cacheKey.lastUpdate = pl.UpdatedAt
+
+ // Check sidecar and ExternalImageURL local file ModTimes for cache invalidation.
+ // If either is newer than the playlist's UpdatedAt, use that instead so the
+ // cache is busted when a user replaces a sidecar image or local file reference.
+ for _, path := range []string{
+ findPlaylistSidecarPath(ctx, pl.Path),
+ pl.ExternalImageURL,
+ } {
+ if path == "" || strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
+ continue
+ }
+ if info, err := os.Stat(path); err == nil {
+ if info.ModTime().After(a.cacheKey.lastUpdate) {
+ a.cacheKey.lastUpdate = info.ModTime()
+ }
+ }
+ }
+
return a, nil
}
@@ -43,11 +66,81 @@ func (a *playlistArtworkReader) LastUpdated() time.Time {
}
func (a *playlistArtworkReader) Reader(ctx context.Context) (io.ReadCloser, string, error) {
- ff := []sourceFunc{
+ return selectImageReader(ctx, a.artID,
+ a.fromPlaylistUploadedImage(),
+ a.fromPlaylistSidecar(ctx),
+ a.fromPlaylistExternalImage(ctx),
a.fromGeneratedTiledCover(ctx),
fromAlbumPlaceholder(),
+ )
+}
+
+func (a *playlistArtworkReader) fromPlaylistUploadedImage() sourceFunc {
+ return fromLocalFile(a.pl.UploadedImagePath())
+}
+
+func (a *playlistArtworkReader) fromPlaylistSidecar(ctx context.Context) sourceFunc {
+ return fromLocalFile(findPlaylistSidecarPath(ctx, a.pl.Path))
+}
+
+func (a *playlistArtworkReader) fromPlaylistExternalImage(ctx context.Context) sourceFunc {
+ return func() (io.ReadCloser, string, error) {
+ imgURL := a.pl.ExternalImageURL
+ if imgURL == "" {
+ return nil, "", nil
+ }
+ parsed, err := url.Parse(imgURL)
+ if err != nil {
+ return nil, "", err
+ }
+ if parsed.Scheme == "http" || parsed.Scheme == "https" {
+ if !conf.Server.EnableM3UExternalAlbumArt {
+ return nil, "", nil
+ }
+ return fromURL(ctx, parsed)
+ }
+ return fromLocalFile(imgURL)()
}
- return selectImageReader(ctx, a.artID, ff...)
+}
+
+// fromLocalFile returns a sourceFunc that opens the given local path.
+// Returns (nil, "", nil) if path is empty — signalling "not found, try next source".
+func fromLocalFile(path string) sourceFunc {
+ return func() (io.ReadCloser, string, error) {
+ if path == "" {
+ return nil, "", nil
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, "", err
+ }
+ return f, path, nil
+ }
+}
+
+// findPlaylistSidecarPath scans the directory of the playlist file for a sidecar
+// image file with the same base name (case-insensitive). Returns empty string if
+// no matching image is found or if plsPath is empty.
+func findPlaylistSidecarPath(ctx context.Context, plsPath string) string {
+ if plsPath == "" {
+ return ""
+ }
+ dir := filepath.Dir(plsPath)
+ base := strings.TrimSuffix(filepath.Base(plsPath), filepath.Ext(plsPath))
+
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ log.Warn(ctx, "Could not read directory for playlist sidecar", "dir", dir, err)
+ return ""
+ }
+ for _, entry := range entries {
+ name := entry.Name()
+ nameBase := strings.TrimSuffix(name, filepath.Ext(name))
+ if !entry.IsDir() && strings.EqualFold(nameBase, base) && model.IsImageFile(name) {
+ return filepath.Join(dir, name)
+ }
+ }
+ return ""
}
func (a *playlistArtworkReader) fromGeneratedTiledCover(ctx context.Context) sourceFunc {
@@ -107,7 +200,7 @@ func (a *playlistArtworkReader) createTile(_ context.Context, r io.ReadCloser) (
if err != nil {
return nil, err
}
- return imaging.Fill(img, tileSize/2, tileSize/2, imaging.Center, imaging.Lanczos), nil
+ return fillCenter(img, tileSize/2, tileSize/2), nil
}
func (a *playlistArtworkReader) createTiledImage(_ context.Context, tiles []image.Image) (io.ReadCloser, error) {
@@ -145,3 +238,32 @@ func rect(pos int) image.Rectangle {
r.Max.Y = r.Min.Y + tileSize/2
return r
}
+
+// fillCenter crops the source image from the center and scales it to fill dstW x dstH exactly,
+// equivalent to imaging.Fill with Center anchor.
+func fillCenter(src image.Image, dstW, dstH int) image.Image {
+ srcBounds := src.Bounds()
+ srcW := srcBounds.Dx()
+ srcH := srcBounds.Dy()
+
+ // Calculate crop rectangle (center crop to match destination aspect ratio)
+ srcAspect := float64(srcW) / float64(srcH)
+ dstAspect := float64(dstW) / float64(dstH)
+
+ var cropRect image.Rectangle
+ if srcAspect > dstAspect {
+ // Source is wider — crop horizontally
+ cropW := int(float64(srcH) * dstAspect)
+ cropX := (srcW - cropW) / 2
+ cropRect = image.Rect(srcBounds.Min.X+cropX, srcBounds.Min.Y, srcBounds.Min.X+cropX+cropW, srcBounds.Max.Y)
+ } else {
+ // Source is taller — crop vertically
+ cropH := int(float64(srcW) / dstAspect)
+ cropY := (srcH - cropH) / 2
+ cropRect = image.Rect(srcBounds.Min.X, srcBounds.Min.Y+cropY, srcBounds.Max.X, srcBounds.Min.Y+cropY+cropH)
+ }
+
+ dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+ xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, cropRect, draw.Src, nil)
+ return dst
+}
diff --git a/core/artwork/reader_radio.go b/core/artwork/reader_radio.go
new file mode 100644
index 000000000..22db6e302
--- /dev/null
+++ b/core/artwork/reader_radio.go
@@ -0,0 +1,40 @@
+package artwork
+
+import (
+ "context"
+ "io"
+ "time"
+
+ "github.com/navidrome/navidrome/model"
+)
+
+type radioArtworkReader struct {
+ cacheKey
+ a *artwork
+ radio model.Radio
+}
+
+func newRadioArtworkReader(ctx context.Context, artwork *artwork, artID model.ArtworkID) (*radioArtworkReader, error) {
+ r, err := artwork.ds.Radio(ctx).Get(artID.ID)
+ if err != nil {
+ return nil, err
+ }
+ a := &radioArtworkReader{a: artwork, radio: *r}
+ a.cacheKey.artID = artID
+ a.cacheKey.lastUpdate = r.UpdatedAt
+ return a, nil
+}
+
+func (a *radioArtworkReader) LastUpdated() time.Time {
+ return a.lastUpdate
+}
+
+func (a *radioArtworkReader) Reader(ctx context.Context) (io.ReadCloser, string, error) {
+ return selectImageReader(ctx, a.artID,
+ a.fromRadioUploadedImage(),
+ )
+}
+
+func (a *radioArtworkReader) fromRadioUploadedImage() sourceFunc {
+ return fromLocalFile(a.radio.UploadedImagePath())
+}
diff --git a/core/artwork/reader_radio_test.go b/core/artwork/reader_radio_test.go
new file mode 100644
index 000000000..1f5bc9084
--- /dev/null
+++ b/core/artwork/reader_radio_test.go
@@ -0,0 +1,84 @@
+package artwork
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/model"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("radioArtworkReader", func() {
+ var (
+ tempDir string
+ reader *radioArtworkReader
+ )
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ tempDir = GinkgoT().TempDir()
+ conf.Server.DataFolder = tempDir
+
+ Expect(os.MkdirAll(filepath.Join(tempDir, "artwork", "radio"), 0755)).To(Succeed())
+
+ reader = &radioArtworkReader{}
+ })
+
+ Describe("fromRadioUploadedImage", func() {
+ When("radio has an uploaded image", func() {
+ It("returns the uploaded image", func() {
+ imgPath := filepath.Join(tempDir, "artwork", "radio", "rd-1_test.jpg")
+ Expect(os.WriteFile(imgPath, []byte("uploaded radio image"), 0600)).To(Succeed())
+
+ reader.radio = model.Radio{ID: "rd-1", UploadedImage: "rd-1_test.jpg"}
+ sf := reader.fromRadioUploadedImage()
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ Expect(path).To(Equal(imgPath))
+ r.Close()
+ })
+ })
+
+ When("radio has no uploaded image", func() {
+ It("returns nil reader (falls through)", func() {
+ reader.radio = model.Radio{ID: "rd-1"}
+ sf := reader.fromRadioUploadedImage()
+ r, path, err := sf()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).To(BeNil())
+ Expect(path).To(BeEmpty())
+ })
+ })
+ })
+
+ Describe("Reader", func() {
+ When("radio has an uploaded image", func() {
+ It("returns the image reader", func() {
+ imgPath := filepath.Join(tempDir, "artwork", "radio", "rd-1_test.jpg")
+ Expect(os.WriteFile(imgPath, []byte("uploaded radio image"), 0600)).To(Succeed())
+
+ reader.radio = model.Radio{ID: "rd-1", UploadedImage: "rd-1_test.jpg"}
+ reader.cacheKey.artID = model.ArtworkID{Kind: model.KindRadioArtwork, ID: "rd-1"}
+ r, _, err := reader.Reader(context.Background())
+ Expect(err).ToNot(HaveOccurred())
+ Expect(r).ToNot(BeNil())
+ r.Close()
+ })
+ })
+
+ When("radio has no uploaded image", func() {
+ It("returns ErrUnavailable", func() {
+ reader.radio = model.Radio{ID: "rd-1"}
+ reader.cacheKey.artID = model.ArtworkID{Kind: model.KindRadioArtwork, ID: "rd-1"}
+ r, _, err := reader.Reader(context.Background())
+ Expect(err).To(MatchError(ErrUnavailable))
+ Expect(r).To(BeNil())
+ })
+ })
+ })
+})
diff --git a/core/artwork/reader_resized.go b/core/artwork/reader_resized.go
index 83e6e25c2..72baad434 100644
--- a/core/artwork/reader_resized.go
+++ b/core/artwork/reader_resized.go
@@ -5,17 +5,26 @@ import (
"context"
"fmt"
"image"
+ "image/draw"
"image/jpeg"
"image/png"
"io"
+ "sync"
"time"
- "github.com/disintegration/imaging"
+ "github.com/gen2brain/webp"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
+ xdraw "golang.org/x/image/draw"
)
+var bufPool = sync.Pool{
+ New: func() any {
+ return new(bytes.Buffer)
+ },
+}
+
type resizedArtworkReader struct {
artID model.ArtworkID
cacheKey string
@@ -46,7 +55,7 @@ func (a *resizedArtworkReader) Key() string {
if a.square {
return baseKey + ".square"
}
- return fmt.Sprintf("%s.%d", baseKey, conf.Server.CoverJpegQuality)
+ return fmt.Sprintf("%s.%d", baseKey, conf.Server.CoverArtQuality)
}
func (a *resizedArtworkReader) LastUpdated() time.Time {
@@ -61,7 +70,7 @@ func (a *resizedArtworkReader) Reader(ctx context.Context) (io.ReadCloser, strin
}
defer orig.Close()
- resized, origSize, err := resizeImage(orig, a.size, a.square)
+ resized, origSize, err := a.resizeImage(ctx, orig)
if resized == nil {
log.Trace(ctx, "Image smaller than requested size", "artID", a.artID, "original", origSize, "resized", a.size, "square", a.square)
} else {
@@ -75,11 +84,42 @@ func (a *resizedArtworkReader) Reader(ctx context.Context) (io.ReadCloser, strin
orig, _, err = a.a.Get(ctx, a.artID, 0, false)
return orig, "", err
}
+ // Preserve ReadCloser semantics if the resized reader already supports Close
+ // (e.g., ffmpeg pipe), otherwise wrap with NopCloser
+ if rc, ok := resized.(io.ReadCloser); ok {
+ return rc, fmt.Sprintf("%s@%d", a.artID, a.size), nil
+ }
return io.NopCloser(resized), fmt.Sprintf("%s@%d", a.artID, a.size), nil
}
-func resizeImage(reader io.Reader, size int, square bool) (io.Reader, int, error) {
- original, format, err := image.Decode(reader)
+func (a *resizedArtworkReader) resizeImage(ctx context.Context, reader io.Reader) (io.Reader, int, error) {
+ data, err := io.ReadAll(reader)
+ if err != nil {
+ return nil, 0, fmt.Errorf("reading image data: %w", err)
+ }
+
+ // Preserve animation for animated images (skip for square thumbnails)
+ if !a.square {
+ if isAnimatedGIF(data) {
+ if a.a.ffmpeg.IsAvailable() {
+ // Animated GIF: convert to animated WebP via ffmpeg (with optional resize)
+ r, err := a.a.ffmpeg.ConvertAnimatedImage(ctx, bytes.NewReader(data), a.size, conf.Server.CoverArtQuality)
+ if err == nil {
+ return r, 0, nil
+ }
+ log.Warn(ctx, "Could not convert animated GIF, falling back to static", err)
+ }
+ } else if isAnimatedWebP(data) || isAnimatedPNG(data) {
+ // Animated WebP/APNG: return original as-is (ffmpeg can't re-encode these)
+ return bytes.NewReader(data), 0, nil
+ }
+ }
+
+ return resizeStaticImage(data, a.size, a.square)
+}
+
+func resizeStaticImage(data []byte, size int, square bool) (io.Reader, int, error) {
+ original, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, 0, err
}
@@ -87,30 +127,54 @@ func resizeImage(reader io.Reader, size int, square bool) (io.Reader, int, error
bounds := original.Bounds()
originalSize := max(bounds.Max.X, bounds.Max.Y)
+ // Clamp size to original dimensions - upscaling wastes resources and adds no information
+ if size > originalSize {
+ size = originalSize
+ }
+
if originalSize <= size && !square {
return nil, originalSize, nil
}
- var resized image.Image
- if originalSize >= size {
- resized = imaging.Fit(original, size, size, imaging.Lanczos)
- } else {
- if bounds.Max.Y < bounds.Max.X {
- resized = imaging.Resize(original, size, 0, imaging.Lanczos)
- } else {
- resized = imaging.Resize(original, 0, size, imaging.Lanczos)
- }
- }
- if square {
- bg := image.NewRGBA(image.Rect(0, 0, size, size))
- resized = imaging.OverlayCenter(bg, resized, 1)
- }
+ // Calculate aspect-fit dimensions
+ srcW, srcH := bounds.Dx(), bounds.Dy()
+ scale := float64(size) / float64(max(srcW, srcH))
+ dstW := int(float64(srcW) * scale)
+ dstH := int(float64(srcH) * scale)
- buf := new(bytes.Buffer)
- if format == "png" || square {
- err = png.Encode(buf, resized)
+ var dst *image.NRGBA
+ var dstRect image.Rectangle
+ if square {
+ // Square canvas with image centered (transparent padding via zero-initialized NRGBA)
+ dst = image.NewNRGBA(image.Rect(0, 0, size, size))
+ offsetX := (size - dstW) / 2
+ offsetY := (size - dstH) / 2
+ dstRect = image.Rect(offsetX, offsetY, offsetX+dstW, offsetY+dstH)
} else {
- err = jpeg.Encode(buf, resized, &jpeg.Options{Quality: conf.Server.CoverJpegQuality})
+ // Tight-fit canvas
+ dst = image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
+ dstRect = dst.Bounds()
}
- return buf, originalSize, err
+ xdraw.CatmullRom.Scale(dst, dstRect, original, bounds, draw.Src, nil)
+
+ buf := bufPool.Get().(*bytes.Buffer)
+ buf.Reset()
+ if conf.Server.DevJpegCoverArt {
+ if square {
+ err = png.Encode(buf, dst)
+ } else {
+ err = jpeg.Encode(buf, dst, &jpeg.Options{Quality: conf.Server.CoverArtQuality})
+ }
+ } else {
+ err = webp.Encode(buf, dst, webp.Options{Quality: conf.Server.CoverArtQuality})
+ }
+ if err != nil {
+ bufPool.Put(buf)
+ return nil, originalSize, err
+ }
+ // Copy bytes before returning buffer to pool (pool may reuse the buffer)
+ encoded := make([]byte, buf.Len())
+ copy(encoded, buf.Bytes())
+ bufPool.Put(buf)
+ return bytes.NewReader(encoded), originalSize, nil
}
diff --git a/core/artwork/reader_resized_test.go b/core/artwork/reader_resized_test.go
new file mode 100644
index 000000000..7c9e21c0a
--- /dev/null
+++ b/core/artwork/reader_resized_test.go
@@ -0,0 +1,170 @@
+package artwork
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+
+ "github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("resizeImage", func() {
+ var mockFF *tests.MockFFmpeg
+ var r *resizedArtworkReader
+
+ BeforeEach(func() {
+ mockFF = tests.NewMockFFmpeg("converted-animated-data")
+ r = &resizedArtworkReader{
+ size: 300,
+ square: false,
+ a: &artwork{ffmpeg: mockFF},
+ }
+ })
+
+ Describe("animated GIF handling", func() {
+ It("converts animated GIF via ffmpeg when available", func() {
+ data := createAnimatedGIF(3)
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result).ToNot(BeNil())
+
+ // Should have been processed by ffmpeg (mock returns "converted-animated-data")
+ output, err := io.ReadAll(result)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(output).To(Equal(data)) // MockFFmpeg echoes input back
+ })
+
+ It("falls back to static resize when ffmpeg fails for animated GIF", func() {
+ mockFF.Error = errors.New("ffmpeg failed")
+ // Use size smaller than image so static resize actually produces output
+ r.size = 1
+ data := createAnimatedGIF(3)
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ // Should fall through to static resize successfully (no ffmpeg error propagated)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result).ToNot(BeNil())
+
+ // Verify it's a static image (WebP encoded), not the ffmpeg error
+ output, err := io.ReadAll(result)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(len(output)).To(BeNumerically(">", 0))
+ })
+
+ It("skips animation for square thumbnails even with animated GIF", func() {
+ r.square = true
+ data := createAnimatedGIF(3)
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ // Should fall through to static resize (not ffmpeg conversion)
+ // The minimal test GIF may or may not resize successfully,
+ // but ffmpeg should NOT have been called for animated conversion
+ _ = result
+ _ = err
+ // Verify by checking the mock wasn't used for animated conversion:
+ // If ffmpeg was called, it would return mock data, not static resize result
+ })
+ })
+
+ Describe("animated WebP handling", func() {
+ It("returns animated WebP data as-is when not square", func() {
+ data := createAnimatedWebPBytes()
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result).ToNot(BeNil())
+
+ // Should return original data unchanged
+ output, err := io.ReadAll(result)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(output).To(Equal(data))
+ })
+
+ It("does not passthrough animated WebP for square thumbnails", func() {
+ r.square = true
+ data := createAnimatedWebPBytes()
+ // Should fall through to static resize, which will fail on fake WebP data
+ _, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ // Static decode will fail on our minimal test WebP bytes (not a real image)
+ Expect(err).To(HaveOccurred())
+ })
+ })
+
+ Describe("animated PNG handling", func() {
+ It("returns animated PNG data as-is when not square", func() {
+ data := createAPNGBytes()
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result).ToNot(BeNil())
+
+ // Should return original data unchanged
+ output, err := io.ReadAll(result)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(output).To(Equal(data))
+ })
+
+ It("does not passthrough animated PNG for square thumbnails", func() {
+ r.square = true
+ data := createAPNGBytes()
+ // Should fall through to static resize
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ // Static PNG decode should succeed on our APNG (it's a valid PNG)
+ if err == nil {
+ Expect(result).ToNot(BeNil())
+ }
+ })
+ })
+
+ Describe("static image handling", func() {
+ It("resizes a static PNG normally", func() {
+ data := createStaticPNGBytes()
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ // Static PNG is 2x2, size 300 is larger, so should return nil (no upscale)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result).To(BeNil())
+ })
+ })
+
+ Describe("ReadCloser preservation", func() {
+ It("preserves Close semantics from ffmpeg ReadCloser", func() {
+ // Create a trackable ReadCloser
+ tracker := &closeTracker{Reader: bytes.NewReader([]byte("test data"))}
+ mockFF2 := &mockFFmpegWithCloser{tracker: tracker}
+ r.a = &artwork{ffmpeg: mockFF2}
+
+ data := createAnimatedGIF(3)
+ result, _, err := r.resizeImage(context.Background(), bytes.NewReader(data))
+ Expect(err).ToNot(HaveOccurred())
+
+ // The result should be an io.ReadCloser (the tracker)
+ rc, ok := result.(io.ReadCloser)
+ Expect(ok).To(BeTrue())
+ Expect(rc.Close()).ToNot(HaveOccurred())
+ Expect(tracker.closed).To(BeTrue())
+ })
+ })
+})
+
+// closeTracker is an io.ReadCloser that tracks whether Close was called.
+type closeTracker struct {
+ io.Reader
+ closed bool
+}
+
+func (c *closeTracker) Close() error {
+ c.closed = true
+ return nil
+}
+
+// mockFFmpegWithCloser is a minimal FFmpeg mock that returns a specific ReadCloser
+// for ConvertAnimatedImage, allowing us to verify Close propagation.
+type mockFFmpegWithCloser struct {
+ ffmpeg.FFmpeg
+ tracker *closeTracker
+}
+
+func (m *mockFFmpegWithCloser) IsAvailable() bool { return true }
+func (m *mockFFmpegWithCloser) ConvertAnimatedImage(_ context.Context, _ io.Reader, _ int, _ int) (io.ReadCloser, error) {
+ return m.tracker, nil
+}
diff --git a/core/artwork/sources.go b/core/artwork/sources.go
index 4250a373b..0628461e0 100644
--- a/core/artwork/sources.go
+++ b/core/artwork/sources.go
@@ -15,13 +15,13 @@ import (
"strings"
"time"
- "github.com/dhowden/tag"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/ffmpeg"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/resources"
+ "go.senan.xyz/taglib"
)
func selectImageReader(ctx context.Context, artID model.ArtworkID, extractFuncs ...sourceFunc) (io.ReadCloser, string, error) {
@@ -88,46 +88,39 @@ func fromTag(ctx context.Context, path string) sourceFunc {
if path == "" {
return nil, "", nil
}
- f, err := os.Open(path)
+ f, err := taglib.OpenReadOnly(path, taglib.WithReadStyle(taglib.ReadStyleFast))
if err != nil {
return nil, "", err
}
defer f.Close()
- m, err := tag.ReadFrom(f)
- if err != nil {
- return nil, "", err
- }
-
- types := m.PictureTypes()
- if len(types) == 0 {
+ images := f.Properties().Images
+ if len(images) == 0 {
return nil, "", fmt.Errorf("no embedded image found in %s", path)
}
- var picture *tag.Picture
- for _, regex := range picTypeRegexes {
- for _, t := range types {
- if regex.MatchString(t) {
- log.Trace(ctx, "Found embedded image", "type", t, "path", path)
- picture = m.Pictures(t)
- break
- }
- }
- if picture != nil {
- break
- }
- }
- if picture == nil {
- log.Trace(ctx, "Could not find a front image. Getting the first one", "type", types[0], "path", path)
- picture = m.Picture()
- }
- if picture == nil {
+ imageIndex := findBestImageIndex(ctx, images, path)
+ data, err := f.Image(imageIndex)
+ if err != nil || len(data) == 0 {
return nil, "", fmt.Errorf("could not load embedded image from %s", path)
}
- return io.NopCloser(bytes.NewReader(picture.Data)), path, nil
+ return io.NopCloser(bytes.NewReader(data)), path, nil
}
}
+func findBestImageIndex(ctx context.Context, images []taglib.ImageDesc, path string) int {
+ for _, regex := range picTypeRegexes {
+ for i, img := range images {
+ if regex.MatchString(img.Type) {
+ log.Trace(ctx, "Found embedded image", "type", img.Type, "path", path)
+ return i
+ }
+ }
+ }
+ log.Trace(ctx, "Could not find a front image. Getting the first one", "type", images[0].Type, "path", path)
+ return 0
+}
+
func fromFFmpegTag(ctx context.Context, ffmpeg ffmpeg.FFmpeg, path string) sourceFunc {
return func() (io.ReadCloser, string, error) {
if path == "" {
@@ -182,7 +175,8 @@ func fromAlbumExternalSource(ctx context.Context, al model.Album, provider exter
func fromURL(ctx context.Context, imageUrl *url.URL) (io.ReadCloser, string, error) {
hc := http.Client{Timeout: 5 * time.Second}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, imageUrl.String(), nil)
- resp, err := hc.Do(req)
+ req.Header.Set("User-Agent", consts.HTTPUserAgent)
+ resp, err := hc.Do(req) //nolint:gosec
if err != nil {
return nil, "", err
}
diff --git a/core/auth/auth.go b/core/auth/auth.go
index fd2b670a4..a75111b35 100644
--- a/core/auth/auth.go
+++ b/core/auth/auth.go
@@ -8,7 +8,7 @@ import (
"time"
"github.com/go-chi/jwtauth/v5"
- "github.com/lestrrat-go/jwx/v2/jwt"
+ "github.com/lestrrat-go/jwx/v3/jwt"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
@@ -45,42 +45,30 @@ func Init(ds model.DataStore) {
})
}
-func createBaseClaims() map[string]any {
- tokenClaims := map[string]any{}
- tokenClaims[jwt.IssuerKey] = consts.JWTIssuer
- return tokenClaims
-}
-
-func CreatePublicToken(claims map[string]any) (string, error) {
- tokenClaims := createBaseClaims()
- for k, v := range claims {
- tokenClaims[k] = v
- }
- _, token, err := TokenAuth.Encode(tokenClaims)
-
+func CreatePublicToken(claims Claims) (string, error) {
+ claims.Issuer = consts.JWTIssuer
+ _, token, err := TokenAuth.Encode(claims.ToMap())
return token, err
}
-func CreateExpiringPublicToken(exp time.Time, claims map[string]any) (string, error) {
- tokenClaims := createBaseClaims()
+func CreateExpiringPublicToken(exp time.Time, claims Claims) (string, error) {
+ claims.Issuer = consts.JWTIssuer
if !exp.IsZero() {
- tokenClaims[jwt.ExpirationKey] = exp.UTC().Unix()
+ claims.ExpiresAt = exp
}
- for k, v := range claims {
- tokenClaims[k] = v
- }
- _, token, err := TokenAuth.Encode(tokenClaims)
-
+ _, token, err := TokenAuth.Encode(claims.ToMap())
return token, err
}
func CreateToken(u *model.User) (string, error) {
- claims := createBaseClaims()
- claims[jwt.SubjectKey] = u.UserName
- claims[jwt.IssuedAtKey] = time.Now().UTC().Unix()
- claims["uid"] = u.ID
- claims["adm"] = u.IsAdmin
- token, _, err := TokenAuth.Encode(claims)
+ claims := Claims{
+ Issuer: consts.JWTIssuer,
+ Subject: u.UserName,
+ IssuedAt: time.Now(),
+ UserID: u.ID,
+ IsAdmin: u.IsAdmin,
+ }
+ token, _, err := TokenAuth.Encode(claims.ToMap())
if err != nil {
return "", err
}
@@ -89,23 +77,18 @@ func CreateToken(u *model.User) (string, error) {
}
func TouchToken(token jwt.Token) (string, error) {
- claims, err := token.AsMap(context.Background())
- if err != nil {
- return "", err
- }
-
- claims[jwt.ExpirationKey] = time.Now().UTC().Add(conf.Server.SessionTimeout).Unix()
- _, newToken, err := TokenAuth.Encode(claims)
-
+ claims := ClaimsFromToken(token).
+ WithExpiresAt(time.Now().UTC().Add(conf.Server.SessionTimeout))
+ _, newToken, err := TokenAuth.Encode(claims.ToMap())
return newToken, err
}
-func Validate(tokenStr string) (map[string]interface{}, error) {
+func Validate(tokenStr string) (Claims, error) {
token, err := jwtauth.VerifyToken(TokenAuth, tokenStr)
if err != nil {
- return nil, err
+ return Claims{}, err
}
- return token.AsMap(context.Background())
+ return ClaimsFromToken(token), nil
}
func WithAdminUser(ctx context.Context, ds model.DataStore) context.Context {
@@ -113,9 +96,9 @@ func WithAdminUser(ctx context.Context, ds model.DataStore) context.Context {
if err != nil {
c, err := ds.User(ctx).CountAll()
if c == 0 && err == nil {
- log.Debug(ctx, "Scanner: No admin user yet!", err)
+ log.Debug(ctx, "No admin user yet!", err)
} else {
- log.Error(ctx, "Scanner: No admin user found!", err)
+ log.Error(ctx, "No admin user found!", err)
}
u = &model.User{}
}
@@ -137,6 +120,19 @@ func createNewSecret(ctx context.Context, ds model.DataStore) string {
return secret
}
+// EncodeToken creates a signed JWT from an arbitrary claims map.
+// It sets the issuer claim automatically.
+func EncodeToken(claims map[string]any) (string, error) {
+ claims[jwt.IssuerKey] = consts.JWTIssuer
+ _, token, err := TokenAuth.Encode(claims)
+ return token, err
+}
+
+// DecodeAndVerifyToken verifies a JWT string and returns the parsed token.
+func DecodeAndVerifyToken(tokenStr string) (jwt.Token, error) {
+ return jwtauth.VerifyToken(TokenAuth, tokenStr)
+}
+
func getEncKey() []byte {
key := cmp.Or(
conf.Server.PasswordEncryptionKey,
diff --git a/core/auth/auth_test.go b/core/auth/auth_test.go
index 504e56a52..761dd205c 100644
--- a/core/auth/auth_test.go
+++ b/core/auth/auth_test.go
@@ -45,7 +45,7 @@ var _ = Describe("Auth", func() {
})
It("returns the claims from a valid JWT token", func() {
- claims := map[string]interface{}{}
+ claims := map[string]any{}
claims["iss"] = "issuer"
claims["iat"] = time.Now().Unix()
claims["exp"] = time.Now().Add(1 * time.Minute).Unix()
@@ -54,11 +54,11 @@ var _ = Describe("Auth", func() {
decodedClaims, err := auth.Validate(tokenStr)
Expect(err).NotTo(HaveOccurred())
- Expect(decodedClaims["iss"]).To(Equal("issuer"))
+ Expect(decodedClaims.Issuer).To(Equal("issuer"))
})
It("returns ErrExpired if the `exp` field is in the past", func() {
- claims := map[string]interface{}{}
+ claims := map[string]any{}
claims["iss"] = "issuer"
claims["exp"] = time.Now().Add(-1 * time.Minute).Unix()
_, tokenStr, err := auth.TokenAuth.Encode(claims)
@@ -82,18 +82,18 @@ var _ = Describe("Auth", func() {
claims, err := auth.Validate(tokenStr)
Expect(err).NotTo(HaveOccurred())
- Expect(claims["iss"]).To(Equal(consts.JWTIssuer))
- Expect(claims["sub"]).To(Equal("johndoe"))
- Expect(claims["uid"]).To(Equal("123"))
- Expect(claims["adm"]).To(Equal(true))
- Expect(claims["exp"]).To(BeTemporally(">", time.Now()))
+ Expect(claims.Issuer).To(Equal(consts.JWTIssuer))
+ Expect(claims.Subject).To(Equal("johndoe"))
+ Expect(claims.UserID).To(Equal("123"))
+ Expect(claims.IsAdmin).To(Equal(true))
+ Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now()))
})
})
Describe("TouchToken", func() {
It("updates the expiration time", func() {
yesterday := time.Now().Add(-oneDay)
- claims := map[string]interface{}{}
+ claims := map[string]any{}
claims["iss"] = "issuer"
claims["exp"] = yesterday.Unix()
token, _, err := auth.TokenAuth.Encode(claims)
@@ -104,8 +104,7 @@ var _ = Describe("Auth", func() {
decodedClaims, err := auth.Validate(touched)
Expect(err).NotTo(HaveOccurred())
- exp := decodedClaims["exp"].(time.Time)
- Expect(exp.Sub(yesterday)).To(BeNumerically(">=", oneDay))
+ Expect(decodedClaims.ExpiresAt.Sub(yesterday)).To(BeNumerically(">=", oneDay))
})
})
})
diff --git a/core/auth/claims.go b/core/auth/claims.go
new file mode 100644
index 000000000..c0e4dea7f
--- /dev/null
+++ b/core/auth/claims.go
@@ -0,0 +1,96 @@
+package auth
+
+import (
+ "time"
+
+ "github.com/lestrrat-go/jwx/v3/jwt"
+)
+
+// Claims represents the typed JWT claims used throughout Navidrome,
+// replacing the untyped map[string]any approach.
+type Claims struct {
+ // Standard JWT claims
+ Issuer string
+ Subject string // username for session tokens
+ IssuedAt time.Time
+ ExpiresAt time.Time
+
+ // Custom claims
+ UserID string // "uid"
+ IsAdmin bool // "adm"
+ ID string // "id" - artwork/mediafile ID
+ Format string // "f" - audio format
+ BitRate int // "b" - audio bitrate
+}
+
+// ToMap converts Claims to a map[string]any for use with TokenAuth.Encode().
+// Only non-zero fields are included.
+func (c Claims) ToMap() map[string]any {
+ m := make(map[string]any)
+ if c.Issuer != "" {
+ m[jwt.IssuerKey] = c.Issuer
+ }
+ if c.Subject != "" {
+ m[jwt.SubjectKey] = c.Subject
+ }
+ if !c.IssuedAt.IsZero() {
+ m[jwt.IssuedAtKey] = c.IssuedAt.UTC().Unix()
+ }
+ if !c.ExpiresAt.IsZero() {
+ m[jwt.ExpirationKey] = c.ExpiresAt.UTC().Unix()
+ }
+ if c.UserID != "" {
+ m["uid"] = c.UserID
+ }
+ if c.IsAdmin {
+ m["adm"] = c.IsAdmin
+ }
+ if c.ID != "" {
+ m["id"] = c.ID
+ }
+ if c.Format != "" {
+ m["f"] = c.Format
+ }
+ if c.BitRate != 0 {
+ m["b"] = c.BitRate
+ }
+ return m
+}
+
+func (c Claims) WithExpiresAt(t time.Time) Claims {
+ c.ExpiresAt = t
+ return c
+}
+
+// ClaimsFromToken extracts Claims directly from a jwt.Token using token.Get().
+func ClaimsFromToken(token jwt.Token) Claims {
+ var c Claims
+ c.Issuer, _ = token.Issuer()
+ c.Subject, _ = token.Subject()
+ c.IssuedAt, _ = token.IssuedAt()
+ c.ExpiresAt, _ = token.Expiration()
+
+ var uid string
+ if err := token.Get("uid", &uid); err == nil {
+ c.UserID = uid
+ }
+ var adm bool
+ if err := token.Get("adm", &adm); err == nil {
+ c.IsAdmin = adm
+ }
+ var id string
+ if err := token.Get("id", &id); err == nil {
+ c.ID = id
+ }
+ var f string
+ if err := token.Get("f", &f); err == nil {
+ c.Format = f
+ }
+ if err := token.Get("b", &c.BitRate); err != nil {
+ var bf float64
+ if err := token.Get("b", &bf); err == nil {
+ c.BitRate = int(bf)
+ }
+ }
+ return c
+}
diff --git a/core/auth/claims_test.go b/core/auth/claims_test.go
new file mode 100644
index 000000000..cf6b07263
--- /dev/null
+++ b/core/auth/claims_test.go
@@ -0,0 +1,99 @@
+package auth_test
+
+import (
+ "time"
+
+ "github.com/go-chi/jwtauth/v5"
+ "github.com/navidrome/navidrome/core/auth"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Claims", func() {
+ Describe("ToMap", func() {
+ It("includes only non-zero fields", func() {
+ c := auth.Claims{
+ Issuer: "ND",
+ Subject: "johndoe",
+ UserID: "123",
+ IsAdmin: true,
+ }
+ m := c.ToMap()
+ Expect(m).To(HaveKeyWithValue("iss", "ND"))
+ Expect(m).To(HaveKeyWithValue("sub", "johndoe"))
+ Expect(m).To(HaveKeyWithValue("uid", "123"))
+ Expect(m).To(HaveKeyWithValue("adm", true))
+ Expect(m).NotTo(HaveKey("exp"))
+ Expect(m).NotTo(HaveKey("iat"))
+ Expect(m).NotTo(HaveKey("id"))
+ Expect(m).NotTo(HaveKey("f"))
+ Expect(m).NotTo(HaveKey("b"))
+ })
+
+ It("includes expiration and issued-at when set", func() {
+ now := time.Now()
+ c := auth.Claims{
+ IssuedAt: now,
+ ExpiresAt: now.Add(time.Hour),
+ }
+ m := c.ToMap()
+ Expect(m).To(HaveKey("iat"))
+ Expect(m).To(HaveKey("exp"))
+ })
+
+ It("includes custom claims for public tokens", func() {
+ c := auth.Claims{
+ ID: "al-123",
+ Format: "mp3",
+ BitRate: 192,
+ }
+ m := c.ToMap()
+ Expect(m).To(HaveKeyWithValue("id", "al-123"))
+ Expect(m).To(HaveKeyWithValue("f", "mp3"))
+ Expect(m).To(HaveKeyWithValue("b", 192))
+ })
+ })
+
+ Describe("ClaimsFromToken", func() {
+ It("round-trips session claims through encode/decode", func() {
+ tokenAuth := jwtauth.New("HS256", []byte("test-secret"), nil)
+ now := time.Now().Truncate(time.Second)
+ original := auth.Claims{
+ Issuer: "ND",
+ Subject: "johndoe",
+ UserID: "123",
+ IsAdmin: true,
+ }
+ m := original.ToMap()
+ m["iat"] = now.UTC().Unix()
+ token, _, err := tokenAuth.Encode(m)
+ Expect(err).NotTo(HaveOccurred())
+
+ c := auth.ClaimsFromToken(token)
+ Expect(c.Issuer).To(Equal("ND"))
+ Expect(c.Subject).To(Equal("johndoe"))
+ Expect(c.UserID).To(Equal("123"))
+ Expect(c.IsAdmin).To(BeTrue())
+ Expect(c.IssuedAt.UTC()).To(Equal(now.UTC()))
+ })
+
+ It("round-trips public token claims through encode/decode", func() {
+ tokenAuth := jwtauth.New("HS256", []byte("test-secret"), nil)
+ original := auth.Claims{
+ Issuer: "ND",
+ ID: "al-456",
+ Format: "opus",
+ BitRate: 128,
+ }
+ token, _, err := tokenAuth.Encode(original.ToMap())
+ Expect(err).NotTo(HaveOccurred())
+
+ c := auth.ClaimsFromToken(token)
+ Expect(c.Issuer).To(Equal("ND"))
+ Expect(c.ID).To(Equal("al-456"))
+ Expect(c.Format).To(Equal("opus"))
+ Expect(c.BitRate).To(Equal(128))
+ })
+ })
+
+})
diff --git a/core/external/extdata_helper_test.go b/core/external/extdata_helper_test.go
index 29975e5c5..8fabf4490 100644
--- a/core/external/extdata_helper_test.go
+++ b/core/external/extdata_helper_test.go
@@ -40,7 +40,7 @@ func (m *mockArtistRepo) Get(id string) (*model.Artist, error) {
// GetAll implements model.ArtistRepository.
func (m *mockArtistRepo) GetAll(options ...model.QueryOptions) (model.Artists, error) {
- argsSlice := make([]interface{}, len(options))
+ argsSlice := make([]any, len(options))
for i, v := range options {
argsSlice[i] = v
}
@@ -92,9 +92,14 @@ func (m *mockMediaFileRepo) Get(id string) (*model.MediaFile, error) {
return args.Get(0).(*model.MediaFile), args.Error(1)
}
+// GetAllByTags implements model.MediaFileRepository.
+func (m *mockMediaFileRepo) GetAllByTags(_ model.TagName, _ []string, options ...model.QueryOptions) (model.MediaFiles, error) {
+ return m.GetAll(options...)
+}
+
// GetAll implements model.MediaFileRepository.
func (m *mockMediaFileRepo) GetAll(options ...model.QueryOptions) (model.MediaFiles, error) {
- argsSlice := make([]interface{}, len(options))
+ argsSlice := make([]any, len(options))
for i, v := range options {
argsSlice[i] = v
}
@@ -147,7 +152,7 @@ func (m *mockAlbumRepo) Get(id string) (*model.Album, error) {
// GetAll implements model.AlbumRepository.
func (m *mockAlbumRepo) GetAll(options ...model.QueryOptions) (model.Albums, error) {
- argsSlice := make([]interface{}, len(options))
+ argsSlice := make([]any, len(options))
for i, v := range options {
argsSlice[i] = v
}
@@ -282,3 +287,27 @@ func (m *mockAgents) GetAlbumImages(ctx context.Context, name, artist, mbid stri
}
return nil, args.Error(1)
}
+
+func (m *mockAgents) GetSimilarSongsByTrack(ctx context.Context, id, name, artist, mbid string, count int) ([]agents.Song, error) {
+ args := m.Called(ctx, id, name, artist, mbid, count)
+ if args.Get(0) != nil {
+ return args.Get(0).([]agents.Song), args.Error(1)
+ }
+ return nil, args.Error(1)
+}
+
+func (m *mockAgents) GetSimilarSongsByAlbum(ctx context.Context, id, name, artist, mbid string, count int) ([]agents.Song, error) {
+ args := m.Called(ctx, id, name, artist, mbid, count)
+ if args.Get(0) != nil {
+ return args.Get(0).([]agents.Song), args.Error(1)
+ }
+ return nil, args.Error(1)
+}
+
+func (m *mockAgents) GetSimilarSongsByArtist(ctx context.Context, id, name, mbid string, count int) ([]agents.Song, error) {
+ args := m.Called(ctx, id, name, mbid, count)
+ if args.Get(0) != nil {
+ return args.Get(0).([]agents.Song), args.Error(1)
+ }
+ return nil, args.Error(1)
+}
diff --git a/core/external/provider.go b/core/external/provider.go
index 8e9a458c1..a30afed15 100644
--- a/core/external/provider.go
+++ b/core/external/provider.go
@@ -12,10 +12,6 @@ import (
"github.com/Masterminds/squirrel"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
- _ "github.com/navidrome/navidrome/core/agents/deezer"
- _ "github.com/navidrome/navidrome/core/agents/lastfm"
- _ "github.com/navidrome/navidrome/core/agents/listenbrainz"
- _ "github.com/navidrome/navidrome/core/agents/spotify"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils"
@@ -36,7 +32,7 @@ const (
type Provider interface {
UpdateAlbumInfo(ctx context.Context, id string) (*model.Album, error)
UpdateArtistInfo(ctx context.Context, id string, count int, includeNotPresent bool) (*model.Artist, error)
- ArtistRadio(ctx context.Context, id string, count int) (model.MediaFiles, error)
+ SimilarSongs(ctx context.Context, id string, count int) (model.MediaFiles, error)
TopSongs(ctx context.Context, artist string, count int) (model.MediaFiles, error)
ArtistImage(ctx context.Context, id string) (*url.URL, error)
AlbumImage(ctx context.Context, id string) (*url.URL, error)
@@ -51,12 +47,28 @@ type provider struct {
type auxAlbum struct {
model.Album
- Name string
+}
+
+// Name returns the appropriate album name for external API calls
+// based on the DevPreserveUnicodeInExternalCalls configuration option
+func (a *auxAlbum) Name() string {
+ if conf.Server.DevPreserveUnicodeInExternalCalls {
+ return a.Album.Name
+ }
+ return str.Clear(a.Album.Name)
}
type auxArtist struct {
model.Artist
- Name string
+}
+
+// Name returns the appropriate artist name for external API calls
+// based on the DevPreserveUnicodeInExternalCalls configuration option
+func (a *auxArtist) Name() string {
+ if conf.Server.DevPreserveUnicodeInExternalCalls {
+ return a.Artist.Name
+ }
+ return str.Clear(a.Artist.Name)
}
type Agents interface {
@@ -68,6 +80,9 @@ type Agents interface {
agents.ArtistSimilarRetriever
agents.ArtistTopSongsRetriever
agents.ArtistURLRetriever
+ agents.SimilarSongsByTrackRetriever
+ agents.SimilarSongsByAlbumRetriever
+ agents.SimilarSongsByArtistRetriever
}
func NewProvider(ds model.DataStore, agents Agents) Provider {
@@ -78,7 +93,7 @@ func NewProvider(ds model.DataStore, agents Agents) Provider {
}
func (e *provider) getAlbum(ctx context.Context, id string) (auxAlbum, error) {
- var entity interface{}
+ var entity any
entity, err := model.GetEntityByID(ctx, e.ds, id)
if err != nil {
return auxAlbum{}, err
@@ -88,7 +103,6 @@ func (e *provider) getAlbum(ctx context.Context, id string) (auxAlbum, error) {
switch v := entity.(type) {
case *model.Album:
album.Album = *v
- album.Name = str.Clear(v.Name)
case *model.MediaFile:
return e.getAlbum(ctx, v.AlbumID)
default:
@@ -106,8 +120,9 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
}
updatedAt := V(album.ExternalInfoUpdatedAt)
+ albumName := album.Name()
if updatedAt.IsZero() {
- log.Debug(ctx, "AlbumInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", album.Name)
+ log.Debug(ctx, "AlbumInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", albumName)
album, err = e.populateAlbumInfo(ctx, album)
if err != nil {
return nil, err
@@ -116,7 +131,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
// If info is expired, trigger a populateAlbumInfo in the background
if time.Since(updatedAt) > conf.Server.DevAlbumInfoTimeToLive {
- log.Debug("Found expired cached AlbumInfo, refreshing in the background", "updatedAt", album.ExternalInfoUpdatedAt, "name", album.Name)
+ log.Debug("Found expired cached AlbumInfo, refreshing in the background", "updatedAt", album.ExternalInfoUpdatedAt, "name", albumName)
e.albumQueue.enqueue(&album)
}
@@ -125,12 +140,13 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
func (e *provider) populateAlbumInfo(ctx context.Context, album auxAlbum) (auxAlbum, error) {
start := time.Now()
- info, err := e.ag.GetAlbumInfo(ctx, album.Name, album.AlbumArtist, album.MbzAlbumID)
+ albumName := album.Name()
+ info, err := e.ag.GetAlbumInfo(ctx, albumName, album.AlbumArtist, album.MbzAlbumID)
if errors.Is(err, agents.ErrNotFound) {
return album, nil
}
if err != nil {
- log.Error("Error refreshing AlbumInfo", "id", album.ID, "name", album.Name, "artist", album.AlbumArtist,
+ log.Error("Error refreshing AlbumInfo", "id", album.ID, "name", albumName, "artist", album.AlbumArtist,
"elapsed", time.Since(start), err)
return album, err
}
@@ -142,7 +158,7 @@ func (e *provider) populateAlbumInfo(ctx context.Context, album auxAlbum) (auxAl
album.Description = info.Description
}
- images, err := e.ag.GetAlbumImages(ctx, album.Name, album.AlbumArtist, album.MbzAlbumID)
+ images, err := e.ag.GetAlbumImages(ctx, albumName, album.AlbumArtist, album.MbzAlbumID)
if err == nil && len(images) > 0 {
sort.Slice(images, func(i, j int) bool {
return images[i].Size > images[j].Size
@@ -161,7 +177,7 @@ func (e *provider) populateAlbumInfo(ctx context.Context, album auxAlbum) (auxAl
err = e.ds.Album(ctx).UpdateExternalInfo(&album.Album)
if err != nil {
- log.Error(ctx, "Error trying to update album external information", "id", album.ID, "name", album.Name,
+ log.Error(ctx, "Error trying to update album external information", "id", album.ID, "name", albumName,
"elapsed", time.Since(start), err)
} else {
log.Trace(ctx, "AlbumInfo collected", "album", album, "elapsed", time.Since(start))
@@ -171,7 +187,7 @@ func (e *provider) populateAlbumInfo(ctx context.Context, album auxAlbum) (auxAl
}
func (e *provider) getArtist(ctx context.Context, id string) (auxArtist, error) {
- var entity interface{}
+ var entity any
entity, err := model.GetEntityByID(ctx, e.ds, id)
if err != nil {
return auxArtist{}, err
@@ -181,7 +197,6 @@ func (e *provider) getArtist(ctx context.Context, id string) (auxArtist, error)
switch v := entity.(type) {
case *model.Artist:
artist.Artist = *v
- artist.Name = str.Clear(v.Name)
case *model.MediaFile:
return e.getArtist(ctx, v.ArtistID)
case *model.Album:
@@ -210,8 +225,9 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
// If we don't have any info, retrieves it now
updatedAt := V(artist.ExternalInfoUpdatedAt)
+ artistName := artist.Name()
if updatedAt.IsZero() {
- log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artist.Name)
+ log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artistName)
artist, err = e.populateArtistInfo(ctx, artist)
if err != nil {
return auxArtist{}, err
@@ -220,7 +236,7 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
// If info is expired, trigger a populateArtistInfo in the background
if time.Since(updatedAt) > conf.Server.DevArtistInfoTimeToLive {
- log.Debug("Found expired cached ArtistInfo, refreshing in the background", "updatedAt", updatedAt, "name", artist.Name)
+ log.Debug("Found expired cached ArtistInfo, refreshing in the background", "updatedAt", updatedAt, "name", artistName)
e.artistQueue.enqueue(&artist)
}
return artist, nil
@@ -229,8 +245,9 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
func (e *provider) populateArtistInfo(ctx context.Context, artist auxArtist) (auxArtist, error) {
start := time.Now()
// Get MBID first, if it is not yet available
+ artistName := artist.Name()
if artist.MbzArtistID == "" {
- mbid, err := e.ag.GetArtistMBID(ctx, artist.ID, artist.Name)
+ mbid, err := e.ag.GetArtistMBID(ctx, artist.ID, artistName)
if mbid != "" && err == nil {
artist.MbzArtistID = mbid
}
@@ -242,18 +259,18 @@ func (e *provider) populateArtistInfo(ctx context.Context, artist auxArtist) (au
g.Go(func() error { e.callGetImage(ctx, e.ag, &artist); return nil })
g.Go(func() error { e.callGetBiography(ctx, e.ag, &artist); return nil })
g.Go(func() error { e.callGetURL(ctx, e.ag, &artist); return nil })
- g.Go(func() error { e.callGetSimilar(ctx, e.ag, &artist, maxSimilarArtists, true); return nil })
+ g.Go(func() error { e.callGetSimilarArtists(ctx, e.ag, &artist, maxSimilarArtists, true); return nil })
_ = g.Wait()
if utils.IsCtxDone(ctx) {
- log.Warn(ctx, "ArtistInfo update canceled", "elapsed", "id", artist.ID, "name", artist.Name, time.Since(start), ctx.Err())
+ log.Warn(ctx, "ArtistInfo update canceled", "id", artist.ID, "name", artistName, "elapsed", time.Since(start), ctx.Err())
return artist, ctx.Err()
}
artist.ExternalInfoUpdatedAt = P(time.Now())
err := e.ds.Artist(ctx).UpdateExternalInfo(&artist.Artist)
if err != nil {
- log.Error(ctx, "Error trying to update artist external information", "id", artist.ID, "name", artist.Name,
+ log.Error(ctx, "Error trying to update artist external information", "id", artist.ID, "name", artistName,
"elapsed", time.Since(start), err)
} else {
log.Trace(ctx, "ArtistInfo collected", "artist", artist, "elapsed", time.Since(start))
@@ -261,27 +278,59 @@ func (e *provider) populateArtistInfo(ctx context.Context, artist auxArtist) (au
return artist, nil
}
-func (e *provider) ArtistRadio(ctx context.Context, id string, count int) (model.MediaFiles, error) {
+func (e *provider) SimilarSongs(ctx context.Context, id string, count int) (model.MediaFiles, error) {
+ entity, err := model.GetEntityByID(ctx, e.ds, id)
+ if err != nil {
+ return nil, err
+ }
+
+ var songs []agents.Song
+
+ // Try entity-specific similarity first
+ switch v := entity.(type) {
+ case *model.MediaFile:
+ songs, err = e.ag.GetSimilarSongsByTrack(ctx, v.ID, v.Title, v.Artist, v.MbzRecordingID, count)
+ case *model.Album:
+ songs, err = e.ag.GetSimilarSongsByAlbum(ctx, v.ID, v.Name, v.AlbumArtist, v.MbzAlbumID, count)
+ case *model.Artist:
+ songs, err = e.ag.GetSimilarSongsByArtist(ctx, v.ID, v.Name, v.MbzArtistID, count)
+ default:
+ log.Warn(ctx, "Unknown entity type", "id", id, "type", fmt.Sprintf("%T", entity))
+ return nil, model.ErrNotFound
+ }
+
+ if err == nil && len(songs) > 0 {
+ return e.matchSongsToLibrary(ctx, songs, count)
+ }
+
+ // Fallback to existing similar artists + top songs algorithm
+ return e.similarSongsFallback(ctx, id, count)
+}
+
+// similarSongsFallback uses the original similar artists + top songs algorithm. The idea is to
+// get the artist of the given entity, retrieve similar artists, get their top songs, and pick
+// a weighted random selection of songs to return as similar songs.
+func (e *provider) similarSongsFallback(ctx context.Context, id string, count int) (model.MediaFiles, error) {
artist, err := e.getArtist(ctx, id)
if err != nil {
return nil, err
}
- e.callGetSimilar(ctx, e.ag, &artist, 15, false)
+ e.callGetSimilarArtists(ctx, e.ag, &artist, 15, false)
if utils.IsCtxDone(ctx) {
- log.Warn(ctx, "ArtistRadio call canceled", ctx.Err())
+ log.Warn(ctx, "SimilarSongs call canceled", ctx.Err())
return nil, ctx.Err()
}
weightedSongs := random.NewWeightedChooser[model.MediaFile]()
addArtist := func(a model.Artist, weightedSongs *random.WeightedChooser[model.MediaFile], count, artistWeight int) error {
if utils.IsCtxDone(ctx) {
- log.Warn(ctx, "ArtistRadio call canceled", ctx.Err())
+ log.Warn(ctx, "SimilarSongs call canceled", ctx.Err())
return ctx.Err()
}
topCount := max(count, 20)
- topSongs, err := e.getMatchingTopSongs(ctx, e.ag, &auxArtist{Name: a.Name, Artist: a}, topCount)
+ topSongs, err := e.getMatchingTopSongs(ctx, e.ag, &auxArtist{Artist: a}, topCount)
if err != nil {
log.Warn(ctx, "Error getting artist's top songs", "artist", a.Name, err)
return nil
@@ -325,13 +374,19 @@ func (e *provider) ArtistImage(ctx context.Context, id string) (*url.URL, error)
return nil, err
}
- e.callGetImage(ctx, e.ag, &artist)
- if utils.IsCtxDone(ctx) {
- log.Warn(ctx, "ArtistImage call canceled", ctx.Err())
- return nil, ctx.Err()
+ // Use already-stored image URL if available, avoiding expensive external API calls.
+ // If the info is expired, the background refresh (via UpdateArtistInfo/artistQueue) will update it.
+ imageUrl := artist.ArtistImageUrl()
+ if imageUrl == "" {
+ // No cached URL — must fetch from external source synchronously
+ e.callGetImage(ctx, e.ag, &artist)
+ if utils.IsCtxDone(ctx) {
+ log.Warn(ctx, "ArtistImage call canceled", ctx.Err())
+ return nil, ctx.Err()
+ }
+ imageUrl = artist.ArtistImageUrl()
}
- imageUrl := artist.ArtistImageUrl()
if imageUrl == "" {
return nil, model.ErrNotFound
}
@@ -344,22 +399,23 @@ func (e *provider) AlbumImage(ctx context.Context, id string) (*url.URL, error)
return nil, err
}
- images, err := e.ag.GetAlbumImages(ctx, album.Name, album.AlbumArtist, album.MbzAlbumID)
+ albumName := album.Name()
+ images, err := e.ag.GetAlbumImages(ctx, albumName, album.AlbumArtist, album.MbzAlbumID)
if err != nil {
switch {
case errors.Is(err, agents.ErrNotFound):
- log.Trace(ctx, "Album not found in agent", "albumID", id, "name", album.Name, "artist", album.AlbumArtist)
+ log.Trace(ctx, "Album not found in agent", "albumID", id, "name", albumName, "artist", album.AlbumArtist)
return nil, model.ErrNotFound
case errors.Is(err, context.Canceled):
log.Debug(ctx, "GetAlbumImages call canceled", err)
default:
- log.Warn(ctx, "Error getting album images from agent", "albumID", id, "name", album.Name, "artist", album.AlbumArtist, err)
+ log.Warn(ctx, "Error getting album images from agent", "albumID", id, "name", albumName, "artist", album.AlbumArtist, err)
}
return nil, err
}
if len(images) == 0 {
- log.Warn(ctx, "Agent returned no images without error", "albumID", id, "name", album.Name, "artist", album.AlbumArtist)
+ log.Warn(ctx, "Agent returned no images without error", "albumID", id, "name", albumName, "artist", album.AlbumArtist)
return nil, model.ErrNotFound
}
@@ -401,124 +457,38 @@ func (e *provider) TopSongs(ctx context.Context, artistName string, count int) (
}
func (e *provider) getMatchingTopSongs(ctx context.Context, agent agents.ArtistTopSongsRetriever, artist *auxArtist, count int) (model.MediaFiles, error) {
- songs, err := agent.GetArtistTopSongs(ctx, artist.ID, artist.Name, artist.MbzArtistID, count)
+ artistName := artist.Name()
+ songs, err := agent.GetArtistTopSongs(ctx, artist.ID, artistName, artist.MbzArtistID, count)
if err != nil {
- return nil, fmt.Errorf("failed to get top songs for artist %s: %w", artist.Name, err)
+ return nil, fmt.Errorf("failed to get top songs for artist %s: %w", artistName, err)
}
- mbidMatches, err := e.loadTracksByMBID(ctx, songs)
- if err != nil {
- return nil, fmt.Errorf("failed to load tracks by MBID: %w", err)
- }
- titleMatches, err := e.loadTracksByTitle(ctx, songs, artist, mbidMatches)
- if err != nil {
- return nil, fmt.Errorf("failed to load tracks by title: %w", err)
+ // Enrich songs with artist info if not already present (for top songs, we know the artist)
+ for i := range songs {
+ if songs[i].Artist == "" {
+ songs[i].Artist = artistName
+ }
+ if songs[i].ArtistMBID == "" {
+ songs[i].ArtistMBID = artist.MbzArtistID
+ }
}
- log.Trace(ctx, "Top Songs loaded", "name", artist.Name, "numSongs", len(songs), "numMBIDMatches", len(mbidMatches), "numTitleMatches", len(titleMatches))
- mfs := e.selectTopSongs(songs, mbidMatches, titleMatches, count)
+ mfs, err := e.matchSongsToLibrary(ctx, songs, count)
+ if err != nil {
+ return nil, err
+ }
if len(mfs) == 0 {
- log.Debug(ctx, "No matching top songs found", "name", artist.Name)
+ log.Debug(ctx, "No matching top songs found", "name", artistName)
} else {
- log.Debug(ctx, "Found matching top songs", "name", artist.Name, "numSongs", len(mfs))
+ log.Debug(ctx, "Found matching top songs", "name", artistName, "numSongs", len(mfs))
}
return mfs, nil
}
-func (e *provider) loadTracksByMBID(ctx context.Context, songs []agents.Song) (map[string]model.MediaFile, error) {
- var mbids []string
- for _, s := range songs {
- if s.MBID != "" {
- mbids = append(mbids, s.MBID)
- }
- }
- matches := map[string]model.MediaFile{}
- if len(mbids) == 0 {
- return matches, nil
- }
- res, err := e.ds.MediaFile(ctx).GetAll(model.QueryOptions{
- Filters: squirrel.And{
- squirrel.Eq{"mbz_recording_id": mbids},
- squirrel.Eq{"missing": false},
- },
- })
- if err != nil {
- return matches, err
- }
- for _, mf := range res {
- if id := mf.MbzRecordingID; id != "" {
- if _, ok := matches[id]; !ok {
- matches[id] = mf
- }
- }
- }
- return matches, nil
-}
-
-func (e *provider) loadTracksByTitle(ctx context.Context, songs []agents.Song, artist *auxArtist, mbidMatches map[string]model.MediaFile) (map[string]model.MediaFile, error) {
- titleMap := map[string]string{}
- for _, s := range songs {
- if s.MBID != "" && mbidMatches[s.MBID].ID != "" {
- continue
- }
- sanitized := str.SanitizeFieldForSorting(s.Name)
- titleMap[sanitized] = s.Name
- }
- matches := map[string]model.MediaFile{}
- if len(titleMap) == 0 {
- return matches, nil
- }
- titleFilters := squirrel.Or{}
- for sanitized := range titleMap {
- titleFilters = append(titleFilters, squirrel.Like{"order_title": sanitized})
- }
-
- res, err := e.ds.MediaFile(ctx).GetAll(model.QueryOptions{
- Filters: squirrel.And{
- squirrel.Or{
- squirrel.Eq{"artist_id": artist.ID},
- squirrel.Eq{"album_artist_id": artist.ID},
- },
- titleFilters,
- squirrel.Eq{"missing": false},
- },
- Sort: "starred desc, rating desc, year asc, compilation asc ",
- })
- if err != nil {
- return matches, err
- }
- for _, mf := range res {
- sanitized := str.SanitizeFieldForSorting(mf.Title)
- if _, ok := matches[sanitized]; !ok {
- matches[sanitized] = mf
- }
- }
- return matches, nil
-}
-
-func (e *provider) selectTopSongs(songs []agents.Song, byMBID, byTitle map[string]model.MediaFile, count int) model.MediaFiles {
- var mfs model.MediaFiles
- for _, t := range songs {
- if len(mfs) == count {
- break
- }
- if t.MBID != "" {
- if mf, ok := byMBID[t.MBID]; ok {
- mfs = append(mfs, mf)
- continue
- }
- }
- if mf, ok := byTitle[str.SanitizeFieldForSorting(t.Name)]; ok {
- mfs = append(mfs, mf)
- }
- }
- return mfs
-}
-
func (e *provider) callGetURL(ctx context.Context, agent agents.ArtistURLRetriever, artist *auxArtist) {
- artisURL, err := agent.GetArtistURL(ctx, artist.ID, artist.Name, artist.MbzArtistID)
+ artisURL, err := agent.GetArtistURL(ctx, artist.ID, artist.Name(), artist.MbzArtistID)
if err != nil {
return
}
@@ -526,7 +496,7 @@ func (e *provider) callGetURL(ctx context.Context, agent agents.ArtistURLRetriev
}
func (e *provider) callGetBiography(ctx context.Context, agent agents.ArtistBiographyRetriever, artist *auxArtist) {
- bio, err := agent.GetArtistBiography(ctx, artist.ID, str.Clear(artist.Name), artist.MbzArtistID)
+ bio, err := agent.GetArtistBiography(ctx, artist.ID, artist.Name(), artist.MbzArtistID)
if err != nil {
return
}
@@ -536,7 +506,7 @@ func (e *provider) callGetBiography(ctx context.Context, agent agents.ArtistBiog
}
func (e *provider) callGetImage(ctx context.Context, agent agents.ArtistImageRetriever, artist *auxArtist) {
- images, err := agent.GetArtistImages(ctx, artist.ID, artist.Name, artist.MbzArtistID)
+ images, err := agent.GetArtistImages(ctx, artist.ID, artist.Name(), artist.MbzArtistID)
if err != nil {
return
}
@@ -553,15 +523,16 @@ func (e *provider) callGetImage(ctx context.Context, agent agents.ArtistImageRet
}
}
-func (e *provider) callGetSimilar(ctx context.Context, agent agents.ArtistSimilarRetriever, artist *auxArtist,
+func (e *provider) callGetSimilarArtists(ctx context.Context, agent agents.ArtistSimilarRetriever, artist *auxArtist,
limit int, includeNotPresent bool) {
- similar, err := agent.GetSimilarArtists(ctx, artist.ID, artist.Name, artist.MbzArtistID, limit)
+ artistName := artist.Name()
+ similar, err := agent.GetSimilarArtists(ctx, artist.ID, artistName, artist.MbzArtistID, limit)
if len(similar) == 0 || err != nil {
return
}
start := time.Now()
sa, err := e.mapSimilarArtists(ctx, similar, limit, includeNotPresent)
- log.Debug(ctx, "Mapped Similar Artists", "artist", artist.Name, "numSimilar", len(sa), "elapsed", time.Since(start))
+ log.Debug(ctx, "Mapped Similar Artists", "artist", artistName, "numSimilar", len(sa), "elapsed", time.Since(start))
if err != nil {
return
}
@@ -572,36 +543,51 @@ func (e *provider) mapSimilarArtists(ctx context.Context, similar []agents.Artis
var result model.Artists
var notPresent []string
- artistNames := slice.Map(similar, func(artist agents.Artist) string { return artist.Name })
-
- // Query all artists at once
- clauses := slice.Map(artistNames, func(name string) squirrel.Sqlizer {
- return squirrel.Like{"artist.name": name}
- })
- artists, err := e.ds.Artist(ctx).GetAll(model.QueryOptions{
- Filters: squirrel.Or(clauses),
- })
+ // Load artists by ID (highest priority)
+ idMatches, err := e.loadArtistsByID(ctx, similar)
if err != nil {
return nil, err
}
- // Create a map for quick lookup
- artistMap := make(map[string]model.Artist)
- for _, artist := range artists {
- artistMap[artist.Name] = artist
+ // Load artists by MBID (second priority)
+ mbidMatches, err := e.loadArtistsByMBID(ctx, similar, idMatches)
+ if err != nil {
+ return nil, err
+ }
+
+ // Load artists by name (lowest priority, fallback)
+ nameMatches, err := e.loadArtistsByName(ctx, similar, idMatches, mbidMatches)
+ if err != nil {
+ return nil, err
}
count := 0
- // Process the similar artists
+ // Process the similar artists using priority: ID → MBID → Name
for _, s := range similar {
- if artist, found := artistMap[s.Name]; found {
+ if count >= limit {
+ break
+ }
+ // Try ID match first
+ if s.ID != "" {
+ if artist, found := idMatches[s.ID]; found {
+ result = append(result, artist)
+ count++
+ continue
+ }
+ }
+ // Try MBID match second
+ if s.MBID != "" {
+ if artist, found := mbidMatches[s.MBID]; found {
+ result = append(result, artist)
+ count++
+ continue
+ }
+ }
+ // Fall back to name match
+ if artist, found := nameMatches[s.Name]; found {
result = append(result, artist)
count++
-
- if count >= limit {
- break
- }
} else {
notPresent = append(notPresent, s.Name)
}
@@ -624,6 +610,95 @@ func (e *provider) mapSimilarArtists(ctx context.Context, similar []agents.Artis
return result, nil
}
+func (e *provider) loadArtistsByID(ctx context.Context, similar []agents.Artist) (map[string]model.Artist, error) {
+ var ids []string
+ for _, s := range similar {
+ if s.ID != "" {
+ ids = append(ids, s.ID)
+ }
+ }
+ matches := map[string]model.Artist{}
+ if len(ids) == 0 {
+ return matches, nil
+ }
+ res, err := e.ds.Artist(ctx).GetAll(model.QueryOptions{
+ Filters: squirrel.Eq{"artist.id": ids},
+ })
+ if err != nil {
+ return matches, err
+ }
+ for _, a := range res {
+ if _, ok := matches[a.ID]; !ok {
+ matches[a.ID] = a
+ }
+ }
+ return matches, nil
+}
+
+func (e *provider) loadArtistsByMBID(ctx context.Context, similar []agents.Artist, idMatches map[string]model.Artist) (map[string]model.Artist, error) {
+ var mbids []string
+ for _, s := range similar {
+ // Skip if already matched by ID
+ if s.ID != "" && idMatches[s.ID].ID != "" {
+ continue
+ }
+ if s.MBID != "" {
+ mbids = append(mbids, s.MBID)
+ }
+ }
+ matches := map[string]model.Artist{}
+ if len(mbids) == 0 {
+ return matches, nil
+ }
+ res, err := e.ds.Artist(ctx).GetAll(model.QueryOptions{
+ Filters: squirrel.Eq{"mbz_artist_id": mbids},
+ })
+ if err != nil {
+ return matches, err
+ }
+ for _, a := range res {
+ if id := a.MbzArtistID; id != "" {
+ if _, ok := matches[id]; !ok {
+ matches[id] = a
+ }
+ }
+ }
+ return matches, nil
+}
+
+func (e *provider) loadArtistsByName(ctx context.Context, similar []agents.Artist, idMatches map[string]model.Artist, mbidMatches map[string]model.Artist) (map[string]model.Artist, error) {
+ var names []string
+ for _, s := range similar {
+ // Skip if already matched by ID or MBID
+ if s.ID != "" && idMatches[s.ID].ID != "" {
+ continue
+ }
+ if s.MBID != "" && mbidMatches[s.MBID].ID != "" {
+ continue
+ }
+ names = append(names, s.Name)
+ }
+ matches := map[string]model.Artist{}
+ if len(names) == 0 {
+ return matches, nil
+ }
+ clauses := slice.Map(names, func(name string) squirrel.Sqlizer {
+ return squirrel.Like{"artist.name": name}
+ })
+ res, err := e.ds.Artist(ctx).GetAll(model.QueryOptions{
+ Filters: squirrel.Or(clauses),
+ })
+ if err != nil {
+ return matches, err
+ }
+ for _, a := range res {
+ if _, ok := matches[a.Name]; !ok {
+ matches[a.Name] = a
+ }
+ }
+ return matches, nil
+}
+
func (e *provider) findArtistByName(ctx context.Context, artistName string) (*auxArtist, error) {
artists, err := e.ds.Artist(ctx).GetAll(model.QueryOptions{
Filters: squirrel.Like{"artist.name": artistName},
@@ -635,11 +710,7 @@ func (e *provider) findArtistByName(ctx context.Context, artistName string) (*au
if len(artists) == 0 {
return nil, model.ErrNotFound
}
- artist := &auxArtist{
- Artist: artists[0],
- Name: str.Clear(artists[0].Name),
- }
- return artist, nil
+ return &auxArtist{Artist: artists[0]}, nil
}
func (e *provider) loadSimilar(ctx context.Context, artist *auxArtist, count int, includeNotPresent bool) error {
@@ -655,7 +726,7 @@ func (e *provider) loadSimilar(ctx context.Context, artist *auxArtist, count int
Filters: squirrel.Eq{"artist.id": ids},
})
if err != nil {
- log.Error("Error loading similar artists", "id", artist.ID, "name", artist.Name, err)
+ log.Error("Error loading similar artists", "id", artist.ID, "name", artist.Name(), err)
return err
}
diff --git a/core/external/provider_albumimage_test.go b/core/external/provider_albumimage_test.go
index 9b682462d..8a81b4f4d 100644
--- a/core/external/provider_albumimage_test.go
+++ b/core/external/provider_albumimage_test.go
@@ -260,6 +260,69 @@ var _ = Describe("Provider - AlbumImage", func() {
mockMediaFileRepo.AssertCalled(GinkgoT(), "Get", "not-found")
mockAlbumAgent.AssertNotCalled(GinkgoT(), "GetAlbumImages", mock.Anything, mock.Anything, mock.Anything)
})
+
+ Context("Unicode handling in album names", func() {
+ var albumWithEnDash *model.Album
+ var expectedURL *url.URL
+
+ const (
+ originalAlbumName = "Raising Hell–Deluxe" // Album name with en dash
+ normalizedAlbumName = "Raising Hell-Deluxe" // Normalized version with hyphen
+ )
+
+ BeforeEach(func() {
+ // Test with en dash (–) in album name
+ albumWithEnDash = &model.Album{ID: "album-endash", Name: originalAlbumName, AlbumArtistID: "artist-1"}
+ mockArtistRepo.Mock = mock.Mock{} // Reset default expectations
+ mockAlbumRepo.Mock = mock.Mock{} // Reset default expectations
+ mockArtistRepo.On("Get", "album-endash").Return(nil, model.ErrNotFound).Once()
+ mockAlbumRepo.On("Get", "album-endash").Return(albumWithEnDash, nil).Once()
+
+ expectedURL, _ = url.Parse("http://example.com/album.jpg")
+
+ // Mock the album agent to return an image for the album
+ mockAlbumAgent.On("GetAlbumImages", ctx, mock.AnythingOfType("string"), "", "").
+ Return([]agents.ExternalImage{
+ {URL: "http://example.com/album.jpg", Size: 1000},
+ }, nil).Once()
+ })
+
+ When("DevPreserveUnicodeInExternalCalls is true", func() {
+ BeforeEach(func() {
+ conf.Server.DevPreserveUnicodeInExternalCalls = true
+ })
+
+ It("preserves Unicode characters in album names", func() {
+ // Act
+ imgURL, err := provider.AlbumImage(ctx, "album-endash")
+
+ // Assert
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgURL).To(Equal(expectedURL))
+ mockAlbumRepo.AssertCalled(GinkgoT(), "Get", "album-endash")
+ // This is the key assertion: ensure the original Unicode name is used
+ mockAlbumAgent.AssertCalled(GinkgoT(), "GetAlbumImages", ctx, originalAlbumName, "", "")
+ })
+ })
+
+ When("DevPreserveUnicodeInExternalCalls is false", func() {
+ BeforeEach(func() {
+ conf.Server.DevPreserveUnicodeInExternalCalls = false
+ })
+
+ It("normalizes Unicode characters", func() {
+ // Act
+ imgURL, err := provider.AlbumImage(ctx, "album-endash")
+
+ // Assert
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgURL).To(Equal(expectedURL))
+ mockAlbumRepo.AssertCalled(GinkgoT(), "Get", "album-endash")
+ // This assertion ensures the normalized name is used (en dash → hyphen)
+ mockAlbumAgent.AssertCalled(GinkgoT(), "GetAlbumImages", ctx, normalizedAlbumName, "", "")
+ })
+ })
+ })
})
// mockAlbumInfoAgent implementation
diff --git a/core/external/provider_artistimage_test.go b/core/external/provider_artistimage_test.go
index 96341836a..11290bb66 100644
--- a/core/external/provider_artistimage_test.go
+++ b/core/external/provider_artistimage_test.go
@@ -265,6 +265,67 @@ var _ = Describe("Provider - ArtistImage", func() {
mockArtistRepo.AssertCalled(GinkgoT(), "Get", "artist-1")
mockImageAgent.AssertCalled(GinkgoT(), "GetArtistImages", ctx, "artist-1", "Artist One", "")
})
+
+ Context("Unicode handling in artist names", func() {
+ var artistWithEnDash *model.Artist
+ var expectedURL *url.URL
+
+ const (
+ originalArtistName = "Run–D.M.C." // Artist name with en dash
+ normalizedArtistName = "Run-D.M.C." // Normalized version with hyphen
+ )
+
+ BeforeEach(func() {
+ // Test with en dash (–) in artist name like "Run–D.M.C."
+ artistWithEnDash = &model.Artist{ID: "artist-endash", Name: originalArtistName}
+ mockArtistRepo.Mock = mock.Mock{} // Reset default expectations
+ mockArtistRepo.On("Get", "artist-endash").Return(artistWithEnDash, nil).Once()
+
+ expectedURL, _ = url.Parse("http://example.com/rundmc.jpg")
+
+ // Mock the image agent to return an image for the artist
+ mockImageAgent.On("GetArtistImages", ctx, "artist-endash", mock.AnythingOfType("string"), "").
+ Return([]agents.ExternalImage{
+ {URL: "http://example.com/rundmc.jpg", Size: 1000},
+ }, nil).Once()
+
+ })
+
+ When("DevPreserveUnicodeInExternalCalls is true", func() {
+ BeforeEach(func() {
+ conf.Server.DevPreserveUnicodeInExternalCalls = true
+ })
+ It("preserves Unicode characters in artist names", func() {
+ // Act
+ imgURL, err := provider.ArtistImage(ctx, "artist-endash")
+
+ // Assert
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgURL).To(Equal(expectedURL))
+ mockArtistRepo.AssertCalled(GinkgoT(), "Get", "artist-endash")
+ // This is the key assertion: ensure the original Unicode name is used
+ mockImageAgent.AssertCalled(GinkgoT(), "GetArtistImages", ctx, "artist-endash", originalArtistName, "")
+ })
+ })
+
+ When("DevPreserveUnicodeInExternalCalls is false", func() {
+ BeforeEach(func() {
+ conf.Server.DevPreserveUnicodeInExternalCalls = false
+ })
+
+ It("normalizes Unicode characters", func() {
+ // Act
+ imgURL, err := provider.ArtistImage(ctx, "artist-endash")
+
+ // Assert
+ Expect(err).ToNot(HaveOccurred())
+ Expect(imgURL).To(Equal(expectedURL))
+ mockArtistRepo.AssertCalled(GinkgoT(), "Get", "artist-endash")
+ // This assertion ensures the normalized name is used (en dash → hyphen)
+ mockImageAgent.AssertCalled(GinkgoT(), "GetArtistImages", ctx, "artist-endash", normalizedArtistName, "")
+ })
+ })
+ })
})
// mockArtistImageAgent implementation using testify/mock
diff --git a/core/external/provider_artistradio_test.go b/core/external/provider_artistradio_test.go
deleted file mode 100644
index 21ea07706..000000000
--- a/core/external/provider_artistradio_test.go
+++ /dev/null
@@ -1,196 +0,0 @@
-package external_test
-
-import (
- "context"
- "errors"
-
- "github.com/navidrome/navidrome/core/agents"
- . "github.com/navidrome/navidrome/core/external"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/tests"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
- "github.com/stretchr/testify/mock"
-)
-
-var _ = Describe("Provider - ArtistRadio", func() {
- var ds model.DataStore
- var provider Provider
- var mockAgent *mockSimilarArtistAgent
- var mockTopAgent agents.ArtistTopSongsRetriever
- var mockSimilarAgent agents.ArtistSimilarRetriever
- var agentsCombined Agents
- var artistRepo *mockArtistRepo
- var mediaFileRepo *mockMediaFileRepo
- var ctx context.Context
-
- BeforeEach(func() {
- ctx = GinkgoT().Context()
-
- artistRepo = newMockArtistRepo()
- mediaFileRepo = newMockMediaFileRepo()
-
- ds = &tests.MockDataStore{
- MockedArtist: artistRepo,
- MockedMediaFile: mediaFileRepo,
- }
-
- mockAgent = &mockSimilarArtistAgent{}
- mockTopAgent = mockAgent
- mockSimilarAgent = mockAgent
-
- agentsCombined = &mockAgents{
- topSongsAgent: mockTopAgent,
- similarAgent: mockSimilarAgent,
- }
-
- provider = NewProvider(ds, agentsCombined)
- })
-
- It("returns similar songs from main artist and similar artists", func() {
- artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
- similarArtist := model.Artist{ID: "artist-3", Name: "Similar Artist"}
- song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
- song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"}
- song3 := model.MediaFile{ID: "song-3", Title: "Song Three", ArtistID: "artist-3", MbzRecordingID: "mbid-3"}
-
- artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
- artistRepo.On("Get", "artist-3").Return(&similarArtist, nil).Maybe()
-
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 1 && opt.Filters != nil
- })).Return(model.Artists{artist1}, nil).Once()
-
- similarAgentsResp := []agents.Artist{
- {Name: "Similar Artist", MBID: "similar-mbid"},
- }
- mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
- Return(similarAgentsResp, nil).Once()
-
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 0 && opt.Filters != nil
- })).Return(model.Artists{similarArtist}, nil).Once()
-
- mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
- Return([]agents.Song{
- {Name: "Song One", MBID: "mbid-1"},
- {Name: "Song Two", MBID: "mbid-2"},
- }, nil).Once()
-
- mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-3", "Similar Artist", "", mock.Anything).
- Return([]agents.Song{
- {Name: "Song Three", MBID: "mbid-3"},
- }, nil).Once()
-
- mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
- mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song3}, nil).Once()
-
- songs, err := provider.ArtistRadio(ctx, "artist-1", 3)
-
- Expect(err).ToNot(HaveOccurred())
- Expect(songs).To(HaveLen(3))
- for _, song := range songs {
- Expect(song.ID).To(BeElementOf("song-1", "song-2", "song-3"))
- }
- })
-
- It("returns ErrNotFound when artist is not found", func() {
- artistRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound)
- mediaFileRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound)
-
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 1 && opt.Filters != nil
- })).Return(model.Artists{}, nil).Maybe()
-
- songs, err := provider.ArtistRadio(ctx, "artist-unknown-artist", 5)
-
- Expect(err).To(Equal(model.ErrNotFound))
- Expect(songs).To(BeNil())
- })
-
- It("returns songs from main artist when GetSimilarArtists returns error", func() {
- artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
- song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
-
- artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 1 && opt.Filters != nil
- })).Return(model.Artists{artist1}, nil).Maybe()
-
- mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
- Return(nil, errors.New("error getting similar artists")).Once()
-
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 0 && opt.Filters != nil
- })).Return(model.Artists{}, nil).Once()
-
- mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
- Return([]agents.Song{
- {Name: "Song One", MBID: "mbid-1"},
- }, nil).Once()
-
- mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
-
- songs, err := provider.ArtistRadio(ctx, "artist-1", 5)
-
- Expect(err).ToNot(HaveOccurred())
- Expect(songs).To(HaveLen(1))
- Expect(songs[0].ID).To(Equal("song-1"))
- })
-
- It("returns empty list when GetArtistTopSongs returns error", func() {
- artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
-
- artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 1 && opt.Filters != nil
- })).Return(model.Artists{artist1}, nil).Maybe()
-
- mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
- Return([]agents.Artist{}, nil).Once()
-
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 0 && opt.Filters != nil
- })).Return(model.Artists{}, nil).Once()
-
- mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
- Return(nil, errors.New("error getting top songs")).Once()
-
- songs, err := provider.ArtistRadio(ctx, "artist-1", 5)
-
- Expect(err).ToNot(HaveOccurred())
- Expect(songs).To(BeEmpty())
- })
-
- It("respects count parameter", func() {
- artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
- song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
- song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"}
-
- artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 1 && opt.Filters != nil
- })).Return(model.Artists{artist1}, nil).Maybe()
-
- mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
- Return([]agents.Artist{}, nil).Once()
-
- artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
- return opt.Max == 0 && opt.Filters != nil
- })).Return(model.Artists{}, nil).Once()
-
- mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
- Return([]agents.Song{
- {Name: "Song One", MBID: "mbid-1"},
- {Name: "Song Two", MBID: "mbid-2"},
- }, nil).Once()
-
- mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
-
- songs, err := provider.ArtistRadio(ctx, "artist-1", 1)
-
- Expect(err).ToNot(HaveOccurred())
- Expect(songs).To(HaveLen(1))
- Expect(songs[0].ID).To(BeElementOf("song-1", "song-2"))
- })
-})
diff --git a/core/external/provider_matching.go b/core/external/provider_matching.go
new file mode 100644
index 000000000..74ad56d42
--- /dev/null
+++ b/core/external/provider_matching.go
@@ -0,0 +1,504 @@
+package external
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/core/agents"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/utils/str"
+ "github.com/xrash/smetrics"
+)
+
+// matchSongsToLibrary matches agent song results to local library tracks using a multi-phase
+// matching algorithm that prioritizes accuracy over recall.
+//
+// # Algorithm Overview
+//
+// The algorithm matches songs from external agents (Last.fm, Deezer, etc.) to tracks in the
+// local music library using four matching strategies in priority order:
+//
+// 1. Direct ID match: Songs with an ID field are matched directly to MediaFiles by ID
+// 2. MusicBrainz Recording ID (MBID) match: Songs with MBID are matched to tracks with
+// matching mbz_recording_id
+// 3. ISRC match: Songs with ISRC are matched to tracks with matching ISRC tag
+// 4. Title+Artist fuzzy match: Remaining songs are matched using fuzzy string comparison
+// with metadata specificity scoring
+//
+// # Matching Priority
+//
+// When selecting the final result, matches are prioritized in order: ID > MBID > ISRC > Title+Artist.
+// This ensures that more reliable identifiers take precedence over fuzzy text matching.
+//
+// # Fuzzy Matching Details
+//
+// For title+artist matching, the algorithm uses Jaro-Winkler similarity (threshold configurable
+// via SimilarSongsMatchThreshold, default 85%). Matches are ranked by:
+//
+// 1. Title similarity (Jaro-Winkler score, 0.0-1.0)
+// 2. Duration proximity (closer duration = higher score, 1.0 if unknown)
+// 3. Specificity level (0-5, based on metadata precision):
+// - Level 5: Title + Artist MBID + Album MBID (most specific)
+// - Level 4: Title + Artist MBID + Album name (fuzzy)
+// - Level 3: Title + Artist name + Album name (fuzzy)
+// - Level 2: Title + Artist MBID
+// - Level 1: Title + Artist name
+// - Level 0: Title only
+// 4. Album similarity (Jaro-Winkler, as final tiebreaker)
+//
+// # Examples
+//
+// Example 1 - MBID Priority:
+//
+// Agent returns: {Name: "Paranoid Android", MBID: "abc-123", Artist: "Radiohead"}
+// Library has: [
+// {ID: "t1", Title: "Paranoid Android", MbzRecordingID: "abc-123"},
+// {ID: "t2", Title: "Paranoid Android", Artist: "Radiohead"},
+// ]
+// Result: t1 (MBID match takes priority over title+artist)
+//
+// Example 2 - ISRC Priority:
+//
+// Agent returns: {Name: "Paranoid Android", ISRC: "GBAYE0000351", Artist: "Radiohead"}
+// Library has: [
+// {ID: "t1", Title: "Paranoid Android", Tags: {isrc: ["GBAYE0000351"]}},
+// {ID: "t2", Title: "Paranoid Android", Artist: "Radiohead"},
+// ]
+// Result: t1 (ISRC match takes priority over title+artist)
+//
+// Example 3 - Specificity Ranking:
+//
+// Agent returns: {Name: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator"}
+// Library has: [
+// {ID: "t1", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "101"}, // Level 1
+// {ID: "t2", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator"}, // Level 3
+// ]
+// Result: t2 (Level 3 beats Level 1 due to album match)
+//
+// Example 4 - Fuzzy Title Matching:
+//
+// Agent returns: {Name: "Bohemian Rhapsody", Artist: "Queen"}
+// Library has: {ID: "t1", Title: "Bohemian Rhapsody - Remastered", Artist: "Queen"}
+// With threshold=85%: Match succeeds (similarity ~0.87)
+// With threshold=100%: No match (not exact)
+//
+// # Parameters
+//
+// - ctx: Context for database operations
+// - songs: Slice of agent.Song results from external providers
+// - count: Maximum number of matches to return
+//
+// # Returns
+//
+// Returns up to 'count' MediaFiles from the library that best match the input songs,
+// preserving the original order from the agent. Songs that cannot be matched are skipped.
+func (e *provider) matchSongsToLibrary(ctx context.Context, songs []agents.Song, count int) (model.MediaFiles, error) {
+ idMatches, err := e.loadTracksByID(ctx, songs)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load tracks by ID: %w", err)
+ }
+ mbidMatches, err := e.loadTracksByMBID(ctx, songs, idMatches)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load tracks by MBID: %w", err)
+ }
+ isrcMatches, err := e.loadTracksByISRC(ctx, songs, idMatches, mbidMatches)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load tracks by ISRC: %w", err)
+ }
+ titleMatches, err := e.loadTracksByTitleAndArtist(ctx, songs, idMatches, mbidMatches, isrcMatches)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load tracks by title: %w", err)
+ }
+
+ return e.selectBestMatchingSongs(songs, idMatches, mbidMatches, isrcMatches, titleMatches, count), nil
+}
+
+// songMatchedIn checks if a song has already been matched in any of the provided match maps.
+// It checks the song's ID, MBID, and ISRC fields against the corresponding map keys.
+func songMatchedIn(s agents.Song, priorMatches ...map[string]model.MediaFile) bool {
+ _, found := lookupByIdentifiers(s, priorMatches...)
+ return found
+}
+
+// lookupByIdentifiers searches for a song's identifiers (ID, MBID, ISRC) in the provided maps.
+// Returns the first matching MediaFile found and true, or an empty MediaFile and false if no match.
+func lookupByIdentifiers(s agents.Song, maps ...map[string]model.MediaFile) (model.MediaFile, bool) {
+ keys := []string{s.ID, s.MBID, s.ISRC}
+ for _, m := range maps {
+ for _, key := range keys {
+ if key != "" {
+ if mf, ok := m[key]; ok && mf.ID != "" {
+ return mf, true
+ }
+ }
+ }
+ }
+ return model.MediaFile{}, false
+}
+
+// loadTracksByID fetches MediaFiles from the library using direct ID matching.
+// It extracts all non-empty ID fields from the input songs and performs a single
+// batch query to the database. Returns a map keyed by MediaFile ID for O(1) lookup.
+// Only non-missing files are returned.
+func (e *provider) loadTracksByID(ctx context.Context, songs []agents.Song) (map[string]model.MediaFile, error) {
+ var ids []string
+ for _, s := range songs {
+ if s.ID != "" {
+ ids = append(ids, s.ID)
+ }
+ }
+ matches := map[string]model.MediaFile{}
+ if len(ids) == 0 {
+ return matches, nil
+ }
+ res, err := e.ds.MediaFile(ctx).GetAll(model.QueryOptions{
+ Filters: squirrel.And{
+ squirrel.Eq{"media_file.id": ids},
+ squirrel.Eq{"missing": false},
+ },
+ })
+ if err != nil {
+ return matches, err
+ }
+ for _, mf := range res {
+ if _, ok := matches[mf.ID]; !ok {
+ matches[mf.ID] = mf
+ }
+ }
+ return matches, nil
+}
+
+// loadTracksByMBID fetches MediaFiles from the library using MusicBrainz Recording IDs.
+// It extracts all non-empty MBID fields from the input songs and performs a single
+// batch query against the mbz_recording_id column. Returns a map keyed by MBID for
+// O(1) lookup. Only non-missing files are returned.
+func (e *provider) loadTracksByMBID(ctx context.Context, songs []agents.Song, priorMatches ...map[string]model.MediaFile) (map[string]model.MediaFile, error) {
+ var mbids []string
+ for _, s := range songs {
+ if s.MBID != "" && !songMatchedIn(s, priorMatches...) {
+ mbids = append(mbids, s.MBID)
+ }
+ }
+ matches := map[string]model.MediaFile{}
+ if len(mbids) == 0 {
+ return matches, nil
+ }
+ res, err := e.ds.MediaFile(ctx).GetAll(model.QueryOptions{
+ Filters: squirrel.And{
+ squirrel.Eq{"mbz_recording_id": mbids},
+ squirrel.Eq{"missing": false},
+ },
+ })
+ if err != nil {
+ return matches, err
+ }
+ for _, mf := range res {
+ if id := mf.MbzRecordingID; id != "" {
+ if _, ok := matches[id]; !ok {
+ matches[id] = mf
+ }
+ }
+ }
+ return matches, nil
+}
+
+// loadTracksByISRC fetches MediaFiles from the library using ISRC (International Standard
+// Recording Code) matching. It extracts all non-empty ISRC fields from the input songs and
+// queries the tags JSON column for matching ISRC values. Returns a map keyed by ISRC for
+// O(1) lookup. Only non-missing files are returned.
+func (e *provider) loadTracksByISRC(ctx context.Context, songs []agents.Song, priorMatches ...map[string]model.MediaFile) (map[string]model.MediaFile, error) {
+ var isrcs []string
+ for _, s := range songs {
+ if s.ISRC != "" && !songMatchedIn(s, priorMatches...) {
+ isrcs = append(isrcs, s.ISRC)
+ }
+ }
+ matches := map[string]model.MediaFile{}
+ if len(isrcs) == 0 {
+ return matches, nil
+ }
+ res, err := e.ds.MediaFile(ctx).GetAllByTags(model.TagISRC, isrcs, model.QueryOptions{
+ Filters: squirrel.Eq{"missing": false},
+ })
+ if err != nil {
+ return matches, err
+ }
+ for _, mf := range res {
+ for _, isrc := range mf.Tags.Values(model.TagISRC) {
+ if _, ok := matches[isrc]; !ok {
+ matches[isrc] = mf
+ }
+ }
+ }
+ return matches, nil
+}
+
+// songQuery represents a normalized query for matching a song to library tracks.
+// All string fields are sanitized (lowercased, diacritics removed) for comparison.
+// This struct is used internally by loadTracksByTitleAndArtist to group queries by artist.
+type songQuery struct {
+ title string // Sanitized song title
+ artist string // Sanitized artist name (without articles like "The")
+ artistMBID string // MusicBrainz Artist ID (optional, for higher specificity matching)
+ album string // Sanitized album name (optional, for specificity scoring)
+ albumMBID string // MusicBrainz Album ID (optional, for highest specificity matching)
+ durationMs uint32 // Duration in milliseconds (0 means unknown, skip duration filtering)
+}
+
+// matchScore combines title/album similarity with metadata specificity for ranking matches
+type matchScore struct {
+ titleSimilarity float64 // 0.0-1.0 (Jaro-Winkler)
+ durationProximity float64 // 0.0-1.0 (closer duration = higher, 1.0 if unknown)
+ albumSimilarity float64 // 0.0-1.0 (Jaro-Winkler), used as tiebreaker
+ specificityLevel int // 0-5 (higher = more specific metadata match)
+}
+
+// betterThan returns true if this score beats another.
+// Comparison order: title similarity > duration proximity > specificity level > album similarity
+func (s matchScore) betterThan(other matchScore) bool {
+ if s.titleSimilarity != other.titleSimilarity {
+ return s.titleSimilarity > other.titleSimilarity
+ }
+ if s.durationProximity != other.durationProximity {
+ return s.durationProximity > other.durationProximity
+ }
+ if s.specificityLevel != other.specificityLevel {
+ return s.specificityLevel > other.specificityLevel
+ }
+ return s.albumSimilarity > other.albumSimilarity
+}
+
+// computeSpecificityLevel determines how well query metadata matches a track (0-5).
+// Higher values indicate more specific matches (MBIDs > names > title only).
+// Uses fuzzy matching for album names with the same threshold as title matching.
+func computeSpecificityLevel(q songQuery, mf model.MediaFile, albumThreshold float64) int {
+ title := str.SanitizeFieldForSorting(mf.Title)
+ artist := str.SanitizeFieldForSortingNoArticle(mf.Artist)
+ album := str.SanitizeFieldForSorting(mf.Album)
+
+ // Level 5: Title + Artist MBID + Album MBID (most specific)
+ if q.artistMBID != "" && q.albumMBID != "" &&
+ mf.MbzArtistID == q.artistMBID && mf.MbzAlbumID == q.albumMBID {
+ return 5
+ }
+ // Level 4: Title + Artist MBID + Album name (fuzzy)
+ if q.artistMBID != "" && q.album != "" &&
+ mf.MbzArtistID == q.artistMBID && similarityRatio(album, q.album) >= albumThreshold {
+ return 4
+ }
+ // Level 3: Title + Artist name + Album name (fuzzy)
+ if q.artist != "" && q.album != "" &&
+ artist == q.artist && similarityRatio(album, q.album) >= albumThreshold {
+ return 3
+ }
+ // Level 2: Title + Artist MBID
+ if q.artistMBID != "" && mf.MbzArtistID == q.artistMBID {
+ return 2
+ }
+ // Level 1: Title + Artist name
+ if q.artist != "" && artist == q.artist {
+ return 1
+ }
+ // Level 0: Title only match (but for fuzzy, title matched via similarity)
+ // Check if at least the title matches exactly
+ if title == q.title {
+ return 0
+ }
+ return -1 // No exact title match, but could still be a fuzzy match
+}
+
+// loadTracksByTitleAndArtist loads tracks matching by title with optional artist/album filtering.
+// Uses a unified scoring approach that combines title similarity (Jaro-Winkler) with
+// metadata specificity (MBIDs, album names) for both exact and fuzzy matches.
+// Returns a map keyed by "title|artist" for compatibility with selectBestMatchingSongs.
+func (e *provider) loadTracksByTitleAndArtist(ctx context.Context, songs []agents.Song, priorMatches ...map[string]model.MediaFile) (map[string]model.MediaFile, error) {
+ queries := e.buildTitleQueries(songs, priorMatches...)
+ if len(queries) == 0 {
+ return map[string]model.MediaFile{}, nil
+ }
+
+ threshold := float64(conf.Server.SimilarSongsMatchThreshold) / 100.0
+
+ // Group queries by artist for efficient DB access
+ byArtist := map[string][]songQuery{}
+ for _, q := range queries {
+ if q.artist != "" {
+ byArtist[q.artist] = append(byArtist[q.artist], q)
+ }
+ }
+
+ matches := map[string]model.MediaFile{}
+ for artist, artistQueries := range byArtist {
+ // Single DB query per artist - get all their tracks
+ tracks, err := e.ds.MediaFile(ctx).GetAll(model.QueryOptions{
+ Filters: squirrel.And{
+ squirrel.Eq{"order_artist_name": artist},
+ squirrel.Eq{"missing": false},
+ },
+ Sort: "starred desc, rating desc, year asc, compilation asc",
+ })
+ if err != nil {
+ continue
+ }
+
+ // Find best match for each query using unified scoring
+ for _, q := range artistQueries {
+ if mf, found := e.findBestMatch(q, tracks, threshold); found {
+ key := q.title + "|" + q.artist
+ if _, exists := matches[key]; !exists {
+ matches[key] = mf
+ }
+ }
+ }
+ }
+ return matches, nil
+}
+
+// durationProximity returns a score from 0.0 to 1.0 indicating how close
+// the track's duration is to the target. A perfect match returns 1.0, and the
+// score decreases as the difference grows (using 1 / (1 + diff)). Returns 1.0
+// if durationMs is 0 (unknown), so duration does not influence scoring.
+func durationProximity(durationMs uint32, mediaFileDurationSec float32) float64 {
+ if durationMs <= 0 {
+ return 1.0 // Unknown duration — don't penalise
+ }
+ durationSec := float64(durationMs) / 1000.0
+ diff := math.Abs(durationSec - float64(mediaFileDurationSec))
+ return 1.0 / (1.0 + diff)
+}
+
+// findBestMatch finds the best matching track using combined title/album similarity and specificity scoring.
+// A track must meet the threshold for title similarity, then the best match is chosen by:
+// 1. Highest title similarity
+// 2. Duration proximity (closer duration = higher score, 1.0 if unknown)
+// 3. Highest specificity level
+// 4. Highest album similarity (as final tiebreaker)
+func (e *provider) findBestMatch(q songQuery, tracks model.MediaFiles, threshold float64) (model.MediaFile, bool) {
+ var bestMatch model.MediaFile
+ bestScore := matchScore{titleSimilarity: -1}
+ found := false
+
+ for _, mf := range tracks {
+ trackTitle := str.SanitizeFieldForSorting(mf.Title)
+ titleSim := similarityRatio(q.title, trackTitle)
+
+ if titleSim < threshold {
+ continue
+ }
+
+ // Compute album similarity for tiebreaking (0.0 if no album in query)
+ var albumSim float64
+ if q.album != "" {
+ trackAlbum := str.SanitizeFieldForSorting(mf.Album)
+ albumSim = similarityRatio(q.album, trackAlbum)
+ }
+
+ score := matchScore{
+ titleSimilarity: titleSim,
+ durationProximity: durationProximity(q.durationMs, mf.Duration),
+ albumSimilarity: albumSim,
+ specificityLevel: computeSpecificityLevel(q, mf, threshold),
+ }
+
+ if score.betterThan(bestScore) {
+ bestScore = score
+ bestMatch = mf
+ found = true
+ }
+ }
+ return bestMatch, found
+}
+
+// buildTitleQueries converts agent songs into normalized songQuery structs for title+artist matching.
+// It skips songs that have already been matched in prior phases (by ID, MBID, or ISRC) and sanitizes
+// all string fields for consistent comparison (lowercase, diacritics removed, articles stripped from artist names).
+func (e *provider) buildTitleQueries(songs []agents.Song, priorMatches ...map[string]model.MediaFile) []songQuery {
+ var queries []songQuery
+ for _, s := range songs {
+ if songMatchedIn(s, priorMatches...) {
+ continue
+ }
+ queries = append(queries, songQuery{
+ title: str.SanitizeFieldForSorting(s.Name),
+ artist: str.SanitizeFieldForSortingNoArticle(s.Artist),
+ artistMBID: s.ArtistMBID,
+ album: str.SanitizeFieldForSorting(s.Album),
+ albumMBID: s.AlbumMBID,
+ durationMs: s.Duration,
+ })
+ }
+ return queries
+}
+
+// selectBestMatchingSongs assembles the final result by mapping input songs to their best matching
+// library tracks. It iterates through the input songs in order and selects the first available match
+// using priority order: ID > MBID > ISRC > title+artist.
+//
+// The function also handles deduplication: when multiple different input songs would match the same
+// library track (e.g., "Song (Live)" and "Song (Remastered)" both matching "Song (Live)" in the library),
+// only the first match is kept. However, if the same input song appears multiple times (intentional
+// repetition), duplicates are preserved in the output.
+//
+// Returns up to 'count' MediaFiles, preserving the input order. Songs that cannot be matched are skipped.
+func (e *provider) selectBestMatchingSongs(songs []agents.Song, byID, byMBID, byISRC, byTitleArtist map[string]model.MediaFile, count int) model.MediaFiles {
+ mfs := make(model.MediaFiles, 0, len(songs))
+ // Track MediaFile.ID -> input song that added it, for deduplication
+ addedBy := make(map[string]agents.Song, len(songs))
+
+ for _, t := range songs {
+ if len(mfs) == count {
+ break
+ }
+
+ mf, found := findMatchingTrack(t, byID, byMBID, byISRC, byTitleArtist)
+ if !found {
+ continue
+ }
+
+ // Check for duplicate library track
+ if prevSong, alreadyAdded := addedBy[mf.ID]; alreadyAdded {
+ // Only add duplicate if input songs are identical
+ if t != prevSong {
+ continue // Different input songs → skip mismatch-induced duplicate
+ }
+ } else {
+ addedBy[mf.ID] = t
+ }
+
+ mfs = append(mfs, mf)
+ }
+ return mfs
+}
+
+// findMatchingTrack looks up a song in the match maps using priority order: ID > MBID > ISRC > title+artist.
+// Returns the matched MediaFile and true if found, or an empty MediaFile and false if no match exists.
+func findMatchingTrack(t agents.Song, byID, byMBID, byISRC, byTitleArtist map[string]model.MediaFile) (model.MediaFile, bool) {
+ // Try identifier-based matches first (ID, MBID, ISRC)
+ if mf, found := lookupByIdentifiers(t, byID, byMBID, byISRC); found {
+ return mf, true
+ }
+ // Fall back to title+artist fuzzy match
+ key := str.SanitizeFieldForSorting(t.Name) + "|" + str.SanitizeFieldForSortingNoArticle(t.Artist)
+ if mf, ok := byTitleArtist[key]; ok {
+ return mf, true
+ }
+ return model.MediaFile{}, false
+}
+
+// similarityRatio calculates the similarity between two strings using Jaro-Winkler algorithm.
+// Returns a value between 0.0 (completely different) and 1.0 (identical).
+// Jaro-Winkler is well-suited for matching song titles because it gives higher scores
+// when strings share a common prefix (e.g., "Song Title" vs "Song Title - Remastered").
+func similarityRatio(a, b string) float64 {
+ if a == b {
+ return 1.0
+ }
+ if len(a) == 0 || len(b) == 0 {
+ return 0.0
+ }
+ // JaroWinkler params: boostThreshold=0.7, prefixSize=4
+ return smetrics.JaroWinkler(a, b, 0.7, 4)
+}
diff --git a/core/external/provider_matching_internal_test.go b/core/external/provider_matching_internal_test.go
new file mode 100644
index 000000000..5b9ccea3b
--- /dev/null
+++ b/core/external/provider_matching_internal_test.go
@@ -0,0 +1,57 @@
+package external
+
+import (
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("similarityRatio", func() {
+ It("returns 1.0 for identical strings", func() {
+ Expect(similarityRatio("hello", "hello")).To(BeNumerically("==", 1.0))
+ })
+
+ It("returns 0.0 for empty strings", func() {
+ Expect(similarityRatio("", "test")).To(BeNumerically("==", 0.0))
+ Expect(similarityRatio("test", "")).To(BeNumerically("==", 0.0))
+ })
+
+ It("returns high similarity for remastered suffix", func() {
+ // Jaro-Winkler gives ~0.92 for this case
+ ratio := similarityRatio("paranoid android", "paranoid android remastered")
+ Expect(ratio).To(BeNumerically(">=", 0.85))
+ })
+
+ It("returns high similarity for suffix additions like (Live)", func() {
+ // Jaro-Winkler gives ~0.96 for this case
+ ratio := similarityRatio("bohemian rhapsody", "bohemian rhapsody live")
+ Expect(ratio).To(BeNumerically(">=", 0.90))
+ })
+
+ It("returns high similarity for 'yesterday' variants (common prefix)", func() {
+ // Jaro-Winkler gives ~0.90 because of common prefix
+ ratio := similarityRatio("yesterday", "yesterday once more")
+ Expect(ratio).To(BeNumerically(">=", 0.85))
+ })
+
+ It("returns low similarity for same suffix", func() {
+ // Jaro-Winkler gives ~0.70 for this case
+ ratio := similarityRatio("postman (live)", "taxman (live)")
+ Expect(ratio).To(BeNumerically("<", 0.85))
+ })
+
+ It("handles unicode characters", func() {
+ ratio := similarityRatio("dont stop believin", "don't stop believin'")
+ Expect(ratio).To(BeNumerically(">=", 0.85))
+ })
+
+ It("returns low similarity for completely different strings", func() {
+ ratio := similarityRatio("abc", "xyz")
+ Expect(ratio).To(BeNumerically("<", 0.5))
+ })
+
+ It("is symmetric", func() {
+ ratio1 := similarityRatio("hello world", "hello")
+ ratio2 := similarityRatio("hello", "hello world")
+ Expect(ratio1).To(Equal(ratio2))
+ })
+})
diff --git a/core/external/provider_matching_test.go b/core/external/provider_matching_test.go
new file mode 100644
index 000000000..b3624ef3a
--- /dev/null
+++ b/core/external/provider_matching_test.go
@@ -0,0 +1,762 @@
+package external_test
+
+import (
+ "context"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/core/agents"
+ . "github.com/navidrome/navidrome/core/external"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/stretchr/testify/mock"
+)
+
+var _ = Describe("Provider - Song Matching", func() {
+ var ds model.DataStore
+ var provider Provider
+ var agentsCombined *mockAgents
+ var artistRepo *mockArtistRepo
+ var mediaFileRepo *mockMediaFileRepo
+ var albumRepo *mockAlbumRepo
+ var ctx context.Context
+
+ BeforeEach(func() {
+ ctx = GinkgoT().Context()
+
+ artistRepo = newMockArtistRepo()
+ mediaFileRepo = newMockMediaFileRepo()
+ albumRepo = newMockAlbumRepo()
+
+ ds = &tests.MockDataStore{
+ MockedArtist: artistRepo,
+ MockedMediaFile: mediaFileRepo,
+ MockedAlbum: albumRepo,
+ }
+
+ agentsCombined = &mockAgents{}
+ provider = NewProvider(ds, agentsCombined)
+ })
+
+ // Shared helper for tests that only need artist track queries (no ID/MBID matching)
+ setupSimilarSongsExpectations := func(returnedSongs []agents.Song, artistTracks model.MediaFiles) {
+ agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
+ Return(returnedSongs, nil).Once()
+
+ // loadTracksByTitleAndArtist - queries by artist name
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ and, ok := opt.Filters.(squirrel.And)
+ if !ok || len(and) < 2 {
+ return false
+ }
+ eq, hasEq := and[0].(squirrel.Eq)
+ if !hasEq {
+ return false
+ }
+ _, hasArtist := eq["order_artist_name"]
+ return hasArtist
+ })).Return(artistTracks, nil).Maybe()
+ }
+
+ Describe("matchSongsToLibrary priority matching", func() {
+ var track model.MediaFile
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ // Disable fuzzy matching for these tests to avoid unexpected GetAll calls
+ conf.Server.SimilarSongsMatchThreshold = 100
+
+ track = model.MediaFile{ID: "track-1", Title: "Test Track", Artist: "Test Artist", MbzRecordingID: ""}
+
+ // Setup for GetEntityByID to return the track
+ artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once()
+ })
+
+ setupExpectations := func(returnedSongs []agents.Song, idMatches, mbidMatches, artistTracks model.MediaFiles) {
+ agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
+ Return(returnedSongs, nil).Once()
+
+ // loadTracksByID
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ _, ok := opt.Filters.(squirrel.Eq)
+ return ok
+ })).Return(idMatches, nil).Once()
+
+ // loadTracksByMBID
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ and, ok := opt.Filters.(squirrel.And)
+ if !ok || len(and) < 1 {
+ return false
+ }
+ eq, hasEq := and[0].(squirrel.Eq)
+ if !hasEq {
+ return false
+ }
+ _, hasMBID := eq["mbz_recording_id"]
+ return hasMBID
+ })).Return(mbidMatches, nil).Once()
+
+ // loadTracksByTitleAndArtist - now queries by artist name
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ and, ok := opt.Filters.(squirrel.And)
+ if !ok || len(and) < 2 {
+ return false
+ }
+ eq, hasEq := and[0].(squirrel.Eq)
+ if !hasEq {
+ return false
+ }
+ _, hasArtist := eq["order_artist_name"]
+ return hasArtist
+ })).Return(artistTracks, nil).Maybe()
+ }
+
+ Context("when agent returns artist and album metadata", func() {
+ It("matches by title + artist MBID + album MBID (highest priority)", func() {
+ // Song in library with all MBIDs
+ correctMatch := model.MediaFile{
+ ID: "correct-match", Title: "Similar Song", Artist: "Depeche Mode", Album: "Violator",
+ MbzArtistID: "artist-mbid-123", MbzAlbumID: "album-mbid-456",
+ }
+ // Another song with same title but different MBIDs (should NOT match)
+ wrongMatch := model.MediaFile{
+ ID: "wrong-match", Title: "Similar Song", Artist: "Depeche Mode", Album: "Some Other Album",
+ MbzArtistID: "artist-mbid-123", MbzAlbumID: "different-album-mbid",
+ }
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Depeche Mode", ArtistMBID: "artist-mbid-123", Album: "Violator", AlbumMBID: "album-mbid-456"},
+ }
+
+ setupExpectations(returnedSongs, model.MediaFiles{}, model.MediaFiles{}, model.MediaFiles{wrongMatch, correctMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("correct-match"))
+ })
+
+ It("matches by title + artist name + album name when MBIDs unavailable", func() {
+ // Song in library without MBIDs but with matching artist/album names
+ correctMatch := model.MediaFile{
+ ID: "correct-match", Title: "Similar Song", Artist: "depeche mode", Album: "violator",
+ }
+ // Another song with same title but different artist (should NOT match)
+ wrongMatch := model.MediaFile{
+ ID: "wrong-match", Title: "Similar Song", Artist: "Other Artist", Album: "Other Album",
+ }
+
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Depeche Mode", Album: "Violator"}, // No MBIDs
+ }
+
+ setupExpectations(returnedSongs, model.MediaFiles{}, model.MediaFiles{}, model.MediaFiles{wrongMatch, correctMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("correct-match"))
+ })
+
+ It("matches by title + artist only when album info unavailable", func() {
+ // Song in library with matching artist
+ correctMatch := model.MediaFile{
+ ID: "correct-match", Title: "Similar Song", Artist: "depeche mode", Album: "Some Album",
+ }
+ // Another song with same title but different artist
+ wrongMatch := model.MediaFile{
+ ID: "wrong-match", Title: "Similar Song", Artist: "Other Artist", Album: "Other Album",
+ }
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Depeche Mode"}, // No album info
+ }
+
+ setupExpectations(returnedSongs, model.MediaFiles{}, model.MediaFiles{}, model.MediaFiles{wrongMatch, correctMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("correct-match"))
+ })
+
+ It("does not match songs without artist info", func() {
+ // Songs without artist info cannot be matched since we query by artist
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song"}, // No artist/album info at all
+ }
+
+ // No artist to query, so no GetAll calls for title matching
+ setupExpectations(returnedSongs, model.MediaFiles{}, model.MediaFiles{}, model.MediaFiles{})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(BeEmpty())
+ })
+ })
+
+ Context("when matching multiple songs with the same title but different artists", func() {
+ It("returns distinct matches for each artist's version (covers scenario)", func() {
+ // Multiple covers of the same song by different artists
+ cover1 := model.MediaFile{
+ ID: "cover-1", Title: "Yesterday", Artist: "The Beatles", Album: "Help!",
+ }
+ cover2 := model.MediaFile{
+ ID: "cover-2", Title: "Yesterday", Artist: "Ray Charles", Album: "Greatest Hits",
+ }
+ cover3 := model.MediaFile{
+ ID: "cover-3", Title: "Yesterday", Artist: "Frank Sinatra", Album: "My Way",
+ }
+
+ returnedSongs := []agents.Song{
+ {Name: "Yesterday", Artist: "The Beatles", Album: "Help!"},
+ {Name: "Yesterday", Artist: "Ray Charles", Album: "Greatest Hits"},
+ {Name: "Yesterday", Artist: "Frank Sinatra", Album: "My Way"},
+ }
+
+ setupExpectations(returnedSongs, model.MediaFiles{}, model.MediaFiles{}, model.MediaFiles{cover1, cover2, cover3})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ // All three covers should be returned, not just the first one
+ Expect(songs).To(HaveLen(3))
+ // Verify all three different versions are included
+ ids := []string{songs[0].ID, songs[1].ID, songs[2].ID}
+ Expect(ids).To(ContainElements("cover-1", "cover-2", "cover-3"))
+ })
+ })
+
+ Context("when matching multiple songs with different precision levels", func() {
+ It("prefers more precise matches for each song", func() {
+ // Library has multiple versions of same song
+ preciseMatch := model.MediaFile{
+ ID: "precise", Title: "Song A", Artist: "Artist One", Album: "Album One",
+ MbzArtistID: "mbid-1", MbzAlbumID: "album-mbid-1",
+ }
+ lessAccurateMatch := model.MediaFile{
+ ID: "less-accurate", Title: "Song A", Artist: "Artist One", Album: "Compilation",
+ MbzArtistID: "mbid-1",
+ }
+ artistTwoMatch := model.MediaFile{
+ ID: "artist-two", Title: "Song B", Artist: "Artist Two",
+ }
+
+ returnedSongs := []agents.Song{
+ {Name: "Song A", Artist: "Artist One", ArtistMBID: "mbid-1", Album: "Album One", AlbumMBID: "album-mbid-1"},
+ {Name: "Song B", Artist: "Artist Two"}, // Different artist
+ }
+
+ setupExpectations(returnedSongs, model.MediaFiles{}, model.MediaFiles{}, model.MediaFiles{lessAccurateMatch, preciseMatch, artistTwoMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(2))
+ // First song should be the precise match (has all MBIDs)
+ Expect(songs[0].ID).To(Equal("precise"))
+ // Second song matches by title + artist
+ Expect(songs[1].ID).To(Equal("artist-two"))
+ })
+ })
+ })
+
+ Describe("Fuzzy matching fallback", func() {
+ var track model.MediaFile
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ track = model.MediaFile{ID: "track-1", Title: "Test Track", Artist: "Test Artist"}
+
+ // Setup for GetEntityByID to return the track
+ artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once()
+ })
+
+ Context("with default threshold (85%)", func() {
+ It("matches songs with remastered suffix", func() {
+ conf.Server.SimilarSongsMatchThreshold = 85
+
+ // Agent returns "Paranoid Android" but library has "Paranoid Android - Remastered"
+ returnedSongs := []agents.Song{
+ {Name: "Paranoid Android", Artist: "Radiohead"},
+ }
+ // Artist catalog has the remastered version (fuzzy match will find it)
+ artistTracks := model.MediaFiles{
+ {ID: "remastered", Title: "Paranoid Android - Remastered", Artist: "Radiohead"},
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, artistTracks)
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("remastered"))
+ })
+
+ It("matches songs with live suffix", func() {
+ conf.Server.SimilarSongsMatchThreshold = 85
+
+ returnedSongs := []agents.Song{
+ {Name: "Bohemian Rhapsody", Artist: "Queen"},
+ }
+ artistTracks := model.MediaFiles{
+ {ID: "live", Title: "Bohemian Rhapsody (Live)", Artist: "Queen"},
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, artistTracks)
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("live"))
+ })
+
+ It("does not match completely different songs", func() {
+ conf.Server.SimilarSongsMatchThreshold = 85
+
+ returnedSongs := []agents.Song{
+ {Name: "Yesterday", Artist: "The Beatles"},
+ }
+ // Artist catalog has completely different songs
+ artistTracks := model.MediaFiles{
+ {ID: "different", Title: "Tomorrow Never Knows", Artist: "The Beatles"},
+ {ID: "different2", Title: "Here Comes The Sun", Artist: "The Beatles"},
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, artistTracks)
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(BeEmpty())
+ })
+ })
+
+ Context("with threshold set to 100 (exact match only)", func() {
+ It("only matches exact titles", func() {
+ conf.Server.SimilarSongsMatchThreshold = 100
+
+ returnedSongs := []agents.Song{
+ {Name: "Paranoid Android", Artist: "Radiohead"},
+ }
+ // Artist catalog has only remastered version - no exact match
+ artistTracks := model.MediaFiles{
+ {ID: "remastered", Title: "Paranoid Android - Remastered", Artist: "Radiohead"},
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, artistTracks)
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(BeEmpty())
+ })
+ })
+
+ Context("with lower threshold (75%)", func() {
+ It("matches more aggressively", func() {
+ conf.Server.SimilarSongsMatchThreshold = 75
+
+ returnedSongs := []agents.Song{
+ {Name: "Song", Artist: "Artist"},
+ }
+ artistTracks := model.MediaFiles{
+ {ID: "extended", Title: "Song (Extended Mix)", Artist: "Artist"},
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, artistTracks)
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("extended"))
+ })
+ })
+
+ Context("with fuzzy album matching", func() {
+ It("matches album with (Remaster) suffix", func() {
+ conf.Server.SimilarSongsMatchThreshold = 85
+
+ // Agent returns "A Night at the Opera" but library has remastered version
+ returnedSongs := []agents.Song{
+ {Name: "Bohemian Rhapsody", Artist: "Queen", Album: "A Night at the Opera"},
+ }
+ // Library has same album with remaster suffix
+ correctMatch := model.MediaFile{
+ ID: "correct", Title: "Bohemian Rhapsody", Artist: "Queen", Album: "A Night at the Opera (2011 Remaster)",
+ }
+ wrongMatch := model.MediaFile{
+ ID: "wrong", Title: "Bohemian Rhapsody", Artist: "Queen", Album: "Greatest Hits",
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{wrongMatch, correctMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ // Should prefer the fuzzy album match (Level 3) over title+artist only (Level 1)
+ Expect(songs[0].ID).To(Equal("correct"))
+ })
+
+ It("matches album with (Deluxe Edition) suffix", func() {
+ conf.Server.SimilarSongsMatchThreshold = 85
+
+ returnedSongs := []agents.Song{
+ {Name: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator"},
+ }
+ correctMatch := model.MediaFile{
+ ID: "correct", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator (Deluxe Edition)",
+ }
+ wrongMatch := model.MediaFile{
+ ID: "wrong", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "101",
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{wrongMatch, correctMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("correct"))
+ })
+
+ It("prefers exact album match over fuzzy album match", func() {
+ conf.Server.SimilarSongsMatchThreshold = 85
+
+ returnedSongs := []agents.Song{
+ {Name: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator"},
+ }
+ exactMatch := model.MediaFile{
+ ID: "exact", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator",
+ }
+ fuzzyMatch := model.MediaFile{
+ ID: "fuzzy", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator (Deluxe Edition)",
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{fuzzyMatch, exactMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ // Both have same title similarity (1.0), so should prefer exact album match (higher specificity via higher album similarity)
+ Expect(songs[0].ID).To(Equal("exact"))
+ })
+ })
+ })
+
+ Describe("Duration matching", func() {
+ var track model.MediaFile
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.SimilarSongsMatchThreshold = 100 // Exact title match for predictable tests
+
+ track = model.MediaFile{ID: "track-1", Title: "Test Track", Artist: "Test Artist"}
+
+ // Setup for GetEntityByID to return the track
+ artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once()
+ })
+
+ Context("when agent provides duration", func() {
+ It("prefers tracks with matching duration", func() {
+ // Agent returns song with duration 180000ms (180 seconds)
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Test Artist", Duration: 180000},
+ }
+ // Library has two versions: one matching duration, one not
+ correctMatch := model.MediaFile{
+ ID: "correct", Title: "Similar Song", Artist: "Test Artist", Duration: 180.0,
+ }
+ wrongDuration := model.MediaFile{
+ ID: "wrong", Title: "Similar Song", Artist: "Test Artist", Duration: 240.0,
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{wrongDuration, correctMatch})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("correct"))
+ })
+
+ It("matches tracks with close duration", func() {
+ // Agent returns song with duration 180000ms (180 seconds)
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Test Artist", Duration: 180000},
+ }
+ // Library has track with 182.5 seconds (close to target)
+ closeDuration := model.MediaFile{
+ ID: "close-duration", Title: "Similar Song", Artist: "Test Artist", Duration: 182.5,
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{closeDuration})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("close-duration"))
+ })
+
+ It("prefers closer duration over farther duration", func() {
+ // Agent returns song with duration 180000ms (180 seconds)
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Test Artist", Duration: 180000},
+ }
+ // Library has one close, one far
+ closeDuration := model.MediaFile{
+ ID: "close", Title: "Similar Song", Artist: "Test Artist", Duration: 181.0,
+ }
+ farDuration := model.MediaFile{
+ ID: "far", Title: "Similar Song", Artist: "Test Artist", Duration: 190.0,
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{farDuration, closeDuration})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("close"))
+ })
+
+ It("still matches when no tracks have matching duration", func() {
+ // Agent returns song with duration 180000ms
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Test Artist", Duration: 180000},
+ }
+ // Library only has tracks with very different duration
+ differentDuration := model.MediaFile{
+ ID: "different", Title: "Similar Song", Artist: "Test Artist", Duration: 300.0,
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{differentDuration})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ // Duration mismatch doesn't exclude the track; it's just scored lower
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("different"))
+ })
+
+ It("prefers title match over duration match when titles differ", func() {
+ // Agent returns "Similar Song" with duration 180000ms
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Test Artist", Duration: 180000},
+ }
+ // Library has:
+ // - differentTitle: matches duration but has different title (won't pass title threshold)
+ // - correctTitle: doesn't match duration but has correct title (wins on title similarity)
+ differentTitle := model.MediaFile{
+ ID: "wrong-title", Title: "Different Song", Artist: "Test Artist", Duration: 180.0,
+ }
+ correctTitle := model.MediaFile{
+ ID: "correct-title", Title: "Similar Song", Artist: "Test Artist", Duration: 300.0,
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{differentTitle, correctTitle})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ // Title similarity is the top priority, so the correct title wins despite duration mismatch
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("correct-title"))
+ })
+ })
+
+ Context("when agent does not provide duration", func() {
+ It("matches without duration filtering (duration=0)", func() {
+ // Agent returns song without duration
+ returnedSongs := []agents.Song{
+ {Name: "Similar Song", Artist: "Test Artist", Duration: 0},
+ }
+ // Library tracks with various durations should all be candidates
+ anyTrack := model.MediaFile{
+ ID: "any", Title: "Similar Song", Artist: "Test Artist", Duration: 999.0,
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{anyTrack})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("any"))
+ })
+ })
+
+ Context("edge cases", func() {
+ It("handles very short songs with close duration", func() {
+ // 30-second song with 1-second difference
+ returnedSongs := []agents.Song{
+ {Name: "Short Song", Artist: "Test Artist", Duration: 30000},
+ }
+ shortTrack := model.MediaFile{
+ ID: "short", Title: "Short Song", Artist: "Test Artist", Duration: 31.0,
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{shortTrack})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("short"))
+ })
+ })
+ })
+
+ Describe("Deduplication of mismatched songs", func() {
+ var track model.MediaFile
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.SimilarSongsMatchThreshold = 85 // Allow fuzzy matching
+
+ track = model.MediaFile{ID: "track-1", Title: "Test Track", Artist: "Test Artist"}
+
+ // Setup for GetEntityByID to return the track
+ artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once()
+ })
+
+ It("removes duplicates when different input songs match the same library track", func() {
+ // Agent returns two different versions that will both fuzzy-match to the same library track
+ returnedSongs := []agents.Song{
+ {Name: "Bohemian Rhapsody (Live)", Artist: "Queen"},
+ {Name: "Bohemian Rhapsody (Original Mix)", Artist: "Queen"},
+ }
+ // Library only has one version
+ libraryTrack := model.MediaFile{
+ ID: "br-live", Title: "Bohemian Rhapsody (Live)", Artist: "Queen",
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{libraryTrack})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ // Should only return one track, not two duplicates
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("br-live"))
+ })
+
+ It("preserves duplicates when identical input songs match the same library track", func() {
+ // Agent returns the exact same song twice (intentional repetition)
+ returnedSongs := []agents.Song{
+ {Name: "Bohemian Rhapsody", Artist: "Queen", Album: "A Night at the Opera"},
+ {Name: "Bohemian Rhapsody", Artist: "Queen", Album: "A Night at the Opera"},
+ }
+ // Library has matching track
+ libraryTrack := model.MediaFile{
+ ID: "br", Title: "Bohemian Rhapsody", Artist: "Queen", Album: "A Night at the Opera",
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{libraryTrack})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ // Should return two tracks since input songs were identical
+ Expect(songs).To(HaveLen(2))
+ Expect(songs[0].ID).To(Equal("br"))
+ Expect(songs[1].ID).To(Equal("br"))
+ })
+
+ It("handles mixed scenario with both identical and different input songs", func() {
+ // Agent returns: Song A, Song B (different from A), Song A again (same as first)
+ // All three match to the same library track
+ returnedSongs := []agents.Song{
+ {Name: "Yesterday", Artist: "The Beatles", Album: "Help!"},
+ {Name: "Yesterday (Remastered)", Artist: "The Beatles", Album: "1"}, // Different version
+ {Name: "Yesterday", Artist: "The Beatles", Album: "Help!"}, // Same as first
+ {Name: "Yesterday (Anthology)", Artist: "The Beatles", Album: "Anthology"}, // Another different version
+ }
+ // Library only has one version
+ libraryTrack := model.MediaFile{
+ ID: "yesterday", Title: "Yesterday", Artist: "The Beatles", Album: "Help!",
+ }
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{libraryTrack})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ // Should return 2 tracks:
+ // 1. First "Yesterday" (original)
+ // 2. Third "Yesterday" (same as first, so kept)
+ // Skip: Second "Yesterday (Remastered)" (different input, same library track)
+ // Skip: Fourth "Yesterday (Anthology)" (different input, same library track)
+ Expect(songs).To(HaveLen(2))
+ Expect(songs[0].ID).To(Equal("yesterday"))
+ Expect(songs[1].ID).To(Equal("yesterday"))
+ })
+
+ It("does not deduplicate songs that match different library tracks", func() {
+ // Agent returns different songs that match different library tracks
+ returnedSongs := []agents.Song{
+ {Name: "Song A", Artist: "Artist"},
+ {Name: "Song B", Artist: "Artist"},
+ {Name: "Song C", Artist: "Artist"},
+ }
+ // Library has all three songs
+ trackA := model.MediaFile{ID: "track-a", Title: "Song A", Artist: "Artist"}
+ trackB := model.MediaFile{ID: "track-b", Title: "Song B", Artist: "Artist"}
+ trackC := model.MediaFile{ID: "track-c", Title: "Song C", Artist: "Artist"}
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{trackA, trackB, trackC})
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ // All three should be returned since they match different library tracks
+ Expect(songs).To(HaveLen(3))
+ Expect(songs[0].ID).To(Equal("track-a"))
+ Expect(songs[1].ID).To(Equal("track-b"))
+ Expect(songs[2].ID).To(Equal("track-c"))
+ })
+
+ It("respects count limit after deduplication", func() {
+ // Agent returns 4 songs: 2 unique + 2 that would create duplicates
+ returnedSongs := []agents.Song{
+ {Name: "Song A", Artist: "Artist"},
+ {Name: "Song A (Live)", Artist: "Artist"}, // Different, matches same track
+ {Name: "Song B", Artist: "Artist"},
+ {Name: "Song B (Remix)", Artist: "Artist"}, // Different, matches same track
+ }
+ trackA := model.MediaFile{ID: "track-a", Title: "Song A", Artist: "Artist"}
+ trackB := model.MediaFile{ID: "track-b", Title: "Song B", Artist: "Artist"}
+
+ setupSimilarSongsExpectations(returnedSongs, model.MediaFiles{trackA, trackB})
+
+ // Request only 2 songs
+ songs, err := provider.SimilarSongs(ctx, "track-1", 2)
+
+ Expect(err).ToNot(HaveOccurred())
+ // Should return exactly 2: Song A and Song B (skipping duplicates)
+ Expect(songs).To(HaveLen(2))
+ Expect(songs[0].ID).To(Equal("track-a"))
+ Expect(songs[1].ID).To(Equal("track-b"))
+ })
+ })
+})
diff --git a/core/external/provider_similarsongs_test.go b/core/external/provider_similarsongs_test.go
new file mode 100644
index 000000000..1491d394e
--- /dev/null
+++ b/core/external/provider_similarsongs_test.go
@@ -0,0 +1,443 @@
+package external_test
+
+import (
+ "context"
+ "errors"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/core/agents"
+ . "github.com/navidrome/navidrome/core/external"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/stretchr/testify/mock"
+)
+
+var _ = Describe("Provider - SimilarSongs", func() {
+ var ds model.DataStore
+ var provider Provider
+ var mockAgent *mockSimilarArtistAgent
+ var mockTopAgent agents.ArtistTopSongsRetriever
+ var mockSimilarAgent agents.ArtistSimilarRetriever
+ var agentsCombined *mockAgents
+ var artistRepo *mockArtistRepo
+ var mediaFileRepo *mockMediaFileRepo
+ var albumRepo *mockAlbumRepo
+ var ctx context.Context
+
+ BeforeEach(func() {
+ ctx = GinkgoT().Context()
+
+ artistRepo = newMockArtistRepo()
+ mediaFileRepo = newMockMediaFileRepo()
+ albumRepo = newMockAlbumRepo()
+
+ ds = &tests.MockDataStore{
+ MockedArtist: artistRepo,
+ MockedMediaFile: mediaFileRepo,
+ MockedAlbum: albumRepo,
+ }
+
+ mockAgent = &mockSimilarArtistAgent{}
+ mockTopAgent = mockAgent
+ mockSimilarAgent = mockAgent
+
+ agentsCombined = &mockAgents{
+ topSongsAgent: mockTopAgent,
+ similarAgent: mockSimilarAgent,
+ }
+
+ provider = NewProvider(ds, agentsCombined)
+ })
+
+ Describe("dispatch by entity type", func() {
+ Context("when ID is a MediaFile (track)", func() {
+ It("calls GetSimilarSongsByTrack and returns matched songs", func() {
+ track := model.MediaFile{ID: "track-1", Title: "Just Can't Get Enough", Artist: "Depeche Mode", MbzRecordingID: "track-mbid"}
+ matchedSong := model.MediaFile{ID: "matched-1", Title: "Dreaming of Me", Artist: "Depeche Mode"}
+
+ // GetEntityByID tries Artist, Album, Playlist, then MediaFile
+ artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once()
+
+ agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Just Can't Get Enough", "Depeche Mode", "track-mbid", 5).
+ Return([]agents.Song{
+ {Name: "Dreaming of Me", MBID: "", Artist: "Depeche Mode", ArtistMBID: "artist-mbid"},
+ }, nil).Once()
+
+ // Mock loadTracksByID - no ID matches
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ _, ok := opt.Filters.(squirrel.Eq)
+ return ok
+ })).Return(model.MediaFiles{}, nil).Once()
+
+ // Mock loadTracksByMBID - no MBID matches (empty MBID means this won't be called)
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ and, ok := opt.Filters.(squirrel.And)
+ if !ok || len(and) < 1 {
+ return false
+ }
+ eq, hasEq := and[0].(squirrel.Eq)
+ if !hasEq {
+ return false
+ }
+ _, hasMBID := eq["mbz_recording_id"]
+ return hasMBID
+ })).Return(model.MediaFiles{}, nil).Maybe()
+
+ // Mock loadTracksByTitleAndArtist - queries by artist name
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ and, ok := opt.Filters.(squirrel.And)
+ if !ok || len(and) < 2 {
+ return false
+ }
+ eq, hasEq := and[0].(squirrel.Eq)
+ if !hasEq {
+ return false
+ }
+ _, hasArtist := eq["order_artist_name"]
+ return hasArtist
+ })).Return(model.MediaFiles{matchedSong}, nil).Maybe()
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("matched-1"))
+ })
+
+ It("falls back to artist-based algorithm when GetSimilarSongsByTrack returns empty", func() {
+ track := model.MediaFile{ID: "track-1", Title: "Track", Artist: "Artist", ArtistID: "artist-1"}
+ artist := model.Artist{ID: "artist-1", Name: "Artist"}
+ song := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
+
+ // GetEntityByID for the initial call tries Artist, Album, Playlist, then MediaFile
+ artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once()
+
+ agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Track", "Artist", "", mock.Anything).
+ Return([]agents.Song{}, nil).Once()
+
+ // Fallback calls getArtist(id) which calls GetEntityByID again - this time it finds the mediafile
+ // and recursively calls getArtist(v.ArtistID)
+ artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once()
+ mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once()
+
+ // Then it recurses with the artist-1 ID
+ artistRepo.On("Get", "artist-1").Return(&artist, nil).Maybe()
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 1 && opt.Filters != nil
+ })).Return(model.Artists{artist}, nil).Maybe()
+
+ mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist", "", 15).
+ Return([]agents.Artist{}, nil).Once()
+
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 0 && opt.Filters != nil
+ })).Return(model.Artists{}, nil).Once()
+
+ mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist", "", mock.Anything).
+ Return([]agents.Song{{Name: "Song One", MBID: "mbid-1"}}, nil).Once()
+
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song}, nil).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "track-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("song-1"))
+ })
+ })
+
+ Context("when ID is an Album", func() {
+ It("calls GetSimilarSongsByAlbum and returns matched songs", func() {
+ album := model.Album{ID: "album-1", Name: "Speak & Spell", AlbumArtist: "Depeche Mode", MbzAlbumID: "album-mbid"}
+ matchedSong := model.MediaFile{ID: "matched-1", Title: "New Life", Artist: "Depeche Mode", MbzRecordingID: "song-mbid"}
+
+ // GetEntityByID tries Artist, Album, Playlist, then MediaFile
+ artistRepo.On("Get", "album-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "album-1").Return(&album, nil).Once()
+
+ agentsCombined.On("GetSimilarSongsByAlbum", mock.Anything, "album-1", "Speak & Spell", "Depeche Mode", "album-mbid", 5).
+ Return([]agents.Song{
+ {Name: "New Life", MBID: "song-mbid", Artist: "Depeche Mode"},
+ }, nil).Once()
+
+ // Mock loadTracksByID - no ID matches
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ _, ok := opt.Filters.(squirrel.Eq)
+ return ok
+ })).Return(model.MediaFiles{}, nil).Once()
+
+ // Mock loadTracksByMBID - MBID match
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ and, ok := opt.Filters.(squirrel.And)
+ if !ok || len(and) < 1 {
+ return false
+ }
+ _, hasEq := and[0].(squirrel.Eq)
+ return hasEq
+ })).Return(model.MediaFiles{matchedSong}, nil).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "album-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("matched-1"))
+ })
+
+ It("falls back when GetSimilarSongsByAlbum returns ErrNotFound", func() {
+ album := model.Album{ID: "album-1", Name: "Album", AlbumArtist: "Artist", AlbumArtistID: "artist-1"}
+ artist := model.Artist{ID: "artist-1", Name: "Artist"}
+ song := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
+
+ // GetEntityByID for the initial call tries Artist, Album, Playlist, then MediaFile
+ artistRepo.On("Get", "album-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "album-1").Return(&album, nil).Once()
+
+ agentsCombined.On("GetSimilarSongsByAlbum", mock.Anything, "album-1", "Album", "Artist", "", mock.Anything).
+ Return(nil, agents.ErrNotFound).Once()
+
+ // Fallback calls getArtist(id) which calls GetEntityByID again - this time it finds the album
+ // and recursively calls getArtist(v.AlbumArtistID)
+ artistRepo.On("Get", "album-1").Return(nil, model.ErrNotFound).Once()
+ albumRepo.On("Get", "album-1").Return(&album, nil).Once()
+
+ // Then it recurses with the artist-1 ID
+ artistRepo.On("Get", "artist-1").Return(&artist, nil).Maybe()
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 1 && opt.Filters != nil
+ })).Return(model.Artists{artist}, nil).Maybe()
+
+ mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist", "", 15).
+ Return([]agents.Artist{}, nil).Once()
+
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 0 && opt.Filters != nil
+ })).Return(model.Artists{}, nil).Once()
+
+ mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist", "", mock.Anything).
+ Return([]agents.Song{{Name: "Song One", MBID: "mbid-1"}}, nil).Once()
+
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song}, nil).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "album-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("song-1"))
+ })
+ })
+
+ Context("when ID is an Artist", func() {
+ It("calls GetSimilarSongsByArtist and returns matched songs", func() {
+ artist := model.Artist{ID: "artist-1", Name: "Depeche Mode", MbzArtistID: "artist-mbid"}
+ matchedSong := model.MediaFile{ID: "matched-1", Title: "Enjoy the Silence", Artist: "Depeche Mode", MbzRecordingID: "song-mbid"}
+
+ artistRepo.On("Get", "artist-1").Return(&artist, nil).Once()
+ agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Depeche Mode", "artist-mbid", 5).
+ Return([]agents.Song{
+ {Name: "Enjoy the Silence", MBID: "song-mbid", Artist: "Depeche Mode"},
+ }, nil).Once()
+
+ // Mock loadTracksByID - no ID matches
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ _, ok := opt.Filters.(squirrel.Eq)
+ return ok
+ })).Return(model.MediaFiles{}, nil).Once()
+
+ // Mock loadTracksByMBID - MBID match
+ mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ and, ok := opt.Filters.(squirrel.And)
+ if !ok || len(and) < 1 {
+ return false
+ }
+ _, hasEq := and[0].(squirrel.Eq)
+ return hasEq
+ })).Return(model.MediaFiles{matchedSong}, nil).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "artist-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("matched-1"))
+ })
+ })
+ })
+
+ It("returns similar songs from main artist and similar artists", func() {
+ artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
+ similarArtist := model.Artist{ID: "artist-3", Name: "Similar Artist"}
+ song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
+ song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"}
+ song3 := model.MediaFile{ID: "song-3", Title: "Song Three", ArtistID: "artist-3", MbzRecordingID: "mbid-3"}
+
+ artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
+ artistRepo.On("Get", "artist-3").Return(&similarArtist, nil).Maybe()
+
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 1 && opt.Filters != nil
+ })).Return(model.Artists{artist1}, nil).Once()
+
+ // New similar songs by artist returns ErrNotFound to trigger fallback
+ agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return(nil, agents.ErrNotFound).Once()
+
+ similarAgentsResp := []agents.Artist{
+ {Name: "Similar Artist", MBID: "similar-mbid"},
+ }
+ mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
+ Return(similarAgentsResp, nil).Once()
+
+ // Mock the three-phase artist lookup: ID (skipped - no IDs), MBID, then Name
+ // MBID lookup returns empty (no match)
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ _, ok := opt.Filters.(squirrel.Eq)
+ return opt.Max == 0 && ok
+ })).Return(model.Artists{}, nil).Once()
+ // Name lookup returns the similar artist
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ _, ok := opt.Filters.(squirrel.Or)
+ return opt.Max == 0 && ok
+ })).Return(model.Artists{similarArtist}, nil).Once()
+
+ mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return([]agents.Song{
+ {Name: "Song One", MBID: "mbid-1"},
+ {Name: "Song Two", MBID: "mbid-2"},
+ }, nil).Once()
+
+ mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-3", "Similar Artist", "", mock.Anything).
+ Return([]agents.Song{
+ {Name: "Song Three", MBID: "mbid-3"},
+ }, nil).Once()
+
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song3}, nil).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "artist-1", 3)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(3))
+ for _, song := range songs {
+ Expect(song.ID).To(BeElementOf("song-1", "song-2", "song-3"))
+ }
+ })
+
+ It("returns ErrNotFound when artist is not found", func() {
+ artistRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound)
+ mediaFileRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound)
+ albumRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound)
+
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 1 && opt.Filters != nil
+ })).Return(model.Artists{}, nil).Maybe()
+
+ songs, err := provider.SimilarSongs(ctx, "artist-unknown-artist", 5)
+
+ Expect(err).To(Equal(model.ErrNotFound))
+ Expect(songs).To(BeNil())
+ })
+
+ It("returns songs from main artist when GetSimilarArtists returns error", func() {
+ artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
+ song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
+
+ artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 1 && opt.Filters != nil
+ })).Return(model.Artists{artist1}, nil).Maybe()
+
+ // New similar songs by artist returns ErrNotFound to trigger fallback
+ agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return(nil, agents.ErrNotFound).Once()
+
+ mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
+ Return(nil, errors.New("error getting similar artists")).Once()
+
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 0 && opt.Filters != nil
+ })).Return(model.Artists{}, nil).Once()
+
+ mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return([]agents.Song{
+ {Name: "Song One", MBID: "mbid-1"},
+ }, nil).Once()
+
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "artist-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("song-1"))
+ })
+
+ It("returns empty list when GetArtistTopSongs returns error", func() {
+ artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
+
+ artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 1 && opt.Filters != nil
+ })).Return(model.Artists{artist1}, nil).Maybe()
+
+ // New similar songs by artist returns ErrNotFound to trigger fallback
+ agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return(nil, agents.ErrNotFound).Once()
+
+ mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
+ Return([]agents.Artist{}, nil).Once()
+
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 0 && opt.Filters != nil
+ })).Return(model.Artists{}, nil).Once()
+
+ mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return(nil, errors.New("error getting top songs")).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "artist-1", 5)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(BeEmpty())
+ })
+
+ It("respects count parameter", func() {
+ artist1 := model.Artist{ID: "artist-1", Name: "Artist One"}
+ song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}
+ song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"}
+
+ artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe()
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 1 && opt.Filters != nil
+ })).Return(model.Artists{artist1}, nil).Maybe()
+
+ // New similar songs by artist returns ErrNotFound to trigger fallback
+ agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return(nil, agents.ErrNotFound).Once()
+
+ mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15).
+ Return([]agents.Artist{}, nil).Once()
+
+ artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
+ return opt.Max == 0 && opt.Filters != nil
+ })).Return(model.Artists{}, nil).Once()
+
+ mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything).
+ Return([]agents.Song{
+ {Name: "Song One", MBID: "mbid-1"},
+ {Name: "Song Two", MBID: "mbid-2"},
+ }, nil).Once()
+
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
+
+ songs, err := provider.SimilarSongs(ctx, "artist-1", 1)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(BeElementOf("song-1", "song-2"))
+ })
+})
diff --git a/core/external/provider_topsongs_test.go b/core/external/provider_topsongs_test.go
index 5a5a25714..b73c8ab3e 100644
--- a/core/external/provider_topsongs_test.go
+++ b/core/external/provider_topsongs_test.go
@@ -4,10 +4,11 @@ import (
"context"
"errors"
+ _ "github.com/navidrome/navidrome/adapters/lastfm"
+ _ "github.com/navidrome/navidrome/adapters/listenbrainz"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/agents"
- _ "github.com/navidrome/navidrome/core/agents/lastfm"
- _ "github.com/navidrome/navidrome/core/agents/listenbrainz"
- _ "github.com/navidrome/navidrome/core/agents/spotify"
. "github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
@@ -26,6 +27,10 @@ var _ = Describe("Provider - TopSongs", func() {
)
BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ // Disable fuzzy matching for these tests to avoid unexpected GetAll calls
+ conf.Server.SimilarSongsMatchThreshold = 100
+
ctx = GinkgoT().Context()
artistRepo = newMockArtistRepo() // Use helper mock
@@ -271,4 +276,60 @@ var _ = Describe("Provider - TopSongs", func() {
ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
})
+
+ It("matches songs by ID first when agent provides IDs", func() {
+ // Mock finding the artist
+ artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
+ artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
+
+ // Mock agent response with IDs provided (highest priority matching)
+ // Note: Songs have no MBID to ensure only ID matching is used
+ agentSongs := []agents.Song{
+ {ID: "song-1", Name: "Song One"},
+ {ID: "song-2", Name: "Song Two"},
+ }
+ ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
+
+ // Mock ID lookup (first query - should match both songs directly)
+ song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1"}
+ song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1"}
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
+
+ songs, err := p.TopSongs(ctx, "Artist One", 2)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(2))
+ Expect(songs[0].ID).To(Equal("song-1"))
+ Expect(songs[1].ID).To(Equal("song-2"))
+ artistRepo.AssertExpectations(GinkgoT())
+ ag.AssertExpectations(GinkgoT())
+ mediaFileRepo.AssertExpectations(GinkgoT())
+ })
+
+ It("falls back to MBID when ID is not found", func() {
+ // Mock finding the artist
+ artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
+ artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
+
+ // Mock agent response with ID that won't be found, but MBID that will
+ agentSongs := []agents.Song{
+ {ID: "non-existent-id", Name: "Song One", MBID: "mbid-song-1"},
+ }
+ ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
+
+ // Mock ID lookup - returns empty (ID not found)
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{}, nil).Once()
+ // Mock MBID lookup - finds the song
+ song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
+ mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
+
+ songs, err := p.TopSongs(ctx, "Artist One", 1)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(songs).To(HaveLen(1))
+ Expect(songs[0].ID).To(Equal("song-1"))
+ artistRepo.AssertExpectations(GinkgoT())
+ ag.AssertExpectations(GinkgoT())
+ mediaFileRepo.AssertExpectations(GinkgoT())
+ })
})
diff --git a/core/external/provider_updateartistinfo_test.go b/core/external/provider_updateartistinfo_test.go
index 9b1e8d866..0c489eadd 100644
--- a/core/external/provider_updateartistinfo_test.go
+++ b/core/external/provider_updateartistinfo_test.go
@@ -226,4 +226,88 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
Expect(updatedArtist.ID).To(Equal("ar-agent-fail"))
ag.AssertExpectations(GinkgoT())
})
+
+ It("matches similar artists by ID first when agent provides IDs", func() {
+ originalArtist := &model.Artist{
+ ID: "ar-id-match",
+ Name: "ID Match Artist",
+ }
+ similarByID := model.Artist{ID: "ar-similar-by-id", Name: "Similar By ID", MbzArtistID: "mbid-similar"}
+ mockArtistRepo.SetData(model.Artists{*originalArtist, similarByID})
+
+ // Agent returns similar artist with ID (highest priority matching)
+ rawSimilar := []agents.Artist{
+ {ID: "ar-similar-by-id", Name: "Different Name", MBID: "different-mbid"},
+ }
+
+ ag.On("GetArtistMBID", ctx, "ar-id-match", "ID Match Artist").Return("", nil).Once()
+ ag.On("GetArtistImages", ctx, "ar-id-match", "ID Match Artist", mock.Anything).Return(nil, nil).Maybe()
+ ag.On("GetArtistBiography", ctx, "ar-id-match", "ID Match Artist", mock.Anything).Return("", nil).Maybe()
+ ag.On("GetArtistURL", ctx, "ar-id-match", "ID Match Artist", mock.Anything).Return("", nil).Maybe()
+ ag.On("GetSimilarArtists", ctx, "ar-id-match", "ID Match Artist", mock.Anything, 100).Return(rawSimilar, nil).Once()
+
+ updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-id-match", 10, false)
+
+ Expect(err).NotTo(HaveOccurred())
+ Expect(updatedArtist.SimilarArtists).To(HaveLen(1))
+ // Should match by ID, not by name or MBID
+ Expect(updatedArtist.SimilarArtists[0].ID).To(Equal("ar-similar-by-id"))
+ Expect(updatedArtist.SimilarArtists[0].Name).To(Equal("Similar By ID"))
+ })
+
+ It("matches similar artists by MBID when ID is empty", func() {
+ originalArtist := &model.Artist{
+ ID: "ar-mbid-match",
+ Name: "MBID Match Artist",
+ }
+ similarByMBID := model.Artist{ID: "ar-similar-by-mbid", Name: "Similar By MBID", MbzArtistID: "mbid-similar"}
+ mockArtistRepo.SetData(model.Artists{*originalArtist, similarByMBID})
+
+ // Agent returns similar artist with only MBID (no ID)
+ rawSimilar := []agents.Artist{
+ {Name: "Different Name", MBID: "mbid-similar"},
+ }
+
+ ag.On("GetArtistMBID", ctx, "ar-mbid-match", "MBID Match Artist").Return("", nil).Once()
+ ag.On("GetArtistImages", ctx, "ar-mbid-match", "MBID Match Artist", mock.Anything).Return(nil, nil).Maybe()
+ ag.On("GetArtistBiography", ctx, "ar-mbid-match", "MBID Match Artist", mock.Anything).Return("", nil).Maybe()
+ ag.On("GetArtistURL", ctx, "ar-mbid-match", "MBID Match Artist", mock.Anything).Return("", nil).Maybe()
+ ag.On("GetSimilarArtists", ctx, "ar-mbid-match", "MBID Match Artist", mock.Anything, 100).Return(rawSimilar, nil).Once()
+
+ updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-mbid-match", 10, false)
+
+ Expect(err).NotTo(HaveOccurred())
+ Expect(updatedArtist.SimilarArtists).To(HaveLen(1))
+ // Should match by MBID since ID was empty
+ Expect(updatedArtist.SimilarArtists[0].ID).To(Equal("ar-similar-by-mbid"))
+ Expect(updatedArtist.SimilarArtists[0].Name).To(Equal("Similar By MBID"))
+ })
+
+ It("falls back to name matching when ID and MBID don't match", func() {
+ originalArtist := &model.Artist{
+ ID: "ar-name-match",
+ Name: "Name Match Artist",
+ }
+ similarByName := model.Artist{ID: "ar-similar-by-name", Name: "Similar By Name"}
+ mockArtistRepo.SetData(model.Artists{*originalArtist, similarByName})
+
+ // Agent returns similar artist with non-matching ID and MBID
+ rawSimilar := []agents.Artist{
+ {ID: "non-existent-id", Name: "Similar By Name", MBID: "non-existent-mbid"},
+ }
+
+ ag.On("GetArtistMBID", ctx, "ar-name-match", "Name Match Artist").Return("", nil).Once()
+ ag.On("GetArtistImages", ctx, "ar-name-match", "Name Match Artist", mock.Anything).Return(nil, nil).Maybe()
+ ag.On("GetArtistBiography", ctx, "ar-name-match", "Name Match Artist", mock.Anything).Return("", nil).Maybe()
+ ag.On("GetArtistURL", ctx, "ar-name-match", "Name Match Artist", mock.Anything).Return("", nil).Maybe()
+ ag.On("GetSimilarArtists", ctx, "ar-name-match", "Name Match Artist", mock.Anything, 100).Return(rawSimilar, nil).Once()
+
+ updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-name-match", 10, false)
+
+ Expect(err).NotTo(HaveOccurred())
+ Expect(updatedArtist.SimilarArtists).To(HaveLen(1))
+ // Should fall back to name matching since ID and MBID didn't match
+ Expect(updatedArtist.SimilarArtists[0].ID).To(Equal("ar-similar-by-name"))
+ Expect(updatedArtist.SimilarArtists[0].Name).To(Equal("Similar By Name"))
+ })
})
diff --git a/core/ffmpeg/ffmpeg.go b/core/ffmpeg/ffmpeg.go
index 2e0d5a4b7..33d6733c8 100644
--- a/core/ffmpeg/ffmpeg.go
+++ b/core/ffmpeg/ffmpeg.go
@@ -1,24 +1,52 @@
package ffmpeg
import (
+ "bytes"
"context"
+ "encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
+ "path/filepath"
"strconv"
"strings"
"sync"
"github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
)
+// TranscodeOptions contains all parameters for a transcoding operation.
+type TranscodeOptions struct {
+ Command string // DB command template (used to detect custom vs default)
+ Format string // Target format (mp3, opus, aac, flac)
+ FilePath string
+ BitRate int // kbps, 0 = codec default
+ SampleRate int // 0 = no constraint
+ Channels int // 0 = no constraint
+ BitDepth int // 0 = no constraint; valid values: 16, 24, 32
+ Offset int // seconds
+}
+
+// AudioProbeResult contains authoritative audio stream properties from ffprobe.
+type AudioProbeResult struct {
+ Codec string `json:"codec"`
+ Profile string `json:"profile,omitempty"`
+ BitRate int `json:"bitRate"`
+ SampleRate int `json:"sampleRate"`
+ BitDepth int `json:"bitDepth"`
+ Channels int `json:"channels"`
+}
+
type FFmpeg interface {
- Transcode(ctx context.Context, command, path string, maxBitRate, offset int) (io.ReadCloser, error)
+ Transcode(ctx context.Context, opts TranscodeOptions) (io.ReadCloser, error)
ExtractImage(ctx context.Context, path string) (io.ReadCloser, error)
+ ConvertAnimatedImage(ctx context.Context, reader io.Reader, maxSize int, quality int) (io.ReadCloser, error)
Probe(ctx context.Context, files []string) (string, error)
+ ProbeAudioStream(ctx context.Context, filePath string) (*AudioProbeResult, error)
CmdPath() (string, error)
IsAvailable() bool
Version() string
@@ -29,29 +57,50 @@ func New() FFmpeg {
}
const (
- extractImageCmd = "ffmpeg -i %s -map 0:v -map -0:V -vcodec copy -f image2pipe -"
- probeCmd = "ffmpeg %s -f ffmetadata"
+ extractImageCmd = "ffmpeg -i %s -map 0:v -map -0:V -vcodec copy -f image2pipe -"
+ probeCmd = "ffmpeg %s -f ffmetadata"
+ probeAudioStreamCmd = "ffprobe -v quiet -select_streams a:0 -print_format json -show_streams -show_format %s"
)
type ffmpeg struct{}
-func (e *ffmpeg) Transcode(ctx context.Context, command, path string, maxBitRate, offset int) (io.ReadCloser, error) {
+func (e *ffmpeg) Transcode(ctx context.Context, opts TranscodeOptions) (io.ReadCloser, error) {
if _, err := ffmpegCmd(); err != nil {
return nil, err
}
- // First make sure the file exists
- if err := fileExists(path); err != nil {
+ if err := fileExists(opts.FilePath); err != nil {
return nil, err
}
- args := createFFmpegCommand(command, path, maxBitRate, offset)
+ var args []string
+ if isDefaultCommand(opts.Format, opts.Command) {
+ args = buildDynamicArgs(opts)
+ } else {
+ args = buildTemplateArgs(opts)
+ }
return e.start(ctx, args)
}
+func (e *ffmpeg) ConvertAnimatedImage(ctx context.Context, reader io.Reader, maxSize int, quality int) (io.ReadCloser, error) {
+ cmdPath, err := ffmpegCmd()
+ if err != nil {
+ return nil, err
+ }
+
+ args := []string{cmdPath, "-i", "pipe:0"}
+ if maxSize > 0 {
+ vf := fmt.Sprintf("scale='min(%d,iw)':'min(%d,ih)':force_original_aspect_ratio=decrease", maxSize, maxSize)
+ args = append(args, "-vf", vf)
+ }
+ args = append(args, "-loop", "0", "-c:v", "libwebp_anim",
+ "-quality", strconv.Itoa(quality), "-f", "webp", "-")
+
+ return e.start(ctx, args, reader)
+}
+
func (e *ffmpeg) ExtractImage(ctx context.Context, path string) (io.ReadCloser, error) {
if _, err := ffmpegCmd(); err != nil {
return nil, err
}
- // First make sure the file exists
if err := fileExists(path); err != nil {
return nil, err
}
@@ -81,6 +130,91 @@ func (e *ffmpeg) Probe(ctx context.Context, files []string) (string, error) {
return string(output), nil
}
+func (e *ffmpeg) ProbeAudioStream(ctx context.Context, filePath string) (*AudioProbeResult, error) {
+ if _, err := ffmpegCmd(); err != nil {
+ return nil, err
+ }
+ if err := fileExists(filePath); err != nil {
+ return nil, err
+ }
+ args := createFFmpegCommand(probeAudioStreamCmd, filePath, 0, 0)
+ log.Trace(ctx, "Executing ffprobe command", "args", args)
+ cmd := exec.CommandContext(ctx, args[0], args[1:]...) // #nosec
+ output, err := cmd.Output()
+ if err != nil {
+ return nil, fmt.Errorf("running ffprobe on %q: %w", filePath, err)
+ }
+ return parseProbeOutput(output)
+}
+
+type probeOutput struct {
+ Streams []probeStream `json:"streams"`
+ Format probeFormat `json:"format"`
+}
+
+type probeFormat struct {
+ BitRate string `json:"bit_rate"`
+}
+
+type probeStream struct {
+ CodecName string `json:"codec_name"`
+ CodecType string `json:"codec_type"`
+ Profile string `json:"profile"`
+ SampleRate string `json:"sample_rate"`
+ BitRate string `json:"bit_rate"`
+ Channels int `json:"channels"`
+ BitsPerSample int `json:"bits_per_sample"`
+ BitsPerRawSample string `json:"bits_per_raw_sample"`
+}
+
+func parseProbeOutput(data []byte) (*AudioProbeResult, error) {
+ var output probeOutput
+ if err := json.Unmarshal(data, &output); err != nil {
+ return nil, fmt.Errorf("parsing ffprobe output: %w", err)
+ }
+
+ for _, s := range output.Streams {
+ if s.CodecType != "audio" {
+ continue
+ }
+ bitDepth := s.BitsPerSample
+ if bitDepth == 0 && s.BitsPerRawSample != "" {
+ bitDepth, _ = strconv.Atoi(s.BitsPerRawSample)
+ }
+ result := &AudioProbeResult{
+ Codec: s.CodecName,
+ Channels: s.Channels,
+ BitDepth: bitDepth,
+ }
+
+ // Profile: "unknown" → empty
+ if s.Profile != "" && !strings.EqualFold(s.Profile, "unknown") {
+ result.Profile = s.Profile
+ }
+
+ // Sample rate: string → int
+ if s.SampleRate != "" {
+ result.SampleRate, _ = strconv.Atoi(s.SampleRate)
+ }
+
+ // Bit rate: bps string → kbps int
+ if s.BitRate != "" {
+ bps, _ := strconv.Atoi(s.BitRate)
+ result.BitRate = bps / 1000
+ }
+
+ // Fallback to format-level bit_rate (needed for FLAC, Opus, etc.)
+ if result.BitRate == 0 && output.Format.BitRate != "" {
+ bps, _ := strconv.Atoi(output.Format.BitRate)
+ result.BitRate = bps / 1000
+ }
+
+ return result, nil
+ }
+
+ return nil, fmt.Errorf("no audio stream found in ffprobe output")
+}
+
func (e *ffmpeg) CmdPath() (string, error) {
return ffmpegCmd()
}
@@ -108,11 +242,14 @@ func (e *ffmpeg) Version() string {
return parts[2]
}
-func (e *ffmpeg) start(ctx context.Context, args []string) (io.ReadCloser, error) {
+func (e *ffmpeg) start(ctx context.Context, args []string, input ...io.Reader) (io.ReadCloser, error) {
log.Trace(ctx, "Executing ffmpeg command", "cmd", args)
j := &ffCmd{args: args}
+ if len(input) > 0 {
+ j.input = input[0]
+ }
j.PipeReader, j.out = io.Pipe()
- err := j.start()
+ err := j.start(ctx)
if err != nil {
return nil, err
}
@@ -122,18 +259,25 @@ func (e *ffmpeg) start(ctx context.Context, args []string) (io.ReadCloser, error
type ffCmd struct {
*io.PipeReader
- out *io.PipeWriter
- args []string
- cmd *exec.Cmd
+ out *io.PipeWriter
+ args []string
+ cmd *exec.Cmd
+ input io.Reader // optional stdin source
+ stderr *bytes.Buffer
}
-func (j *ffCmd) start() error {
- cmd := exec.Command(j.args[0], j.args[1:]...) // #nosec
+func (j *ffCmd) start(ctx context.Context) error {
+ cmd := exec.CommandContext(ctx, j.args[0], j.args[1:]...) // #nosec
cmd.Stdout = j.out
+ if j.input != nil {
+ cmd.Stdin = j.input
+ }
+ j.stderr = &bytes.Buffer{}
+ stderrWriter := &limitedWriter{buf: j.stderr, limit: 4096}
if log.IsGreaterOrEqualTo(log.LevelTrace) {
- cmd.Stderr = os.Stderr
+ cmd.Stderr = io.MultiWriter(os.Stderr, stderrWriter)
} else {
- cmd.Stderr = io.Discard
+ cmd.Stderr = stderrWriter
}
j.cmd = cmd
@@ -147,7 +291,11 @@ func (j *ffCmd) wait() {
if err := j.cmd.Wait(); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
- _ = j.out.CloseWithError(fmt.Errorf("%s exited with non-zero status code: %d", j.args[0], exitErr.ExitCode()))
+ errMsg := fmt.Sprintf("%s exited with non-zero status code: %d", j.args[0], exitErr.ExitCode())
+ if stderrOutput := strings.TrimSpace(j.stderr.String()); stderrOutput != "" {
+ errMsg += ": " + stderrOutput
+ }
+ _ = j.out.CloseWithError(errors.New(errMsg))
} else {
_ = j.out.CloseWithError(fmt.Errorf("waiting %s cmd: %w", j.args[0], err))
}
@@ -156,6 +304,156 @@ func (j *ffCmd) wait() {
_ = j.out.Close()
}
+// limitedWriter wraps a bytes.Buffer and stops writing once the limit is reached.
+// Writes that would exceed the limit are silently discarded to prevent unbounded memory usage.
+type limitedWriter struct {
+ buf *bytes.Buffer
+ limit int
+}
+
+func (w *limitedWriter) Write(p []byte) (int, error) {
+ n := len(p)
+ remaining := w.limit - w.buf.Len()
+ if remaining <= 0 {
+ return n, nil // Discard but report success to avoid breaking the writer
+ }
+ if len(p) > remaining {
+ p = p[:remaining]
+ }
+ w.buf.Write(p)
+ return n, nil // Always report full write to avoid ErrShortWrite from io.MultiWriter
+}
+
+// formatCodecMap maps target format to ffmpeg codec flag.
+var formatCodecMap = map[string]string{
+ "mp3": "libmp3lame",
+ "opus": "libopus",
+ "aac": "aac",
+ "flac": "flac",
+}
+
+// formatOutputMap maps target format to ffmpeg output format flag (-f).
+var formatOutputMap = map[string]string{
+ "mp3": "mp3",
+ "opus": "opus",
+ "aac": "adts",
+ "flac": "flac",
+}
+
+// defaultCommands is used to detect whether a user has customized their transcoding command.
+var defaultCommands = func() map[string]string {
+ m := make(map[string]string, len(consts.DefaultTranscodings))
+ for _, t := range consts.DefaultTranscodings {
+ m[t.TargetFormat] = t.Command
+ }
+ return m
+}()
+
+// isDefaultCommand returns true if the command matches the known default for this format.
+func isDefaultCommand(format, command string) bool {
+ return defaultCommands[format] == command
+}
+
+// buildDynamicArgs programmatically constructs ffmpeg arguments for known formats,
+// including all transcoding parameters (bitrate, sample rate, channels).
+func buildDynamicArgs(opts TranscodeOptions) []string {
+ cmdPath, _ := ffmpegCmd()
+ args := []string{cmdPath, "-i", opts.FilePath}
+
+ if opts.Offset > 0 {
+ args = append(args, "-ss", strconv.Itoa(opts.Offset))
+ }
+
+ args = append(args, "-map", "0:a:0")
+
+ if codec, ok := formatCodecMap[opts.Format]; ok {
+ args = append(args, "-c:a", codec)
+ }
+
+ if opts.BitRate > 0 {
+ args = append(args, "-b:a", strconv.Itoa(opts.BitRate)+"k")
+ }
+ if opts.SampleRate > 0 {
+ args = append(args, "-ar", strconv.Itoa(opts.SampleRate))
+ }
+ if opts.Channels > 0 {
+ args = append(args, "-ac", strconv.Itoa(opts.Channels))
+ }
+ // Only pass -sample_fmt for lossless output formats where bit depth matters.
+ // Lossy codecs (mp3, aac, opus) handle sample format conversion internally,
+ // and passing interleaved formats like "s16" causes silent failures.
+ if opts.BitDepth >= 16 && isLosslessOutputFormat(opts.Format) {
+ args = append(args, "-sample_fmt", bitDepthToSampleFmt(opts.BitDepth))
+ }
+
+ args = append(args, "-v", "0")
+
+ if outputFmt, ok := formatOutputMap[opts.Format]; ok {
+ args = append(args, "-f", outputFmt)
+ }
+
+ args = append(args, "-")
+ return args
+}
+
+// buildTemplateArgs handles user-customized command templates, with dynamic injection
+// of sample rate, channels, and bit depth when requested by the transcode decision.
+// Note: these flags are injected unconditionally when non-zero, even if the template
+// already includes them. FFmpeg uses the last occurrence of duplicate flags.
+func buildTemplateArgs(opts TranscodeOptions) []string {
+ args := createFFmpegCommand(opts.Command, opts.FilePath, opts.BitRate, opts.Offset)
+
+ // Dynamically inject -ar, -ac, and -sample_fmt before the output target
+ if opts.SampleRate > 0 {
+ args = injectBeforeOutput(args, "-ar", strconv.Itoa(opts.SampleRate))
+ }
+ if opts.Channels > 0 {
+ args = injectBeforeOutput(args, "-ac", strconv.Itoa(opts.Channels))
+ }
+ if opts.BitDepth >= 16 && isLosslessOutputFormat(opts.Format) {
+ args = injectBeforeOutput(args, "-sample_fmt", bitDepthToSampleFmt(opts.BitDepth))
+ }
+ return args
+}
+
+// injectBeforeOutput inserts a flag and value before the trailing "-" (stdout output).
+func injectBeforeOutput(args []string, flag, value string) []string {
+ if len(args) > 0 && args[len(args)-1] == "-" {
+ result := make([]string, 0, len(args)+2)
+ result = append(result, args[:len(args)-1]...)
+ result = append(result, flag, value, "-")
+ return result
+ }
+ return append(args, flag, value)
+}
+
+// isLosslessOutputFormat returns true if the format is a lossless audio format
+// where preserving bit depth via -sample_fmt is meaningful.
+// Note: this covers only formats ffmpeg can produce as output. For the full set of
+// lossless formats used in transcoding decisions, see core/stream/codec.go:isLosslessFormat.
+func isLosslessOutputFormat(format string) bool {
+ switch strings.ToLower(format) {
+ case "flac", "alac", "wav", "aiff":
+ return true
+ }
+ return false
+}
+
+// bitDepthToSampleFmt converts a bit depth value to the ffmpeg sample_fmt string.
+// FLAC only supports s16 and s32; for 24-bit sources, s32 is the correct format
+// (ffmpeg packs 24-bit samples into 32-bit containers).
+func bitDepthToSampleFmt(bitDepth int) string {
+ switch bitDepth {
+ case 16:
+ return "s16"
+ case 32:
+ return "s32"
+ default:
+ // 24-bit and other depths: use s32 (the next valid container size)
+ return "s32"
+ }
+}
+
// Path will always be an absolute path
func createFFmpegCommand(cmd, path string, maxBitRate, offset int) []string {
var args []string
@@ -196,10 +494,20 @@ func fixCmd(cmd string) []string {
if s == "ffmpeg" || s == "ffmpeg.exe" {
split[i] = cmdPath
}
+ if s == "ffprobe" || s == "ffprobe.exe" {
+ split[i] = ffprobePath(cmdPath)
+ }
}
return split
}
+// ffprobePath derives the ffprobe binary path from the resolved ffmpeg path.
+func ffprobePath(ffmpegCmd string) string {
+ dir := filepath.Dir(ffmpegCmd)
+ base := filepath.Base(ffmpegCmd)
+ return filepath.Join(dir, strings.Replace(base, "ffmpeg", "ffprobe", 1))
+}
+
func ffmpegCmd() (string, error) {
ffOnce.Do(func() {
if conf.Server.FFmpegPath != "" {
diff --git a/core/ffmpeg/ffmpeg_test.go b/core/ffmpeg/ffmpeg_test.go
index 7e67a2a6a..04663828f 100644
--- a/core/ffmpeg/ffmpeg_test.go
+++ b/core/ffmpeg/ffmpeg_test.go
@@ -1,16 +1,28 @@
package ffmpeg
import (
+ "context"
+ "os"
+ "path/filepath"
+ "runtime"
+ sync "sync"
"testing"
+ "time"
+ "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestFFmpeg(t *testing.T) {
- tests.Init(t, false)
+ // Inline test init to avoid import cycle with tests package
+ //nolint:dogsled
+ _, file, _, _ := runtime.Caller(0)
+ appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..", ".."))
+ confPath := filepath.Join(appPath, "tests", "navidrome-test.toml")
+ _ = os.Chdir(appPath)
+ conf.LoadFromFile(confPath)
log.SetLevel(log.LevelFatal)
RegisterFailHandler(Fail)
RunSpecs(t, "FFmpeg Suite")
@@ -65,4 +77,617 @@ var _ = Describe("ffmpeg", func() {
Expect(args).To(Equal([]string{"/usr/bin/with spaces/ffmpeg.exe", "-i", "one.mp3", "-f", "ffmetadata"}))
})
})
+
+ Describe("isDefaultCommand", func() {
+ It("returns true for known default mp3 command", func() {
+ Expect(isDefaultCommand("mp3", "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -f mp3 -")).To(BeTrue())
+ })
+ It("returns true for known default opus command", func() {
+ Expect(isDefaultCommand("opus", "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -c:a libopus -f opus -")).To(BeTrue())
+ })
+ It("returns true for known default aac command", func() {
+ Expect(isDefaultCommand("aac", "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -c:a aac -f adts -")).To(BeTrue())
+ })
+ It("returns true for known default flac command", func() {
+ Expect(isDefaultCommand("flac", "ffmpeg -i %s -ss %t -map 0:a:0 -v 0 -c:a flac -f flac -")).To(BeTrue())
+ })
+ It("returns false for a custom command", func() {
+ Expect(isDefaultCommand("mp3", "ffmpeg -i %s -b:a %bk -custom-flag -f mp3 -")).To(BeFalse())
+ })
+ It("returns false for unknown format", func() {
+ Expect(isDefaultCommand("wav", "ffmpeg -i %s -f wav -")).To(BeFalse())
+ })
+ })
+
+ Describe("buildDynamicArgs", func() {
+ It("builds mp3 args with bitrate, samplerate, and channels", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "mp3",
+ FilePath: "/music/file.flac",
+ BitRate: 256,
+ SampleRate: 48000,
+ Channels: 2,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.flac",
+ "-map", "0:a:0",
+ "-c:a", "libmp3lame",
+ "-b:a", "256k",
+ "-ar", "48000",
+ "-ac", "2",
+ "-v", "0",
+ "-f", "mp3",
+ "-",
+ }))
+ })
+
+ It("builds flac args without bitrate", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "flac",
+ FilePath: "/music/file.dsf",
+ SampleRate: 48000,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.dsf",
+ "-map", "0:a:0",
+ "-c:a", "flac",
+ "-ar", "48000",
+ "-v", "0",
+ "-f", "flac",
+ "-",
+ }))
+ })
+
+ It("builds opus args with bitrate only", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "opus",
+ FilePath: "/music/file.flac",
+ BitRate: 128,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.flac",
+ "-map", "0:a:0",
+ "-c:a", "libopus",
+ "-b:a", "128k",
+ "-v", "0",
+ "-f", "opus",
+ "-",
+ }))
+ })
+
+ It("includes offset when specified", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "mp3",
+ FilePath: "/music/file.mp3",
+ BitRate: 192,
+ Offset: 30,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.mp3",
+ "-ss", "30",
+ "-map", "0:a:0",
+ "-c:a", "libmp3lame",
+ "-b:a", "192k",
+ "-v", "0",
+ "-f", "mp3",
+ "-",
+ }))
+ })
+
+ It("builds aac args with ADTS output", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "aac",
+ FilePath: "/music/file.flac",
+ BitRate: 256,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.flac",
+ "-map", "0:a:0",
+ "-c:a", "aac",
+ "-b:a", "256k",
+ "-v", "0",
+ "-f", "adts",
+ "-",
+ }))
+ })
+
+ It("builds flac args with bit depth", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "flac",
+ FilePath: "/music/file.dsf",
+ BitDepth: 24,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.dsf",
+ "-map", "0:a:0",
+ "-c:a", "flac",
+ "-sample_fmt", "s32",
+ "-v", "0",
+ "-f", "flac",
+ "-",
+ }))
+ })
+
+ It("omits -sample_fmt when bit depth is 0", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "flac",
+ FilePath: "/music/file.flac",
+ BitDepth: 0,
+ })
+ Expect(args).ToNot(ContainElement("-sample_fmt"))
+ })
+
+ It("omits -sample_fmt when bit depth is too low (DSD)", func() {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: "flac",
+ FilePath: "/music/file.dsf",
+ BitDepth: 1,
+ })
+ Expect(args).ToNot(ContainElement("-sample_fmt"))
+ })
+
+ DescribeTable("omits -sample_fmt for lossy formats even when bit depth >= 16",
+ func(format string, bitRate int) {
+ args := buildDynamicArgs(TranscodeOptions{
+ Format: format,
+ FilePath: "/music/file.flac",
+ BitRate: bitRate,
+ BitDepth: 16,
+ })
+ Expect(args).ToNot(ContainElement("-sample_fmt"))
+ },
+ Entry("mp3", "mp3", 256),
+ Entry("aac", "aac", 256),
+ Entry("opus", "opus", 128),
+ )
+ })
+
+ Describe("bitDepthToSampleFmt", func() {
+ It("converts 16-bit", func() {
+ Expect(bitDepthToSampleFmt(16)).To(Equal("s16"))
+ })
+ It("converts 24-bit to s32 (FLAC only supports s16/s32)", func() {
+ Expect(bitDepthToSampleFmt(24)).To(Equal("s32"))
+ })
+ It("converts 32-bit", func() {
+ Expect(bitDepthToSampleFmt(32)).To(Equal("s32"))
+ })
+ })
+
+ Describe("buildTemplateArgs", func() {
+ It("injects -ar and -ac into custom template", func() {
+ args := buildTemplateArgs(TranscodeOptions{
+ Command: "ffmpeg -i %s -b:a %bk -v 0 -f mp3 -",
+ FilePath: "/music/file.flac",
+ BitRate: 192,
+ SampleRate: 44100,
+ Channels: 2,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.flac",
+ "-b:a", "192k", "-v", "0", "-f", "mp3",
+ "-ar", "44100", "-ac", "2",
+ "-",
+ }))
+ })
+
+ It("injects only -ar when channels is 0", func() {
+ args := buildTemplateArgs(TranscodeOptions{
+ Command: "ffmpeg -i %s -b:a %bk -v 0 -f mp3 -",
+ FilePath: "/music/file.flac",
+ BitRate: 192,
+ SampleRate: 48000,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.flac",
+ "-b:a", "192k", "-v", "0", "-f", "mp3",
+ "-ar", "48000",
+ "-",
+ }))
+ })
+
+ It("does not inject anything when sample rate and channels are 0", func() {
+ args := buildTemplateArgs(TranscodeOptions{
+ Command: "ffmpeg -i %s -b:a %bk -v 0 -f mp3 -",
+ FilePath: "/music/file.flac",
+ BitRate: 192,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.flac",
+ "-b:a", "192k", "-v", "0", "-f", "mp3",
+ "-",
+ }))
+ })
+
+ It("injects -sample_fmt for lossless output format with bit depth", func() {
+ args := buildTemplateArgs(TranscodeOptions{
+ Command: "ffmpeg -i %s -v 0 -c:a flac -f flac -",
+ Format: "flac",
+ FilePath: "/music/file.dsf",
+ BitDepth: 24,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.dsf",
+ "-v", "0", "-c:a", "flac", "-f", "flac",
+ "-sample_fmt", "s32",
+ "-",
+ }))
+ })
+
+ It("does not inject -sample_fmt for lossy output format even with bit depth", func() {
+ args := buildTemplateArgs(TranscodeOptions{
+ Command: "ffmpeg -i %s -b:a %bk -v 0 -f mp3 -",
+ Format: "mp3",
+ FilePath: "/music/file.flac",
+ BitRate: 192,
+ BitDepth: 16,
+ })
+ Expect(args).To(Equal([]string{
+ "ffmpeg", "-i", "/music/file.flac",
+ "-b:a", "192k", "-v", "0", "-f", "mp3",
+ "-",
+ }))
+ })
+ })
+
+ Describe("injectBeforeOutput", func() {
+ It("inserts flag before trailing dash", func() {
+ args := injectBeforeOutput([]string{"ffmpeg", "-i", "file.mp3", "-f", "mp3", "-"}, "-ar", "48000")
+ Expect(args).To(Equal([]string{"ffmpeg", "-i", "file.mp3", "-f", "mp3", "-ar", "48000", "-"}))
+ })
+
+ It("appends when no trailing dash", func() {
+ args := injectBeforeOutput([]string{"ffmpeg", "-i", "file.mp3"}, "-ar", "48000")
+ Expect(args).To(Equal([]string{"ffmpeg", "-i", "file.mp3", "-ar", "48000"}))
+ })
+ })
+
+ Describe("parseProbeOutput", func() {
+ It("parses MP3 with embedded artwork (real ffprobe output)", func() {
+ // Real: MP3 file with mjpeg artwork stream after audio
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"mp3","codec_long_name":"MP3 (MPEG audio layer 3)","codec_type":"audio",` +
+ `"sample_fmt":"fltp","sample_rate":"44100","channels":2,"channel_layout":"stereo",` +
+ `"bits_per_sample":0,"bit_rate":"198314","tags":{"encoder":"LAME3.99r"}},` +
+ `{"index":1,"codec_name":"mjpeg","codec_type":"video","profile":"Baseline","width":400,"height":400}]}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("mp3"))
+ Expect(result.Profile).To(BeEmpty()) // MP3 has no profile field
+ Expect(result.SampleRate).To(Equal(44100))
+ Expect(result.Channels).To(Equal(2))
+ Expect(result.BitRate).To(Equal(198)) // 198314 bps -> 198 kbps
+ Expect(result.BitDepth).To(Equal(0)) // lossy codec
+ })
+
+ It("parses AAC-LC in m4a container (real ffprobe output)", func() {
+ // Real: AAC LC file with profile and artwork
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"aac","codec_long_name":"AAC (Advanced Audio Coding)",` +
+ `"profile":"LC","codec_type":"audio","sample_fmt":"fltp","sample_rate":"44100",` +
+ `"channels":2,"channel_layout":"stereo","bits_per_sample":0,"bit_rate":"279958"},` +
+ `{"index":1,"codec_name":"mjpeg","codec_type":"video","profile":"Baseline"}]}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("aac"))
+ Expect(result.Profile).To(Equal("LC"))
+ Expect(result.SampleRate).To(Equal(44100))
+ Expect(result.Channels).To(Equal(2))
+ Expect(result.BitRate).To(Equal(279)) // 279958 bps -> 279 kbps
+ })
+
+ It("parses HE-AACv2 in mp4 container with video stream (real ffprobe output)", func() {
+ // Real: Fraunhofer HE-AACv2 sample (LFE-SBRstereo.mp4), video stream before audio
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"h264","codec_type":"video","profile":"Main"},` +
+ `{"index":1,"codec_name":"aac","codec_long_name":"AAC (Advanced Audio Coding)",` +
+ `"profile":"HE-AACv2","codec_type":"audio","sample_fmt":"fltp",` +
+ `"sample_rate":"48000","channels":2,"channel_layout":"stereo",` +
+ `"bits_per_sample":0,"bit_rate":"55999"}]}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("aac"))
+ Expect(result.Profile).To(Equal("HE-AACv2"))
+ Expect(result.SampleRate).To(Equal(48000))
+ Expect(result.Channels).To(Equal(2))
+ Expect(result.BitRate).To(Equal(55)) // 55999 bps -> 55 kbps
+ })
+
+ It("parses FLAC using bits_per_raw_sample and format-level bit_rate (real ffprobe output)", func() {
+ // Real: FLAC reports bit depth in bits_per_raw_sample, not bits_per_sample.
+ // Stream-level bit_rate is absent; format-level bit_rate is used as fallback.
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"flac","codec_long_name":"FLAC (Free Lossless Audio Codec)",` +
+ `"codec_type":"audio","sample_fmt":"s16","sample_rate":"44100","channels":2,` +
+ `"channel_layout":"stereo","bits_per_sample":0,"bits_per_raw_sample":"16"},` +
+ `{"index":1,"codec_name":"mjpeg","codec_type":"video","profile":"Baseline"}],` +
+ `"format":{"bit_rate":"906900"}}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("flac"))
+ Expect(result.SampleRate).To(Equal(44100))
+ Expect(result.BitDepth).To(Equal(16)) // from bits_per_raw_sample
+ Expect(result.BitRate).To(Equal(906)) // format-level: 906900 bps -> 906 kbps
+ Expect(result.Profile).To(BeEmpty()) // no profile field in real output
+ })
+
+ It("parses Opus with format-level bit_rate fallback (real ffprobe output)", func() {
+ // Real: Opus stream-level bit_rate is absent; format-level is used as fallback.
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"opus","codec_long_name":"Opus (Opus Interactive Audio Codec)",` +
+ `"codec_type":"audio","sample_fmt":"fltp","sample_rate":"48000","channels":2,` +
+ `"channel_layout":"stereo","bits_per_sample":0}],` +
+ `"format":{"bit_rate":"128000"}}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("opus"))
+ Expect(result.SampleRate).To(Equal(48000))
+ Expect(result.Channels).To(Equal(2))
+ Expect(result.BitRate).To(Equal(128)) // format-level: 128000 bps -> 128 kbps
+ Expect(result.BitDepth).To(Equal(0))
+ })
+
+ It("parses WAV/PCM with bits_per_sample (real ffprobe output)", func() {
+ // Real: WAV uses bits_per_sample directly
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"pcm_s16le","codec_long_name":"PCM signed 16-bit little-endian",` +
+ `"codec_type":"audio","sample_fmt":"s16","sample_rate":"44100","channels":2,` +
+ `"bits_per_sample":16,"bit_rate":"1411200"}]}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("pcm_s16le"))
+ Expect(result.SampleRate).To(Equal(44100))
+ Expect(result.Channels).To(Equal(2))
+ Expect(result.BitDepth).To(Equal(16))
+ Expect(result.BitRate).To(Equal(1411))
+ })
+
+ It("parses ALAC in m4a container (real ffprobe output)", func() {
+ // Real: Beatles - You Can't Do That (2023 Mix), ALAC 16-bit
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"alac","codec_long_name":"ALAC (Apple Lossless Audio Codec)",` +
+ `"codec_type":"audio","sample_fmt":"s16p","sample_rate":"44100","channels":2,` +
+ `"channel_layout":"stereo","bits_per_sample":0,"bit_rate":"1011003",` +
+ `"bits_per_raw_sample":"16"},` +
+ `{"index":1,"codec_name":"mjpeg","codec_type":"video","profile":"Baseline"}]}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("alac"))
+ Expect(result.BitDepth).To(Equal(16)) // from bits_per_raw_sample
+ Expect(result.SampleRate).To(Equal(44100))
+ Expect(result.Channels).To(Equal(2))
+ Expect(result.BitRate).To(Equal(1011)) // 1011003 bps -> 1011 kbps
+ })
+
+ It("skips video-only streams", func() {
+ data := []byte(`{"streams":[{"index":0,"codec_name":"mjpeg","codec_type":"video","profile":"Baseline"}]}`)
+ _, err := parseProbeOutput(data)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("no audio stream"))
+ })
+
+ It("returns error for empty streams array", func() {
+ data := []byte(`{"streams":[]}`)
+ _, err := parseProbeOutput(data)
+ Expect(err).To(HaveOccurred())
+ })
+
+ It("returns error for invalid JSON", func() {
+ data := []byte(`not json`)
+ _, err := parseProbeOutput(data)
+ Expect(err).To(HaveOccurred())
+ })
+
+ It("parses HiRes multichannel FLAC with format-level bit_rate (real ffprobe output)", func() {
+ // Real: Pink Floyd - 192kHz/24-bit/7.1 surround FLAC
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"flac","codec_long_name":"FLAC (Free Lossless Audio Codec)",` +
+ `"codec_type":"audio","sample_fmt":"s32","sample_rate":"192000","channels":8,` +
+ `"channel_layout":"7.1","bits_per_sample":0,"bits_per_raw_sample":"24"},` +
+ `{"index":1,"codec_name":"mjpeg","codec_type":"video","profile":"Progressive"}],` +
+ `"format":{"bit_rate":"18432000"}}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("flac"))
+ Expect(result.SampleRate).To(Equal(192000))
+ Expect(result.BitDepth).To(Equal(24))
+ Expect(result.Channels).To(Equal(8))
+ Expect(result.BitRate).To(Equal(18432)) // format-level: 18432000 bps -> 18432 kbps
+ })
+
+ It("parses DSD/DSF file (real ffprobe output)", func() {
+ // Real: Yes - Owner of a Lonely Heart, DSD64 DSF
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"dsd_lsbf_planar",` +
+ `"codec_long_name":"DSD (Direct Stream Digital), least significant bit first, planar",` +
+ `"codec_type":"audio","sample_fmt":"fltp","sample_rate":"352800","channels":2,` +
+ `"channel_layout":"stereo","bits_per_sample":8,"bit_rate":"5644800"},` +
+ `{"index":1,"codec_name":"mjpeg","codec_type":"video","profile":"Baseline"}]}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Codec).To(Equal("dsd_lsbf_planar"))
+ Expect(result.BitDepth).To(Equal(8)) // DSD reports 8 bits_per_sample
+ Expect(result.SampleRate).To(Equal(352800)) // DSD64 sample rate
+ Expect(result.Channels).To(Equal(2))
+ Expect(result.BitRate).To(Equal(5644)) // 5644800 bps -> 5644 kbps
+ })
+
+ It("prefers stream-level bit_rate over format-level when both are present", func() {
+ // ALAC/DSD: stream has bit_rate, format also has bit_rate — stream wins
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"alac","codec_type":"audio","sample_fmt":"s16p",` +
+ `"sample_rate":"44100","channels":2,"bits_per_sample":0,` +
+ `"bit_rate":"1011003","bits_per_raw_sample":"16"}],` +
+ `"format":{"bit_rate":"1050000"}}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.BitRate).To(Equal(1011)) // stream-level: 1011003 bps -> 1011 kbps (not format's 1050)
+ })
+
+ It("returns BitRate 0 when neither stream nor format has bit_rate", func() {
+ data := []byte(`{"streams":[` +
+ `{"index":0,"codec_name":"flac","codec_type":"audio","sample_fmt":"s16",` +
+ `"sample_rate":"44100","channels":2,"bits_per_sample":0,"bits_per_raw_sample":"16"}],` +
+ `"format":{}}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.BitRate).To(Equal(0))
+ })
+
+ It("clears 'unknown' profile to empty string", func() {
+ data := []byte(`{"streams":[{"index":0,"codec_name":"flac",` +
+ `"codec_type":"audio","profile":"unknown","sample_rate":"44100",` +
+ `"channels":2,"bits_per_sample":0}]}`)
+ result, err := parseProbeOutput(data)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(result.Profile).To(BeEmpty())
+ })
+ })
+
+ Describe("FFmpeg", func() {
+ Context("when FFmpeg is available", func() {
+ var ff FFmpeg
+
+ BeforeEach(func() {
+ ffOnce = sync.Once{}
+ ff = New()
+ // Skip if FFmpeg is not available
+ if !ff.IsAvailable() {
+ Skip("FFmpeg not available on this system")
+ }
+ })
+
+ It("should interrupt transcoding when context is cancelled", func() {
+ ctx, cancel := context.WithTimeout(GinkgoT().Context(), 5*time.Second)
+ defer cancel()
+
+ // Use a command that generates audio indefinitely
+ // -f lavfi uses FFmpeg's built-in audio source
+ // -t 0 means no time limit (runs forever)
+ command := "ffmpeg -f lavfi -i sine=frequency=1000:duration=0 -f mp3 -"
+
+ // The input file is not used here, but we need to provide a valid path to the Transcode function
+ stream, err := ff.Transcode(ctx, TranscodeOptions{
+ Command: command,
+ Format: "mp3",
+ FilePath: "tests/fixtures/test.mp3",
+ BitRate: 128,
+ })
+ Expect(err).ToNot(HaveOccurred())
+ defer stream.Close()
+
+ // Read some data first to ensure FFmpeg is running
+ buf := make([]byte, 1024)
+ _, err = stream.Read(buf)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Cancel the context
+ cancel()
+
+ // Next read should fail due to cancelled context
+ _, err = stream.Read(buf)
+ Expect(err).To(HaveOccurred())
+ })
+
+ It("should handle immediate context cancellation", func() {
+ ctx, cancel := context.WithCancel(GinkgoT().Context())
+ cancel() // Cancel immediately
+
+ // This should fail immediately
+ _, err := ff.Transcode(ctx, TranscodeOptions{
+ Command: "ffmpeg -i %s -f mp3 -",
+ Format: "mp3",
+ FilePath: "tests/fixtures/test.mp3",
+ BitRate: 128,
+ })
+ Expect(err).To(MatchError(context.Canceled))
+ })
+ })
+
+ Context("stderr capture", func() {
+ BeforeEach(func() {
+ if runtime.GOOS == "windows" {
+ Skip("stderr capture tests use /bin/sh, skipping on Windows")
+ }
+ })
+
+ It("should include stderr in error when process fails", func() {
+ ff := &ffmpeg{}
+ ctx := GinkgoT().Context()
+
+ // Directly call start() with a bash command that writes to stderr and fails
+ args := []string{"/bin/sh", "-c", "echo 'codec not found: libopus' >&2; exit 1"}
+ stream, err := ff.start(ctx, args)
+ Expect(err).ToNot(HaveOccurred())
+ defer stream.Close()
+
+ buf := make([]byte, 1024)
+ _, err = stream.Read(buf)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("codec not found: libopus"))
+ })
+
+ It("should not include stderr in error when process succeeds", func() {
+ ff := &ffmpeg{}
+ ctx := GinkgoT().Context()
+
+ // Command that writes to stderr but exits successfully
+ args := []string{"/bin/sh", "-c", "echo 'warning: something' >&2; printf 'output'"}
+ stream, err := ff.start(ctx, args)
+ Expect(err).ToNot(HaveOccurred())
+ defer stream.Close()
+
+ buf := make([]byte, 1024)
+ n, err := stream.Read(buf)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(buf[:n])).To(Equal("output"))
+ })
+ })
+
+ Context("with mock process behavior", func() {
+ var longRunningCmd string
+ BeforeEach(func() {
+ // Use a long-running command for testing cancellation
+ switch runtime.GOOS {
+ case "windows":
+ // Use PowerShell's Start-Sleep
+ ffmpegPath = "powershell"
+ longRunningCmd = "powershell -Command Start-Sleep -Seconds 10"
+ default:
+ // Use sleep on Unix-like systems
+ ffmpegPath = "sleep"
+ longRunningCmd = "sleep 10"
+ }
+ })
+
+ It("should terminate the underlying process when context is cancelled", func() {
+ ff := New()
+ ctx, cancel := context.WithTimeout(GinkgoT().Context(), 5*time.Second)
+ defer cancel()
+
+ // Start a process that will run for a while
+ stream, err := ff.Transcode(ctx, TranscodeOptions{
+ Command: longRunningCmd,
+ FilePath: "tests/fixtures/test.mp3",
+ })
+ Expect(err).ToNot(HaveOccurred())
+ defer stream.Close()
+
+ // Give the process time to start
+ time.Sleep(50 * time.Millisecond)
+
+ // Cancel the context
+ cancel()
+
+ // Try to read from the stream, which should fail
+ buf := make([]byte, 100)
+ _, err = stream.Read(buf)
+ Expect(err).To(HaveOccurred(), "Expected stream to be closed due to process termination")
+
+ // Verify the stream is closed by attempting another read
+ _, err = stream.Read(buf)
+ Expect(err).To(HaveOccurred())
+ })
+ })
+ })
})
diff --git a/core/image_upload.go b/core/image_upload.go
new file mode 100644
index 000000000..c2432b647
--- /dev/null
+++ b/core/image_upload.go
@@ -0,0 +1,71 @@
+package core
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/utils"
+)
+
+type ImageUploadService interface {
+ SetImage(ctx context.Context, entityType string, entityID string, name string, oldPath string, reader io.Reader, ext string) (filename string, err error)
+ RemoveImage(ctx context.Context, path string) error
+}
+
+type imageUploadService struct{}
+
+func NewImageUploadService() ImageUploadService {
+ return &imageUploadService{}
+}
+
+func (s *imageUploadService) SetImage(ctx context.Context, entityType string, entityID string, name string, oldPath string, reader io.Reader, ext string) (string, error) {
+ filename := imageFilename(entityID, name, ext)
+ absPath := model.UploadedImagePath(entityType, filename)
+
+ if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {
+ return "", fmt.Errorf("creating image directory: %w", err)
+ }
+
+ // Remove old image if it exists
+ if oldPath != "" {
+ if err := os.Remove(oldPath); err != nil && !os.IsNotExist(err) {
+ log.Warn(ctx, "Failed to remove old image", "path", oldPath, err)
+ }
+ }
+
+ // Save new image
+ f, err := os.Create(absPath)
+ if err != nil {
+ return "", fmt.Errorf("creating image file: %w", err)
+ }
+ defer f.Close()
+
+ if _, err := io.Copy(f, reader); err != nil {
+ return "", fmt.Errorf("writing image file: %w", err)
+ }
+
+ return filename, nil
+}
+
+func (s *imageUploadService) RemoveImage(ctx context.Context, path string) error {
+ if path == "" {
+ return nil
+ }
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("removing image %q: %w", path, err)
+ }
+ return nil
+}
+
+func imageFilename(id, name, ext string) string {
+ clean := utils.CleanFileName(name)
+ if clean == "" {
+ return id + ext
+ }
+ return id + "_" + clean + ext
+}
diff --git a/core/image_upload_test.go b/core/image_upload_test.go
new file mode 100644
index 000000000..d13a04775
--- /dev/null
+++ b/core/image_upload_test.go
@@ -0,0 +1,99 @@
+package core_test
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/core"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("ImageUploadService", func() {
+ var svc core.ImageUploadService
+ var tmpDir string
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ tmpDir = GinkgoT().TempDir()
+ conf.Server.DataFolder = tmpDir
+ svc = core.NewImageUploadService()
+ })
+
+ Describe("SetImage", func() {
+ It("creates directory and saves image file", func() {
+ ctx := context.Background()
+ reader := strings.NewReader("fake image data")
+ filename, err := svc.SetImage(ctx, consts.EntityArtist, "ar-1", "Pink Floyd", "", reader, ".jpg")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(filename).To(Equal("ar-1_pink_floyd.jpg"))
+
+ absPath := filepath.Join(tmpDir, "artwork", "artist", "ar-1_pink_floyd.jpg")
+ data, err := os.ReadFile(absPath)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("fake image data"))
+ })
+
+ It("falls back to ID-only filename when name cleans to empty", func() {
+ ctx := context.Background()
+ reader := strings.NewReader("data")
+ filename, err := svc.SetImage(ctx, consts.EntityPlaylist, "pl-1", "!!!", "", reader, ".png")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(filename).To(Equal("pl-1.png"))
+ })
+
+ It("removes old image when replacing", func() {
+ ctx := context.Background()
+ oldDir := filepath.Join(tmpDir, "artwork", "artist")
+ Expect(os.MkdirAll(oldDir, 0755)).To(Succeed())
+ oldFile := filepath.Join(oldDir, "ar-1_old.png")
+ Expect(os.WriteFile(oldFile, []byte("old"), 0600)).To(Succeed())
+
+ reader := strings.NewReader("new image")
+ _, err := svc.SetImage(ctx, consts.EntityArtist, "ar-1", "New Name", oldFile, reader, ".jpg")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(oldFile).ToNot(BeAnExistingFile())
+
+ newPath := filepath.Join(oldDir, "ar-1_new_name.jpg")
+ Expect(newPath).To(BeAnExistingFile())
+ })
+
+ It("ignores missing old file without error", func() {
+ ctx := context.Background()
+ reader := strings.NewReader("data")
+ _, err := svc.SetImage(ctx, consts.EntityArtist, "ar-1", "Name", "/nonexistent/path.jpg", reader, ".jpg")
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
+
+ Describe("RemoveImage", func() {
+ It("removes the file at the given path", func() {
+ ctx := context.Background()
+ dir := filepath.Join(tmpDir, "artwork", "artist")
+ Expect(os.MkdirAll(dir, 0755)).To(Succeed())
+ path := filepath.Join(dir, "ar-1_test.jpg")
+ Expect(os.WriteFile(path, []byte("img"), 0600)).To(Succeed())
+
+ err := svc.RemoveImage(ctx, path)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(path).ToNot(BeAnExistingFile())
+ })
+
+ It("succeeds when file does not exist", func() {
+ ctx := context.Background()
+ err := svc.RemoveImage(ctx, "/nonexistent/file.jpg")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("succeeds with empty path", func() {
+ ctx := context.Background()
+ err := svc.RemoveImage(ctx, "")
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
+})
diff --git a/core/library.go b/core/library.go
index 7abd35c8f..0bf3be9fa 100644
--- a/core/library.go
+++ b/core/library.go
@@ -21,11 +21,6 @@ import (
"github.com/navidrome/navidrome/utils/slice"
)
-// Scanner interface for triggering scans
-type Scanner interface {
- ScanAll(ctx context.Context, fullScan bool) (warnings []string, err error)
-}
-
// Watcher interface for managing file system watchers
type Watcher interface {
Watch(ctx context.Context, lib *model.Library) error
@@ -42,19 +37,21 @@ type Library interface {
}
type libraryService struct {
- ds model.DataStore
- scanner Scanner
- watcher Watcher
- broker events.Broker
+ ds model.DataStore
+ scanner model.Scanner
+ watcher Watcher
+ broker events.Broker
+ pluginManager PluginUnloader
}
// NewLibrary creates a new Library service
-func NewLibrary(ds model.DataStore, scanner Scanner, watcher Watcher, broker events.Broker) Library {
+func NewLibrary(ds model.DataStore, scanner model.Scanner, watcher Watcher, broker events.Broker, pluginManager PluginUnloader) Library {
return &libraryService{
- ds: ds,
- scanner: scanner,
- watcher: watcher,
- broker: broker,
+ ds: ds,
+ scanner: scanner,
+ watcher: watcher,
+ broker: broker,
+ pluginManager: pluginManager,
}
}
@@ -146,6 +143,7 @@ func (s *libraryService) NewRepository(ctx context.Context) rest.Repository {
scanner: s.scanner,
watcher: s.watcher,
broker: s.broker,
+ pluginManager: s.pluginManager,
}
return wrapper
}
@@ -153,14 +151,15 @@ func (s *libraryService) NewRepository(ctx context.Context) rest.Repository {
type libraryRepositoryWrapper struct {
rest.Repository
model.LibraryRepository
- ctx context.Context
- ds model.DataStore
- scanner Scanner
- watcher Watcher
- broker events.Broker
+ ctx context.Context
+ ds model.DataStore
+ scanner model.Scanner
+ watcher Watcher
+ broker events.Broker
+ pluginManager PluginUnloader
}
-func (r *libraryRepositoryWrapper) Save(entity interface{}) (string, error) {
+func (r *libraryRepositoryWrapper) Save(entity any) (string, error) {
lib := entity.(*model.Library)
if err := r.validateLibrary(lib); err != nil {
return "", err
@@ -192,7 +191,7 @@ func (r *libraryRepositoryWrapper) Save(entity interface{}) (string, error) {
return strconv.Itoa(lib.ID), nil
}
-func (r *libraryRepositoryWrapper) Update(id string, entity interface{}, cols ...string) error {
+func (r *libraryRepositoryWrapper) Update(id string, entity any, _ ...string) error {
lib := entity.(*model.Library)
libID, err := strconv.Atoi(id)
if err != nil {
@@ -277,6 +276,10 @@ func (r *libraryRepositoryWrapper) Delete(id string) error {
log.Debug(r.ctx, "Library deleted - sent refresh event", "libraryID", libID, "name", lib.Name)
}
+ // After successful deletion, check if any plugins were auto-disabled
+ // and need to be unloaded from memory
+ r.pluginManager.UnloadDisabledPlugins(r.ctx)
+
return nil
}
diff --git a/core/library_test.go b/core/library_test.go
index bfbb4300a..175d9c37d 100644
--- a/core/library_test.go
+++ b/core/library_test.go
@@ -9,7 +9,7 @@ import (
"sync"
"github.com/deluan/rest"
- _ "github.com/navidrome/navidrome/adapters/taglib" // Register taglib extractor
+ _ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core"
_ "github.com/navidrome/navidrome/core/storage/local" // Register local storage
@@ -29,9 +29,10 @@ var _ = Describe("Library Service", func() {
var userRepo *tests.MockedUserRepo
var ctx context.Context
var tempDir string
- var scanner *mockScanner
+ var scanner *tests.MockScanner
var watcherManager *mockWatcherManager
var broker *mockEventBroker
+ var pluginManager *mockPluginUnloader
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
@@ -43,14 +44,16 @@ var _ = Describe("Library Service", func() {
ds.MockedUser = userRepo
// Create a mock scanner that tracks calls
- scanner = &mockScanner{}
+ scanner = tests.NewMockScanner()
// Create a mock watcher manager
watcherManager = &mockWatcherManager{
libraryStates: make(map[int]model.Library),
}
// Create a mock event broker
broker = &mockEventBroker{}
- service = core.NewLibrary(ds, scanner, watcherManager, broker)
+ // Create a mock plugin unloader
+ pluginManager = &mockPluginUnloader{}
+ service = core.NewLibrary(ds, scanner, watcherManager, broker, pluginManager)
ctx = context.Background()
// Create a temporary directory for testing valid paths
@@ -616,11 +619,12 @@ var _ = Describe("Library Service", func() {
// Wait briefly for the goroutine to complete
Eventually(func() int {
- return scanner.len()
+ return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1))
// Verify scan was called with correct parameters
- Expect(scanner.ScanCalls[0].FullScan).To(BeFalse()) // Should be quick scan
+ calls := scanner.GetScanAllCalls()
+ Expect(calls[0].FullScan).To(BeFalse()) // Should be quick scan
})
It("triggers scan when updating library path", func() {
@@ -641,11 +645,12 @@ var _ = Describe("Library Service", func() {
// Wait briefly for the goroutine to complete
Eventually(func() int {
- return scanner.len()
+ return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1))
// Verify scan was called with correct parameters
- Expect(scanner.ScanCalls[0].FullScan).To(BeFalse()) // Should be quick scan
+ calls := scanner.GetScanAllCalls()
+ Expect(calls[0].FullScan).To(BeFalse()) // Should be quick scan
})
It("does not trigger scan when updating library without path change", func() {
@@ -661,7 +666,7 @@ var _ = Describe("Library Service", func() {
// Wait a bit to ensure no scan was triggered
Consistently(func() int {
- return scanner.len()
+ return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0))
})
@@ -674,7 +679,7 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since creation failed
Consistently(func() int {
- return scanner.len()
+ return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0))
})
@@ -691,7 +696,7 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since update failed
Consistently(func() int {
- return scanner.len()
+ return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0))
})
@@ -707,11 +712,12 @@ var _ = Describe("Library Service", func() {
// Wait briefly for the goroutine to complete
Eventually(func() int {
- return scanner.len()
+ return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1))
// Verify scan was called with correct parameters
- Expect(scanner.ScanCalls[0].FullScan).To(BeFalse()) // Should be quick scan
+ calls := scanner.GetScanAllCalls()
+ Expect(calls[0].FullScan).To(BeFalse()) // Should be quick scan
})
It("does not trigger scan when library deletion fails", func() {
@@ -721,7 +727,7 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since deletion failed
Consistently(func() int {
- return scanner.len()
+ return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0))
})
@@ -866,31 +872,43 @@ var _ = Describe("Library Service", func() {
Expect(broker.Events).To(HaveLen(1))
})
})
+
+ Describe("Plugin Manager Integration", func() {
+ var repo rest.Persistable
+
+ BeforeEach(func() {
+ // Reset the call count for each test
+ pluginManager.unloadCalls = 0
+ r := service.NewRepository(ctx)
+ repo = r.(rest.Persistable)
+ })
+
+ It("calls UnloadDisabledPlugins after successful library deletion", func() {
+ libraryRepo.SetData(model.Libraries{
+ {ID: 2, Name: "Library to Delete", Path: tempDir},
+ })
+
+ err := repo.Delete("2")
+ Expect(err).NotTo(HaveOccurred())
+ Expect(pluginManager.unloadCalls).To(Equal(1))
+ })
+
+ It("does not call UnloadDisabledPlugins when library deletion fails", func() {
+ // Try to delete non-existent library
+ err := repo.Delete("999")
+ Expect(err).To(HaveOccurred())
+ Expect(pluginManager.unloadCalls).To(Equal(0))
+ })
+ })
})
-// mockScanner provides a simple mock implementation of core.Scanner for testing
-type mockScanner struct {
- ScanCalls []ScanCall
- mu sync.RWMutex
+// mockPluginUnloader is a simple mock for testing UnloadDisabledPlugins calls
+type mockPluginUnloader struct {
+ unloadCalls int
}
-type ScanCall struct {
- FullScan bool
-}
-
-func (m *mockScanner) ScanAll(ctx context.Context, fullScan bool) (warnings []string, err error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- m.ScanCalls = append(m.ScanCalls, ScanCall{
- FullScan: fullScan,
- })
- return []string{}, nil
-}
-
-func (m *mockScanner) len() int {
- m.mu.RLock()
- defer m.mu.RUnlock()
- return len(m.ScanCalls)
+func (m *mockPluginUnloader) UnloadDisabledPlugins(ctx context.Context) {
+ m.unloadCalls++
}
// mockWatcherManager provides a simple mock implementation of core.Watcher for testing
diff --git a/core/lyrics/lyrics.go b/core/lyrics/lyrics.go
index 858a3ffd8..758053042 100644
--- a/core/lyrics/lyrics.go
+++ b/core/lyrics/lyrics.go
@@ -9,23 +9,45 @@ import (
"github.com/navidrome/navidrome/model"
)
-func GetLyrics(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) {
+// Lyrics can fetch lyrics for a media file.
+type Lyrics interface {
+ GetLyrics(ctx context.Context, mf *model.MediaFile) (model.LyricList, error)
+}
+
+// PluginLoader discovers and loads lyrics provider plugins.
+type PluginLoader interface {
+ LoadLyricsProvider(name string) (Lyrics, bool)
+}
+
+type lyricsService struct {
+ pluginLoader PluginLoader
+}
+
+// NewLyrics creates a new lyrics service. pluginLoader may be nil if no plugin
+// system is available.
+func NewLyrics(pluginLoader PluginLoader) Lyrics {
+ return &lyricsService{pluginLoader: pluginLoader}
+}
+
+// GetLyrics returns lyrics for the given media file, trying sources in the
+// order specified by conf.Server.LyricsPriority.
+func (l *lyricsService) GetLyrics(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) {
var lyricsList model.LyricList
var err error
- for pattern := range strings.SplitSeq(strings.ToLower(conf.Server.LyricsPriority), ",") {
+ for pattern := range strings.SplitSeq(conf.Server.LyricsPriority, ",") {
pattern = strings.TrimSpace(pattern)
switch {
- case pattern == "embedded":
+ case strings.EqualFold(pattern, "embedded"):
lyricsList, err = fromEmbedded(ctx, mf)
case strings.HasPrefix(pattern, "."):
- lyricsList, err = fromExternalFile(ctx, mf, pattern)
+ lyricsList, err = fromExternalFile(ctx, mf, strings.ToLower(pattern))
default:
- log.Error(ctx, "Invalid lyric pattern", "pattern", pattern)
+ lyricsList, err = l.fromPlugin(ctx, mf, pattern)
}
if err != nil {
- log.Error(ctx, "error parsing lyrics", "source", pattern, err)
+ log.Error(ctx, "error getting lyrics", "source", pattern, err)
}
if len(lyricsList) > 0 {
diff --git a/core/lyrics/lyrics_test.go b/core/lyrics/lyrics_test.go
index f4197ccf6..2e495a714 100644
--- a/core/lyrics/lyrics_test.go
+++ b/core/lyrics/lyrics_test.go
@@ -3,6 +3,7 @@ package lyrics_test
import (
"context"
"encoding/json"
+ "fmt"
"os"
"github.com/navidrome/navidrome/conf"
@@ -72,7 +73,8 @@ var _ = Describe("sources", func() {
DescribeTable("Lyrics Priority", func(priority string, expected model.LyricList) {
conf.Server.LyricsPriority = priority
- list, err := lyrics.GetLyrics(ctx, &mf)
+ svc := lyrics.NewLyrics(nil)
+ list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil())
Expect(list).To(Equal(expected))
},
@@ -107,7 +109,8 @@ var _ = Describe("sources", func() {
It("should fallback to embedded if an error happens when parsing file", func() {
conf.Server.LyricsPriority = ".mp3,embedded"
- list, err := lyrics.GetLyrics(ctx, &mf)
+ svc := lyrics.NewLyrics(nil)
+ list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil())
Expect(list).To(Equal(embeddedLyrics))
})
@@ -115,10 +118,109 @@ var _ = Describe("sources", func() {
It("should return nothing if error happens when trying to parse file", func() {
conf.Server.LyricsPriority = ".mp3"
- list, err := lyrics.GetLyrics(ctx, &mf)
+ svc := lyrics.NewLyrics(nil)
+ list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil())
Expect(list).To(BeEmpty())
})
})
})
+
+ Context("plugin sources", func() {
+ var mockLoader *mockPluginLoader
+
+ BeforeEach(func() {
+ mockLoader = &mockPluginLoader{}
+ })
+
+ It("should return lyrics from a plugin", func() {
+ conf.Server.LyricsPriority = "test-lyrics-plugin"
+ mockLoader.lyrics = unsyncedLyrics
+ svc := lyrics.NewLyrics(mockLoader)
+ list, err := svc.GetLyrics(ctx, &mf)
+ Expect(err).To(BeNil())
+ Expect(list).To(Equal(unsyncedLyrics))
+ })
+
+ It("should try plugin after embedded returns nothing", func() {
+ conf.Server.LyricsPriority = "embedded,test-lyrics-plugin"
+ mf.Lyrics = "" // No embedded lyrics
+ mockLoader.lyrics = unsyncedLyrics
+ svc := lyrics.NewLyrics(mockLoader)
+ list, err := svc.GetLyrics(ctx, &mf)
+ Expect(err).To(BeNil())
+ Expect(list).To(Equal(unsyncedLyrics))
+ })
+
+ It("should skip plugin if embedded has lyrics", func() {
+ conf.Server.LyricsPriority = "embedded,test-lyrics-plugin"
+ mockLoader.lyrics = unsyncedLyrics
+ svc := lyrics.NewLyrics(mockLoader)
+ list, err := svc.GetLyrics(ctx, &mf)
+ Expect(err).To(BeNil())
+ Expect(list).To(Equal(embeddedLyrics)) // embedded wins
+ })
+
+ It("should skip unknown plugin names gracefully", func() {
+ conf.Server.LyricsPriority = "nonexistent-plugin,embedded"
+ mockLoader.notFound = true
+ svc := lyrics.NewLyrics(mockLoader)
+ list, err := svc.GetLyrics(ctx, &mf)
+ Expect(err).To(BeNil())
+ Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
+ })
+
+ It("should preserve plugin name case from config", func() {
+ conf.Server.LyricsPriority = "MyLyricsPlugin"
+ mockLoader.pluginName = "MyLyricsPlugin"
+ mockLoader.lyrics = unsyncedLyrics
+ svc := lyrics.NewLyrics(mockLoader)
+ list, err := svc.GetLyrics(ctx, &mf)
+ Expect(err).To(BeNil())
+ Expect(list).To(Equal(unsyncedLyrics))
+ })
+
+ It("should handle plugin error gracefully", func() {
+ conf.Server.LyricsPriority = "test-lyrics-plugin,embedded"
+ mockLoader.err = fmt.Errorf("plugin error")
+ svc := lyrics.NewLyrics(mockLoader)
+ list, err := svc.GetLyrics(ctx, &mf)
+ Expect(err).To(BeNil())
+ Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
+ })
+ })
})
+
+type mockPluginLoader struct {
+ lyrics model.LyricList
+ err error
+ notFound bool
+ pluginName string // expected plugin name (exact match, like real manager)
+}
+
+func (m *mockPluginLoader) PluginNames(_ string) []string {
+ if m.notFound {
+ return nil
+ }
+ return []string{"test-lyrics-plugin"}
+}
+
+func (m *mockPluginLoader) LoadLyricsProvider(name string) (lyrics.Lyrics, bool) {
+ if m.notFound {
+ return nil, false
+ }
+ // If pluginName is set, require exact match (like the real plugin manager)
+ if m.pluginName != "" && name != m.pluginName {
+ return nil, false
+ }
+ return &mockLyricsProvider{lyrics: m.lyrics, err: m.err}, true
+}
+
+type mockLyricsProvider struct {
+ lyrics model.LyricList
+ err error
+}
+
+func (m *mockLyricsProvider) GetLyrics(_ context.Context, _ *model.MediaFile) (model.LyricList, error) {
+ return m.lyrics, m.err
+}
diff --git a/core/lyrics/sources.go b/core/lyrics/sources.go
index 6d4a4cc6f..82a10ca41 100644
--- a/core/lyrics/sources.go
+++ b/core/lyrics/sources.go
@@ -8,6 +8,7 @@ import (
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/utils/ioutils"
)
func fromEmbedded(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) {
@@ -27,8 +28,7 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) (
externalLyric := basePath[0:len(basePath)-len(ext)] + suffix
- contents, err := os.ReadFile(externalLyric)
-
+ contents, err := ioutils.UTF8ReadFile(externalLyric)
if errors.Is(err, os.ErrNotExist) {
log.Trace(ctx, "no lyrics found at path", "path", externalLyric)
return nil, nil
@@ -49,3 +49,27 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) (
return model.LyricList{*lyrics}, nil
}
+
+// fromPlugin attempts to load lyrics from a plugin with the given name.
+func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, pluginName string) (model.LyricList, error) {
+ if l.pluginLoader == nil {
+ log.Debug(ctx, "Invalid lyric source", "source", pluginName)
+ return nil, nil
+ }
+
+ provider, ok := l.pluginLoader.LoadLyricsProvider(pluginName)
+ if !ok {
+ log.Warn(ctx, "Lyrics plugin not found", "plugin", pluginName)
+ return nil, nil
+ }
+
+ lyricsList, err := provider.GetLyrics(ctx, mf)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(lyricsList) > 0 {
+ log.Trace(ctx, "Retrieved lyrics from plugin", "plugin", pluginName, "count", len(lyricsList))
+ }
+ return lyricsList, nil
+}
diff --git a/core/lyrics/sources_test.go b/core/lyrics/sources_test.go
index e92564c00..b3d502101 100644
--- a/core/lyrics/sources_test.go
+++ b/core/lyrics/sources_test.go
@@ -108,5 +108,39 @@ var _ = Describe("sources", func() {
},
}))
})
+
+ It("should handle LRC files with UTF-8 BOM marker (issue #4631)", func() {
+ // The function looks for , so we need to pass
+ // a MediaFile with .mp3 path and look for .lrc suffix
+ mf := model.MediaFile{Path: "tests/fixtures/bom-test.mp3"}
+ lyrics, err := fromExternalFile(ctx, &mf, ".lrc")
+
+ Expect(err).To(BeNil())
+ Expect(lyrics).ToNot(BeNil())
+ Expect(lyrics).To(HaveLen(1))
+
+ // The critical assertion: even with BOM, synced should be true
+ Expect(lyrics[0].Synced).To(BeTrue(), "Lyrics with BOM marker should be recognized as synced")
+ Expect(lyrics[0].Line).To(HaveLen(1))
+ Expect(lyrics[0].Line[0].Start).To(Equal(gg.P(int64(0))))
+ Expect(lyrics[0].Line[0].Value).To(ContainSubstring("作曲"))
+ })
+
+ It("should handle UTF-16 LE encoded LRC files", func() {
+ mf := model.MediaFile{Path: "tests/fixtures/bom-utf16-test.mp3"}
+ lyrics, err := fromExternalFile(ctx, &mf, ".lrc")
+
+ Expect(err).To(BeNil())
+ Expect(lyrics).ToNot(BeNil())
+ Expect(lyrics).To(HaveLen(1))
+
+ // UTF-16 should be properly converted to UTF-8
+ Expect(lyrics[0].Synced).To(BeTrue(), "UTF-16 encoded lyrics should be recognized as synced")
+ Expect(lyrics[0].Line).To(HaveLen(2))
+ Expect(lyrics[0].Line[0].Start).To(Equal(gg.P(int64(18800))))
+ Expect(lyrics[0].Line[0].Value).To(Equal("We're no strangers to love"))
+ Expect(lyrics[0].Line[1].Start).To(Equal(gg.P(int64(22801))))
+ Expect(lyrics[0].Line[1].Value).To(Equal("You know the rules and so do I"))
+ })
})
})
diff --git a/core/maintenance.go b/core/maintenance.go
new file mode 100644
index 000000000..13d1141d3
--- /dev/null
+++ b/core/maintenance.go
@@ -0,0 +1,224 @@
+package core
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "sync"
+ "time"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/utils/slice"
+)
+
+type Maintenance interface {
+ // DeleteMissingFiles deletes specific missing files by their IDs
+ DeleteMissingFiles(ctx context.Context, ids []string) error
+ // DeleteAllMissingFiles deletes all files marked as missing
+ DeleteAllMissingFiles(ctx context.Context) error
+}
+
+type maintenanceService struct {
+ ds model.DataStore
+ wg sync.WaitGroup
+}
+
+func NewMaintenance(ds model.DataStore) Maintenance {
+ return &maintenanceService{
+ ds: ds,
+ }
+}
+
+func (s *maintenanceService) DeleteMissingFiles(ctx context.Context, ids []string) error {
+ return s.deleteMissing(ctx, ids)
+}
+
+func (s *maintenanceService) DeleteAllMissingFiles(ctx context.Context) error {
+ return s.deleteMissing(ctx, nil)
+}
+
+// deleteMissing handles the deletion of missing files and triggers necessary cleanup operations
+func (s *maintenanceService) deleteMissing(ctx context.Context, ids []string) error {
+ // Track affected album IDs before deletion for refresh
+ affectedAlbumIDs, err := s.getAffectedAlbumIDs(ctx, ids)
+ if err != nil {
+ log.Warn(ctx, "Error tracking affected albums for refresh", err)
+ // Don't fail the operation, just log the warning
+ }
+
+ // Delete missing files within a transaction
+ err = s.ds.WithTx(func(tx model.DataStore) error {
+ if len(ids) == 0 {
+ _, err := tx.MediaFile(ctx).DeleteAllMissing()
+ return err
+ }
+ return tx.MediaFile(ctx).DeleteMissing(ids)
+ })
+ if err != nil {
+ log.Error(ctx, "Error deleting missing tracks from DB", "ids", ids, err)
+ return err
+ }
+
+ // Run garbage collection to clean up orphaned records
+ if err := s.ds.GC(ctx); err != nil {
+ log.Error(ctx, "Error running GC after deleting missing tracks", err)
+ return err
+ }
+
+ // Refresh statistics in background
+ s.refreshStatsAsync(ctx, affectedAlbumIDs)
+
+ return nil
+}
+
+// refreshAlbums recalculates album attributes (size, duration, song count, etc.) from media files.
+// It uses batch queries to minimize database round-trips for efficiency.
+func (s *maintenanceService) refreshAlbums(ctx context.Context, albumIDs []string) error {
+ if len(albumIDs) == 0 {
+ return nil
+ }
+
+ log.Debug(ctx, "Refreshing albums", "count", len(albumIDs))
+
+ // Process in chunks to avoid query size limits
+ const chunkSize = 100
+ for chunk := range slice.CollectChunks(slices.Values(albumIDs), chunkSize) {
+ if err := s.refreshAlbumChunk(ctx, chunk); err != nil {
+ return fmt.Errorf("refreshing album chunk: %w", err)
+ }
+ }
+
+ log.Debug(ctx, "Successfully refreshed albums", "count", len(albumIDs))
+ return nil
+}
+
+// refreshAlbumChunk processes a single chunk of album IDs
+func (s *maintenanceService) refreshAlbumChunk(ctx context.Context, albumIDs []string) error {
+ albumRepo := s.ds.Album(ctx)
+ mfRepo := s.ds.MediaFile(ctx)
+
+ // Batch load existing albums
+ albums, err := albumRepo.GetAll(model.QueryOptions{
+ Filters: squirrel.Eq{"album.id": albumIDs},
+ })
+ if err != nil {
+ return fmt.Errorf("loading albums: %w", err)
+ }
+
+ // Create a map for quick lookup
+ albumMap := make(map[string]*model.Album, len(albums))
+ for i := range albums {
+ albumMap[albums[i].ID] = &albums[i]
+ }
+
+ // Batch load all media files for these albums
+ mediaFiles, err := mfRepo.GetAll(model.QueryOptions{
+ Filters: squirrel.Eq{"album_id": albumIDs},
+ Sort: "album_id, path",
+ })
+ if err != nil {
+ return fmt.Errorf("loading media files: %w", err)
+ }
+
+ // Group media files by album ID
+ filesByAlbum := make(map[string]model.MediaFiles)
+ for i := range mediaFiles {
+ albumID := mediaFiles[i].AlbumID
+ filesByAlbum[albumID] = append(filesByAlbum[albumID], mediaFiles[i])
+ }
+
+ // Recalculate each album from its media files
+ for albumID, oldAlbum := range albumMap {
+ mfs, hasTracks := filesByAlbum[albumID]
+ if !hasTracks {
+ // Album has no tracks anymore, skip (will be cleaned up by GC)
+ log.Debug(ctx, "Skipping album with no tracks", "albumID", albumID)
+ continue
+ }
+
+ // Recalculate album from media files
+ newAlbum := mfs.ToAlbum()
+
+ // Only update if something changed (avoid unnecessary writes)
+ if !oldAlbum.Equals(newAlbum) {
+ // Preserve original timestamps
+ newAlbum.UpdatedAt = time.Now()
+ newAlbum.CreatedAt = oldAlbum.CreatedAt
+
+ if err := albumRepo.Put(&newAlbum); err != nil {
+ log.Error(ctx, "Error updating album during refresh", "albumID", albumID, err)
+ // Continue with other albums instead of failing entirely
+ continue
+ }
+ log.Trace(ctx, "Refreshed album", "albumID", albumID, "name", newAlbum.Name)
+ }
+ }
+
+ return nil
+}
+
+// getAffectedAlbumIDs returns distinct album IDs from missing media files
+func (s *maintenanceService) getAffectedAlbumIDs(ctx context.Context, ids []string) ([]string, error) {
+ var filters squirrel.Sqlizer = squirrel.Eq{"missing": true}
+ if len(ids) > 0 {
+ filters = squirrel.And{
+ squirrel.Eq{"missing": true},
+ squirrel.Eq{"media_file.id": ids},
+ }
+ }
+
+ mfs, err := s.ds.MediaFile(ctx).GetAll(model.QueryOptions{
+ Filters: filters,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // Extract unique album IDs
+ albumIDMap := make(map[string]struct{}, len(mfs))
+ for _, mf := range mfs {
+ if mf.AlbumID != "" {
+ albumIDMap[mf.AlbumID] = struct{}{}
+ }
+ }
+
+ albumIDs := make([]string, 0, len(albumIDMap))
+ for id := range albumIDMap {
+ albumIDs = append(albumIDs, id)
+ }
+
+ return albumIDs, nil
+}
+
+// refreshStatsAsync refreshes artist and album statistics in background goroutines
+func (s *maintenanceService) refreshStatsAsync(ctx context.Context, affectedAlbumIDs []string) {
+ // Refresh artist stats in background
+ s.wg.Go(func() {
+ bgCtx := request.AddValues(context.Background(), ctx)
+ if _, err := s.ds.Artist(bgCtx).RefreshStats(true); err != nil {
+ log.Error(bgCtx, "Error refreshing artist stats after deleting missing files", err)
+ } else {
+ log.Debug(bgCtx, "Successfully refreshed artist stats after deleting missing files")
+ }
+
+ // Refresh album stats in background if we have affected albums
+ if len(affectedAlbumIDs) > 0 {
+ if err := s.refreshAlbums(bgCtx, affectedAlbumIDs); err != nil {
+ log.Error(bgCtx, "Error refreshing album stats after deleting missing files", err)
+ } else {
+ log.Debug(bgCtx, "Successfully refreshed album stats after deleting missing files", "count", len(affectedAlbumIDs))
+ }
+ }
+ })
+}
+
+// Wait waits for all background goroutines to complete.
+// WARNING: This method is ONLY for testing. Never call this in production code.
+// Calling Wait() in production will block until ALL background operations complete
+// and may cause race conditions with new operations starting.
+func (s *maintenanceService) wait() {
+ s.wg.Wait()
+}
diff --git a/core/maintenance_test.go b/core/maintenance_test.go
new file mode 100644
index 000000000..09b442438
--- /dev/null
+++ b/core/maintenance_test.go
@@ -0,0 +1,364 @@
+package core
+
+import (
+ "context"
+ "errors"
+ "sync"
+
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/sirupsen/logrus"
+)
+
+var _ = Describe("Maintenance", func() {
+ var ds *tests.MockDataStore
+ var mfRepo *extendedMediaFileRepo
+ var service Maintenance
+ var ctx context.Context
+
+ BeforeEach(func() {
+ ctx = context.Background()
+ ctx = request.WithUser(ctx, model.User{ID: "user1", IsAdmin: true})
+
+ ds = createTestDataStore()
+ mfRepo = ds.MockedMediaFile.(*extendedMediaFileRepo)
+ service = NewMaintenance(ds)
+ })
+
+ Describe("DeleteMissingFiles", func() {
+ Context("with specific IDs", func() {
+ It("deletes specific missing files and runs GC", func() {
+ // Setup: mock missing files with album IDs
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ {ID: "mf2", AlbumID: "album2", Missing: true},
+ })
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf2"})
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mfRepo.deleteMissingCalled).To(BeTrue())
+ Expect(mfRepo.deletedIDs).To(Equal([]string{"mf1", "mf2"}))
+ Expect(ds.GCCalled).To(BeTrue(), "GC should be called after deletion")
+ })
+
+ It("triggers artist stats refresh and album refresh after deletion", func() {
+ artistRepo := ds.MockedArtist.(*extendedArtistRepo)
+ // Setup: mock missing files with albums
+ albumRepo := ds.MockedAlbum.(*extendedAlbumRepo)
+ albumRepo.SetData(model.Albums{
+ {ID: "album1", Name: "Test Album", SongCount: 5},
+ })
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ {ID: "mf2", AlbumID: "album1", Missing: false, Size: 1000, Duration: 180},
+ {ID: "mf3", AlbumID: "album1", Missing: false, Size: 2000, Duration: 200},
+ })
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1"})
+
+ Expect(err).ToNot(HaveOccurred())
+
+ // Wait for background goroutines to complete
+ service.(*maintenanceService).wait()
+
+ // RefreshStats should be called
+ Expect(artistRepo.IsRefreshStatsCalled()).To(BeTrue(), "Artist stats should be refreshed")
+
+ // Album should be updated with new calculated values
+ Expect(albumRepo.GetPutCallCount()).To(BeNumerically(">", 0), "Album.Put() should be called to refresh album data")
+ })
+
+ It("returns error if deletion fails", func() {
+ mfRepo.deleteMissingError = errors.New("delete failed")
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1"})
+
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("delete failed"))
+ })
+
+ It("continues even if album tracking fails", func() {
+ mfRepo.SetError(true)
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1"})
+
+ // Should not fail, just log warning
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mfRepo.deleteMissingCalled).To(BeTrue())
+ })
+
+ It("returns error if GC fails", func() {
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ })
+
+ // Set GC to return error
+ ds.GCError = errors.New("gc failed")
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1"})
+
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("gc failed"))
+ })
+ })
+
+ Context("album ID extraction", func() {
+ It("extracts unique album IDs from missing files", func() {
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ {ID: "mf2", AlbumID: "album1", Missing: true},
+ {ID: "mf3", AlbumID: "album2", Missing: true},
+ })
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf2", "mf3"})
+
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("skips files without album IDs", func() {
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "", Missing: true},
+ {ID: "mf2", AlbumID: "album1", Missing: true},
+ })
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf2"})
+
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
+ })
+
+ Describe("DeleteAllMissingFiles", func() {
+ It("deletes all missing files and runs GC", func() {
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ {ID: "mf2", AlbumID: "album2", Missing: true},
+ {ID: "mf3", AlbumID: "album3", Missing: true},
+ })
+
+ err := service.DeleteAllMissingFiles(ctx)
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(ds.GCCalled).To(BeTrue(), "GC should be called after deletion")
+ })
+
+ It("returns error if deletion fails", func() {
+ mfRepo.SetError(true)
+
+ err := service.DeleteAllMissingFiles(ctx)
+
+ Expect(err).To(HaveOccurred())
+ })
+
+ It("handles empty result gracefully", func() {
+ mfRepo.SetData(model.MediaFiles{})
+
+ err := service.DeleteAllMissingFiles(ctx)
+
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
+
+ Describe("Album refresh logic", func() {
+ var albumRepo *extendedAlbumRepo
+
+ BeforeEach(func() {
+ albumRepo = ds.MockedAlbum.(*extendedAlbumRepo)
+ })
+
+ Context("when album has no tracks after deletion", func() {
+ It("skips the album without updating it", func() {
+ // Setup album with no remaining tracks
+ albumRepo.SetData(model.Albums{
+ {ID: "album1", Name: "Empty Album", SongCount: 1},
+ })
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ })
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1"})
+
+ Expect(err).ToNot(HaveOccurred())
+
+ // Wait for background goroutines to complete
+ service.(*maintenanceService).wait()
+
+ // Album should NOT be updated because it has no tracks left
+ Expect(albumRepo.GetPutCallCount()).To(Equal(0), "Album with no tracks should not be updated")
+ })
+ })
+
+ Context("when Put fails for one album", func() {
+ It("continues processing other albums", func() {
+ albumRepo.SetData(model.Albums{
+ {ID: "album1", Name: "Album 1"},
+ {ID: "album2", Name: "Album 2"},
+ })
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ {ID: "mf2", AlbumID: "album1", Missing: false, Size: 1000, Duration: 180},
+ {ID: "mf3", AlbumID: "album2", Missing: true},
+ {ID: "mf4", AlbumID: "album2", Missing: false, Size: 2000, Duration: 200},
+ })
+
+ // Make Put fail on first call but succeed on subsequent calls
+ albumRepo.putError = errors.New("put failed")
+ albumRepo.failOnce = true
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf3"})
+
+ // Should not fail even if one album's Put fails
+ Expect(err).ToNot(HaveOccurred())
+
+ // Wait for background goroutines to complete
+ service.(*maintenanceService).wait()
+
+ // Put should have been called multiple times
+ Expect(albumRepo.GetPutCallCount()).To(BeNumerically(">", 0), "Put should be attempted")
+ })
+ })
+
+ Context("when media file loading fails", func() {
+ It("logs warning but continues when tracking affected albums fails", func() {
+ // Set up log capturing
+ hook, cleanup := tests.LogHook()
+ defer cleanup()
+
+ albumRepo.SetData(model.Albums{
+ {ID: "album1", Name: "Album 1"},
+ })
+ mfRepo.SetData(model.MediaFiles{
+ {ID: "mf1", AlbumID: "album1", Missing: true},
+ })
+ // Make GetAll fail when loading media files
+ mfRepo.SetError(true)
+
+ err := service.DeleteMissingFiles(ctx, []string{"mf1"})
+
+ // Deletion should succeed despite the tracking error
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mfRepo.deleteMissingCalled).To(BeTrue())
+
+ // Verify the warning was logged
+ Expect(hook.LastEntry()).ToNot(BeNil())
+ Expect(hook.LastEntry().Level).To(Equal(logrus.WarnLevel))
+ Expect(hook.LastEntry().Message).To(Equal("Error tracking affected albums for refresh"))
+ })
+ })
+ })
+})
+
+// Test helper to create a mock DataStore with controllable behavior
+func createTestDataStore() *tests.MockDataStore {
+ ds := &tests.MockDataStore{}
+
+ // Create extended album repo with Put tracking
+ albumRepo := &extendedAlbumRepo{
+ MockAlbumRepo: tests.CreateMockAlbumRepo(),
+ }
+ ds.MockedAlbum = albumRepo
+
+ // Create extended artist repo with RefreshStats tracking
+ artistRepo := &extendedArtistRepo{
+ MockArtistRepo: tests.CreateMockArtistRepo(),
+ }
+ ds.MockedArtist = artistRepo
+
+ // Create extended media file repo with DeleteMissing support
+ mfRepo := &extendedMediaFileRepo{
+ MockMediaFileRepo: tests.CreateMockMediaFileRepo(),
+ }
+ ds.MockedMediaFile = mfRepo
+
+ return ds
+}
+
+// Extension of MockMediaFileRepo to add DeleteMissing method
+type extendedMediaFileRepo struct {
+ *tests.MockMediaFileRepo
+ deleteMissingCalled bool
+ deletedIDs []string
+ deleteMissingError error
+}
+
+func (m *extendedMediaFileRepo) DeleteMissing(ids []string) error {
+ m.deleteMissingCalled = true
+ m.deletedIDs = ids
+ if m.deleteMissingError != nil {
+ return m.deleteMissingError
+ }
+ // Actually delete from the mock data
+ for _, id := range ids {
+ delete(m.Data, id)
+ }
+ return nil
+}
+
+// Extension of MockAlbumRepo to track Put calls
+type extendedAlbumRepo struct {
+ *tests.MockAlbumRepo
+ mu sync.RWMutex
+ putCallCount int
+ lastPutData *model.Album
+ putError error
+ failOnce bool
+}
+
+func (m *extendedAlbumRepo) Put(album *model.Album) error {
+ m.mu.Lock()
+ m.putCallCount++
+ m.lastPutData = album
+
+ // Handle failOnce behavior
+ var err error
+ if m.putError != nil {
+ if m.failOnce {
+ err = m.putError
+ m.putError = nil // Clear error after first failure
+ m.mu.Unlock()
+ return err
+ }
+ err = m.putError
+ m.mu.Unlock()
+ return err
+ }
+ m.mu.Unlock()
+
+ return m.MockAlbumRepo.Put(album)
+}
+
+func (m *extendedAlbumRepo) GetPutCallCount() int {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.putCallCount
+}
+
+// Extension of MockArtistRepo to track RefreshStats calls
+type extendedArtistRepo struct {
+ *tests.MockArtistRepo
+ mu sync.RWMutex
+ refreshStatsCalled bool
+ refreshStatsError error
+}
+
+func (m *extendedArtistRepo) RefreshStats(allArtists bool) (int64, error) {
+ m.mu.Lock()
+ m.refreshStatsCalled = true
+ err := m.refreshStatsError
+ m.mu.Unlock()
+
+ if err != nil {
+ return 0, err
+ }
+ return m.MockArtistRepo.RefreshStats(allArtists)
+}
+
+func (m *extendedArtistRepo) IsRefreshStatsCalled() bool {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.refreshStatsCalled
+}
diff --git a/core/media_streamer.go b/core/media_streamer.go
deleted file mode 100644
index b3593c4eb..000000000
--- a/core/media_streamer.go
+++ /dev/null
@@ -1,214 +0,0 @@
-package core
-
-import (
- "context"
- "fmt"
- "io"
- "mime"
- "os"
- "sync"
- "time"
-
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/consts"
- "github.com/navidrome/navidrome/core/ffmpeg"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/model/request"
- "github.com/navidrome/navidrome/utils/cache"
-)
-
-type MediaStreamer interface {
- NewStream(ctx context.Context, id string, reqFormat string, reqBitRate int, offset int) (*Stream, error)
- DoStream(ctx context.Context, mf *model.MediaFile, reqFormat string, reqBitRate int, reqOffset int) (*Stream, error)
-}
-
-type TranscodingCache cache.FileCache
-
-func NewMediaStreamer(ds model.DataStore, t ffmpeg.FFmpeg, cache TranscodingCache) MediaStreamer {
- return &mediaStreamer{ds: ds, transcoder: t, cache: cache}
-}
-
-type mediaStreamer struct {
- ds model.DataStore
- transcoder ffmpeg.FFmpeg
- cache cache.FileCache
-}
-
-type streamJob struct {
- ms *mediaStreamer
- mf *model.MediaFile
- filePath string
- format string
- bitRate int
- offset int
-}
-
-func (j *streamJob) Key() string {
- return fmt.Sprintf("%s.%s.%d.%s.%d", j.mf.ID, j.mf.UpdatedAt.Format(time.RFC3339Nano), j.bitRate, j.format, j.offset)
-}
-
-func (ms *mediaStreamer) NewStream(ctx context.Context, id string, reqFormat string, reqBitRate int, reqOffset int) (*Stream, error) {
- mf, err := ms.ds.MediaFile(ctx).Get(id)
- if err != nil {
- return nil, err
- }
-
- return ms.DoStream(ctx, mf, reqFormat, reqBitRate, reqOffset)
-}
-
-func (ms *mediaStreamer) DoStream(ctx context.Context, mf *model.MediaFile, reqFormat string, reqBitRate int, reqOffset int) (*Stream, error) {
- var format string
- var bitRate int
- var cached bool
- defer func() {
- log.Info(ctx, "Streaming file", "title", mf.Title, "artist", mf.Artist, "format", format, "cached", cached,
- "bitRate", bitRate, "user", userName(ctx), "transcoding", format != "raw",
- "originalFormat", mf.Suffix, "originalBitRate", mf.BitRate)
- }()
-
- format, bitRate = selectTranscodingOptions(ctx, ms.ds, mf, reqFormat, reqBitRate)
- s := &Stream{ctx: ctx, mf: mf, format: format, bitRate: bitRate}
- filePath := mf.AbsolutePath()
-
- if format == "raw" {
- log.Debug(ctx, "Streaming RAW file", "id", mf.ID, "path", filePath,
- "requestBitrate", reqBitRate, "requestFormat", reqFormat, "requestOffset", reqOffset,
- "originalBitrate", mf.BitRate, "originalFormat", mf.Suffix,
- "selectedBitrate", bitRate, "selectedFormat", format)
- f, err := os.Open(filePath)
- if err != nil {
- return nil, err
- }
- s.ReadCloser = f
- s.Seeker = f
- s.format = mf.Suffix
- return s, nil
- }
-
- job := &streamJob{
- ms: ms,
- mf: mf,
- filePath: filePath,
- format: format,
- bitRate: bitRate,
- offset: reqOffset,
- }
- r, err := ms.cache.Get(ctx, job)
- if err != nil {
- log.Error(ctx, "Error accessing transcoding cache", "id", mf.ID, err)
- return nil, err
- }
- cached = r.Cached
-
- s.ReadCloser = r
- s.Seeker = r.Seeker
-
- log.Debug(ctx, "Streaming TRANSCODED file", "id", mf.ID, "path", filePath,
- "requestBitrate", reqBitRate, "requestFormat", reqFormat, "requestOffset", reqOffset,
- "originalBitrate", mf.BitRate, "originalFormat", mf.Suffix,
- "selectedBitrate", bitRate, "selectedFormat", format, "cached", cached, "seekable", s.Seekable())
-
- return s, nil
-}
-
-type Stream struct {
- ctx context.Context
- mf *model.MediaFile
- bitRate int
- format string
- io.ReadCloser
- io.Seeker
-}
-
-func (s *Stream) Seekable() bool { return s.Seeker != nil }
-func (s *Stream) Duration() float32 { return s.mf.Duration }
-func (s *Stream) ContentType() string { return mime.TypeByExtension("." + s.format) }
-func (s *Stream) Name() string { return s.mf.Title + "." + s.format }
-func (s *Stream) ModTime() time.Time { return s.mf.UpdatedAt }
-func (s *Stream) EstimatedContentLength() int {
- return int(s.mf.Duration * float32(s.bitRate) / 8 * 1024)
-}
-
-// TODO This function deserves some love (refactoring)
-func selectTranscodingOptions(ctx context.Context, ds model.DataStore, mf *model.MediaFile, reqFormat string, reqBitRate int) (format string, bitRate int) {
- format = "raw"
- if reqFormat == "raw" {
- return format, 0
- }
- if reqFormat == mf.Suffix && reqBitRate == 0 {
- bitRate = mf.BitRate
- return format, bitRate
- }
- trc, hasDefault := request.TranscodingFrom(ctx)
- var cFormat string
- var cBitRate int
- if reqFormat != "" {
- cFormat = reqFormat
- } else {
- if hasDefault {
- cFormat = trc.TargetFormat
- cBitRate = trc.DefaultBitRate
- if p, ok := request.PlayerFrom(ctx); ok {
- cBitRate = p.MaxBitRate
- }
- } else if reqBitRate > 0 && reqBitRate < mf.BitRate && conf.Server.DefaultDownsamplingFormat != "" {
- // If no format is specified and no transcoding associated to the player, but a bitrate is specified,
- // and there is no transcoding set for the player, we use the default downsampling format.
- // But only if the requested bitRate is lower than the original bitRate.
- log.Debug("Default Downsampling", "Using default downsampling format", conf.Server.DefaultDownsamplingFormat)
- cFormat = conf.Server.DefaultDownsamplingFormat
- }
- }
- if reqBitRate > 0 {
- cBitRate = reqBitRate
- }
- if cBitRate == 0 && cFormat == "" {
- return format, bitRate
- }
- t, err := ds.Transcoding(ctx).FindByFormat(cFormat)
- if err == nil {
- format = t.TargetFormat
- if cBitRate != 0 {
- bitRate = cBitRate
- } else {
- bitRate = t.DefaultBitRate
- }
- }
- if format == mf.Suffix && bitRate >= mf.BitRate {
- format = "raw"
- bitRate = 0
- }
- return format, bitRate
-}
-
-var (
- onceTranscodingCache sync.Once
- instanceTranscodingCache TranscodingCache
-)
-
-func GetTranscodingCache() TranscodingCache {
- onceTranscodingCache.Do(func() {
- instanceTranscodingCache = NewTranscodingCache()
- })
- return instanceTranscodingCache
-}
-
-func NewTranscodingCache() TranscodingCache {
- return cache.NewFileCache("Transcoding", conf.Server.TranscodingCacheSize,
- consts.TranscodingCacheDir, consts.DefaultTranscodingCacheMaxItems,
- func(ctx context.Context, arg cache.Item) (io.Reader, error) {
- job := arg.(*streamJob)
- t, err := job.ms.ds.Transcoding(ctx).FindByFormat(job.format)
- if err != nil {
- log.Error(ctx, "Error loading transcoding command", "format", job.format, err)
- return nil, os.ErrInvalid
- }
- out, err := job.ms.transcoder.Transcode(ctx, t.Command, job.filePath, job.bitRate, job.offset)
- if err != nil {
- log.Error(ctx, "Error starting transcoder", "id", job.mf.ID, err)
- return nil, os.ErrInvalid
- }
- return out, nil
- })
-}
diff --git a/core/media_streamer_Internal_test.go b/core/media_streamer_Internal_test.go
deleted file mode 100644
index 44fbf701c..000000000
--- a/core/media_streamer_Internal_test.go
+++ /dev/null
@@ -1,162 +0,0 @@
-package core
-
-import (
- "context"
-
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/model/request"
- "github.com/navidrome/navidrome/tests"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("MediaStreamer", func() {
- var ds model.DataStore
- ctx := log.NewContext(context.Background())
-
- BeforeEach(func() {
- ds = &tests.MockDataStore{MockedTranscoding: &tests.MockTranscodingRepo{}}
- })
-
- Context("selectTranscodingOptions", func() {
- mf := &model.MediaFile{}
- Context("player is not configured", func() {
- It("returns raw if raw is requested", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, _ := selectTranscodingOptions(ctx, ds, mf, "raw", 0)
- Expect(format).To(Equal("raw"))
- })
- It("returns raw if a transcoder does not exists", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, _ := selectTranscodingOptions(ctx, ds, mf, "m4a", 0)
- Expect(format).To(Equal("raw"))
- })
- It("returns the requested format if a transcoder exists", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "mp3", 0)
- Expect(format).To(Equal("mp3"))
- Expect(bitRate).To(Equal(160)) // Default Bit Rate
- })
- It("returns raw if requested format is the same as the original and it is not necessary to downsample", func() {
- mf.Suffix = "mp3"
- mf.BitRate = 112
- format, _ := selectTranscodingOptions(ctx, ds, mf, "mp3", 128)
- Expect(format).To(Equal("raw"))
- })
- It("returns the requested format if requested BitRate is lower than original", func() {
- mf.Suffix = "mp3"
- mf.BitRate = 320
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "mp3", 192)
- Expect(format).To(Equal("mp3"))
- Expect(bitRate).To(Equal(192))
- })
- It("returns raw if requested format is the same as the original, but requested BitRate is 0", func() {
- mf.Suffix = "mp3"
- mf.BitRate = 320
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "mp3", 0)
- Expect(format).To(Equal("raw"))
- Expect(bitRate).To(Equal(320))
- })
- Context("Downsampling", func() {
- BeforeEach(func() {
- conf.Server.DefaultDownsamplingFormat = "opus"
- mf.Suffix = "FLAC"
- mf.BitRate = 960
- })
- It("returns the DefaultDownsamplingFormat if a maxBitrate is requested but not the format", func() {
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "", 128)
- Expect(format).To(Equal("opus"))
- Expect(bitRate).To(Equal(128))
- })
- It("returns raw if maxBitrate is equal or greater than original", func() {
- // This happens with DSub (and maybe other clients?). See https://github.com/navidrome/navidrome/issues/2066
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "", 960)
- Expect(format).To(Equal("raw"))
- Expect(bitRate).To(Equal(0))
- })
- })
- })
-
- Context("player has format configured", func() {
- BeforeEach(func() {
- t := model.Transcoding{ID: "oga1", TargetFormat: "oga", DefaultBitRate: 96}
- ctx = request.WithTranscoding(ctx, t)
- })
- It("returns raw if raw is requested", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, _ := selectTranscodingOptions(ctx, ds, mf, "raw", 0)
- Expect(format).To(Equal("raw"))
- })
- It("returns configured format/bitrate as default", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "", 0)
- Expect(format).To(Equal("oga"))
- Expect(bitRate).To(Equal(96))
- })
- It("returns requested format", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "mp3", 0)
- Expect(format).To(Equal("mp3"))
- Expect(bitRate).To(Equal(160)) // Default Bit Rate
- })
- It("returns requested bitrate", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "", 80)
- Expect(format).To(Equal("oga"))
- Expect(bitRate).To(Equal(80))
- })
- It("returns raw if selected bitrate and format is the same as original", func() {
- mf.Suffix = "mp3"
- mf.BitRate = 192
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "mp3", 192)
- Expect(format).To(Equal("raw"))
- Expect(bitRate).To(Equal(0))
- })
- })
-
- Context("player has maxBitRate configured", func() {
- BeforeEach(func() {
- t := model.Transcoding{ID: "oga1", TargetFormat: "oga", DefaultBitRate: 96}
- p := model.Player{ID: "player1", TranscodingId: t.ID, MaxBitRate: 192}
- ctx = request.WithTranscoding(ctx, t)
- ctx = request.WithPlayer(ctx, p)
- })
- It("returns raw if raw is requested", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, _ := selectTranscodingOptions(ctx, ds, mf, "raw", 0)
- Expect(format).To(Equal("raw"))
- })
- It("returns configured format/bitrate as default", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "", 0)
- Expect(format).To(Equal("oga"))
- Expect(bitRate).To(Equal(192))
- })
- It("returns requested format", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "mp3", 0)
- Expect(format).To(Equal("mp3"))
- Expect(bitRate).To(Equal(160)) // Default Bit Rate
- })
- It("returns requested bitrate", func() {
- mf.Suffix = "flac"
- mf.BitRate = 1000
- format, bitRate := selectTranscodingOptions(ctx, ds, mf, "", 160)
- Expect(format).To(Equal("oga"))
- Expect(bitRate).To(Equal(160))
- })
- })
- })
-})
diff --git a/core/metrics/insights.go b/core/metrics/insights.go
index f4f8738e7..5f3f491ea 100644
--- a/core/metrics/insights.go
+++ b/core/metrics/insights.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"math"
"net/http"
+ "os"
"path/filepath"
"runtime"
"runtime/debug"
@@ -21,7 +22,9 @@ import (
"github.com/navidrome/navidrome/core/metrics/insights"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/plugins/schema"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/plugins"
+ "github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/utils/singleton"
)
@@ -35,18 +38,12 @@ var (
)
type insightsCollector struct {
- ds model.DataStore
- pluginLoader PluginLoader
- lastRun atomic.Int64
- lastStatus atomic.Bool
+ ds model.DataStore
+ lastRun atomic.Int64
+ lastStatus atomic.Bool
}
-// PluginLoader defines an interface for loading plugins
-type PluginLoader interface {
- PluginList() map[string]schema.PluginManifest
-}
-
-func GetInstance(ds model.DataStore, pluginLoader PluginLoader) Insights {
+func GetInstance(ds model.DataStore) Insights {
return singleton.GetInstance(func() *insightsCollector {
id, err := ds.Property(context.TODO()).Get(consts.InsightsIDKey)
if err != nil {
@@ -58,14 +55,21 @@ func GetInstance(ds model.DataStore, pluginLoader PluginLoader) Insights {
}
}
insightsID = id
- return &insightsCollector{ds: ds, pluginLoader: pluginLoader}
+ return &insightsCollector{ds: ds}
})
}
func (c *insightsCollector) Run(ctx context.Context) {
- ctx = auth.WithAdminUser(ctx, c.ds)
for {
- c.sendInsights(ctx)
+ // Refresh admin context on each iteration to handle cases where
+ // admin user wasn't available on previous runs
+ insightsCtx := auth.WithAdminUser(ctx, c.ds)
+ u, _ := request.UserFrom(insightsCtx)
+ if !u.IsAdmin {
+ log.Trace(insightsCtx, "No admin user available, skipping insights collection")
+ } else {
+ c.sendInsights(insightsCtx)
+ }
select {
case <-time.After(consts.InsightsUpdateInterval):
continue
@@ -104,7 +108,7 @@ func (c *insightsCollector) sendInsights(ctx context.Context) {
return
}
req.Header.Set("Content-Type", "application/json")
- resp, err := hc.Do(req)
+ resp, err := hc.Do(req) //nolint:gosec
if err != nil {
log.Trace(ctx, "Could not send Insights data", err)
return
@@ -160,6 +164,13 @@ var staticData = sync.OnceValue(func() insights.Data {
data.Build.Settings, data.Build.GoVersion = buildInfo()
data.OS.Containerized = consts.InContainer
+ // Install info
+ packageFilename := filepath.Join(conf.Server.DataFolder, ".package")
+ packageFileData, err := os.ReadFile(packageFilename)
+ if err == nil {
+ data.OS.Package = string(packageFileData)
+ }
+
// OS info
data.OS.Type = runtime.GOOS
data.OS.Arch = runtime.GOARCH
@@ -188,7 +199,6 @@ var staticData = sync.OnceValue(func() insights.Data {
data.Config.EnableSharing = conf.Server.EnableSharing
data.Config.EnableStarRating = conf.Server.EnableStarRating
data.Config.EnableLastFM = conf.Server.LastFM.Enabled && conf.Server.LastFM.ApiKey != "" && conf.Server.LastFM.Secret != ""
- data.Config.EnableSpotify = conf.Server.Spotify.ID != "" && conf.Server.Spotify.Secret != ""
data.Config.EnableListenBrainz = conf.Server.ListenBrainz.Enabled
data.Config.EnableDeezer = conf.Server.Deezer.Enabled
data.Config.EnableMediaFileCoverArt = conf.Server.EnableMediaFileCoverArt
@@ -197,18 +207,20 @@ var staticData = sync.OnceValue(func() insights.Data {
data.Config.TranscodingCacheSize = conf.Server.TranscodingCacheSize
data.Config.ImageCacheSize = conf.Server.ImageCacheSize
data.Config.SessionTimeout = uint64(math.Trunc(conf.Server.SessionTimeout.Seconds()))
- data.Config.SearchFullString = conf.Server.SearchFullString
+ data.Config.SearchFullString = conf.Server.Search.FullString
+ data.Config.SearchBackend = conf.Server.Search.Backend
data.Config.RecentlyAddedByModTime = conf.Server.RecentlyAddedByModTime
data.Config.PreferSortTags = conf.Server.PreferSortTags
data.Config.BackupSchedule = conf.Server.Backup.Schedule
data.Config.BackupCount = conf.Server.Backup.Count
data.Config.DevActivityPanel = conf.Server.DevActivityPanel
data.Config.ScannerEnabled = conf.Server.Scanner.Enabled
+ data.Config.ScannerExtractor = conf.Server.Scanner.Extractor
data.Config.ScanSchedule = conf.Server.Scanner.Schedule
data.Config.ScanWatcherWait = uint64(math.Trunc(conf.Server.Scanner.WatcherWait.Seconds()))
data.Config.ScanOnStartup = conf.Server.Scanner.ScanOnStartup
- data.Config.ReverseProxyConfigured = conf.Server.ReverseProxyWhitelist != ""
- data.Config.HasCustomPID = conf.Server.PID.Track != "" || conf.Server.PID.Album != ""
+ data.Config.ReverseProxyConfigured = conf.Server.ExtAuth.TrustedSources != ""
+ data.Config.HasCustomPID = conf.Server.PID.Track != consts.DefaultTrackPID || conf.Server.PID.Album != consts.DefaultAlbumPID
data.Config.HasCustomTags = len(conf.Server.Tags) > 0
return data
@@ -254,6 +266,10 @@ func (c *insightsCollector) collect(ctx context.Context) []byte {
if err != nil {
log.Trace(ctx, "Error reading active users count", err)
}
+ data.Library.FileSuffixes, err = c.ds.MediaFile(ctx).CountBySuffix()
+ if err != nil {
+ log.Trace(ctx, "Error reading file suffixes count", err)
+ }
// Check for smart playlists
data.Config.HasSmartPlaylists, err = c.hasSmartPlaylists(ctx)
@@ -303,12 +319,16 @@ func (c *insightsCollector) hasSmartPlaylists(ctx context.Context) (bool, error)
// collectPlugins collects information about installed plugins
func (c *insightsCollector) collectPlugins(_ context.Context) map[string]insights.PluginInfo {
- plugins := make(map[string]insights.PluginInfo)
- for id, manifest := range c.pluginLoader.PluginList() {
- plugins[id] = insights.PluginInfo{
- Name: manifest.Name,
- Version: manifest.Version,
+ // TODO Fix import/inject cycles
+ manager := plugins.GetManager(c.ds, events.GetBroker(), nil)
+ info := manager.GetPluginInfo()
+
+ result := make(map[string]insights.PluginInfo, len(info))
+ for name, p := range info {
+ result[name] = insights.PluginInfo{
+ Name: p.Name,
+ Version: p.Version,
}
}
- return plugins
+ return result
}
diff --git a/core/metrics/insights/data.go b/core/metrics/insights/data.go
index 105a6218e..27186e020 100644
--- a/core/metrics/insights/data.go
+++ b/core/metrics/insights/data.go
@@ -16,6 +16,7 @@ type Data struct {
Containerized bool `json:"containerized"`
Arch string `json:"arch"`
NumCPU int `json:"numCPU"`
+ Package string `json:"package,omitempty"`
} `json:"os"`
Mem struct {
Alloc uint64 `json:"alloc"`
@@ -39,12 +40,14 @@ type Data struct {
Libraries int64 `json:"libraries"`
ActiveUsers int64 `json:"activeUsers"`
ActivePlayers map[string]int64 `json:"activePlayers,omitempty"`
+ FileSuffixes map[string]int64 `json:"fileSuffixes,omitempty"`
} `json:"library"`
Config struct {
LogLevel string `json:"logLevel,omitempty"`
LogFileConfigured bool `json:"logFileConfigured,omitempty"`
TLSConfigured bool `json:"tlsConfigured,omitempty"`
ScannerEnabled bool `json:"scannerEnabled,omitempty"`
+ ScannerExtractor string `json:"scannerExtractor,omitempty"`
ScanSchedule string `json:"scanSchedule,omitempty"`
ScanWatcherWait uint64 `json:"scanWatcherWait,omitempty"`
ScanOnStartup bool `json:"scanOnStartup,omitempty"`
@@ -58,13 +61,13 @@ type Data struct {
EnableListenBrainz bool `json:"enableListenBrainz,omitempty"`
EnableDeezer bool `json:"enableDeezer,omitempty"`
EnableMediaFileCoverArt bool `json:"enableMediaFileCoverArt,omitempty"`
- EnableSpotify bool `json:"enableSpotify,omitempty"`
EnableJukebox bool `json:"enableJukebox,omitempty"`
EnablePrometheus bool `json:"enablePrometheus,omitempty"`
EnableCoverAnimation bool `json:"enableCoverAnimation,omitempty"`
EnableNowPlaying bool `json:"enableNowPlaying,omitempty"`
SessionTimeout uint64 `json:"sessionTimeout,omitempty"`
SearchFullString bool `json:"searchFullString,omitempty"`
+ SearchBackend string `json:"searchBackend,omitempty"`
RecentlyAddedByModTime bool `json:"recentlyAddedByModTime,omitempty"`
PreferSortTags bool `json:"preferSortTags,omitempty"`
BackupSchedule string `json:"backupSchedule,omitempty"`
diff --git a/core/metrics/insights_linux.go b/core/metrics/insights_linux.go
index dbf3c277c..f37c945c1 100644
--- a/core/metrics/insights_linux.go
+++ b/core/metrics/insights_linux.go
@@ -42,6 +42,7 @@ type MountInfo struct {
var fsTypeMap = map[int64]string{
0x5346414f: "afs",
+ 0x187: "autofs",
0x61756673: "aufs",
0x9123683E: "btrfs",
0xc36400: "ceph",
@@ -55,9 +56,11 @@ var fsTypeMap = map[int64]string{
0x6a656a63: "fakeowner", // FS inside a container
0x65735546: "fuse",
0x4244: "hfs",
+ 0x482b: "hfs+",
0x9660: "iso9660",
0x3153464a: "jfs",
0x00006969: "nfs",
+ 0x5346544e: "ntfs", // NTFS_SB_MAGIC
0x7366746e: "ntfs",
0x794c7630: "overlayfs",
0x9fa0: "proc",
@@ -69,8 +72,16 @@ var fsTypeMap = map[int64]string{
0x01021997: "v9fs",
0x786f4256: "vboxsf",
0x4d44: "vfat",
+ 0xca451a4e: "virtiofs",
0x58465342: "xfs",
0x2FC12FC1: "zfs",
+ 0x7c7c6673: "prlfs", // Parallels Shared Folders
+
+ // Signed/unsigned conversion issues (negative hex values converted to uint32)
+ -0x6edc97c2: "btrfs", // 0x9123683e
+ -0x1acb2be: "smb2", // 0xfe534d42
+ -0xacb2be: "cifs", // 0xff534d42
+ -0xd0adff0: "f2fs", // 0xf2f52010
}
func getFilesystemType(path string) (string, error) {
diff --git a/core/playback/mpv/mpv.go b/core/playback/mpv/mpv.go
index f356a1410..035e18dd5 100644
--- a/core/playback/mpv/mpv.go
+++ b/core/playback/mpv/mpv.go
@@ -10,9 +10,9 @@ import (
"strings"
"sync"
- "github.com/kballard/go-shellquote"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/utils/shellquote"
)
func start(ctx context.Context, args []string) (Executor, error) {
diff --git a/core/playback/mpv/mpv_test.go b/core/playback/mpv/mpv_test.go
index 20c02501b..b1f2435a3 100644
--- a/core/playback/mpv/mpv_test.go
+++ b/core/playback/mpv/mpv_test.go
@@ -188,7 +188,7 @@ var _ = Describe("MPV", func() {
It("returns empty slice for empty template", func() {
args := createMPVCommand("auto", "/music/test.mp3", "/tmp/socket")
- Expect(args).To(Equal([]string{}))
+ Expect(args).To(BeEmpty())
})
})
})
diff --git a/core/playback/queue.go b/core/playback/queue.go
index 0c230a61f..d15eaad96 100644
--- a/core/playback/queue.go
+++ b/core/playback/queue.go
@@ -3,6 +3,7 @@ package playback
import (
"fmt"
"math/rand"
+ "strings"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
@@ -21,11 +22,11 @@ func NewQueue() *Queue {
}
func (pd *Queue) String() string {
- filenames := ""
+ var filenames strings.Builder
for idx, item := range pd.Items {
- filenames += fmt.Sprint(idx) + ":" + item.Path + " "
+ filenames.WriteString(fmt.Sprint(idx) + ":" + item.Path + " ")
}
- return fmt.Sprintf("#Items: %d, idx: %d, files: %s", len(pd.Items), pd.Index, filenames)
+ return fmt.Sprintf("#Items: %d, idx: %d, files: %s", len(pd.Items), pd.Index, filenames.String())
}
// returns the current mediafile or nil
diff --git a/core/playlists.go b/core/playlists.go
deleted file mode 100644
index 2eebc94e7..000000000
--- a/core/playlists.go
+++ /dev/null
@@ -1,390 +0,0 @@
-package core
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/url"
- "os"
- "path/filepath"
- "regexp"
- "strings"
- "time"
-
- "github.com/RaveNoX/go-jsoncommentstrip"
- "github.com/bmatcuk/doublestar/v4"
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/model/criteria"
- "github.com/navidrome/navidrome/model/request"
- "github.com/navidrome/navidrome/utils/slice"
- "golang.org/x/text/unicode/norm"
-)
-
-type Playlists interface {
- ImportFile(ctx context.Context, folder *model.Folder, filename string) (*model.Playlist, error)
- Update(ctx context.Context, playlistID string, name *string, comment *string, public *bool, idsToAdd []string, idxToRemove []int) error
- ImportM3U(ctx context.Context, reader io.Reader) (*model.Playlist, error)
-}
-
-type playlists struct {
- ds model.DataStore
-}
-
-func NewPlaylists(ds model.DataStore) Playlists {
- return &playlists{ds: ds}
-}
-
-func InPlaylistsPath(folder model.Folder) bool {
- if conf.Server.PlaylistsPath == "" {
- return true
- }
- rel, _ := filepath.Rel(folder.LibraryPath, folder.AbsolutePath())
- for _, path := range strings.Split(conf.Server.PlaylistsPath, string(filepath.ListSeparator)) {
- if match, _ := doublestar.Match(path, rel); match {
- return true
- }
- }
- return false
-}
-
-func (s *playlists) ImportFile(ctx context.Context, folder *model.Folder, filename string) (*model.Playlist, error) {
- pls, err := s.parsePlaylist(ctx, filename, folder)
- if err != nil {
- log.Error(ctx, "Error parsing playlist", "path", filepath.Join(folder.AbsolutePath(), filename), err)
- return nil, err
- }
- log.Debug("Found playlist", "name", pls.Name, "lastUpdated", pls.UpdatedAt, "path", pls.Path, "numTracks", len(pls.Tracks))
- err = s.updatePlaylist(ctx, pls)
- if err != nil {
- log.Error(ctx, "Error updating playlist", "path", filepath.Join(folder.AbsolutePath(), filename), err)
- }
- return pls, err
-}
-
-func (s *playlists) ImportM3U(ctx context.Context, reader io.Reader) (*model.Playlist, error) {
- owner, _ := request.UserFrom(ctx)
- pls := &model.Playlist{
- OwnerID: owner.ID,
- Public: false,
- Sync: false,
- }
- err := s.parseM3U(ctx, pls, nil, reader)
- if err != nil {
- log.Error(ctx, "Error parsing playlist", err)
- return nil, err
- }
- err = s.ds.Playlist(ctx).Put(pls)
- if err != nil {
- log.Error(ctx, "Error saving playlist", err)
- return nil, err
- }
- return pls, nil
-}
-
-func (s *playlists) parsePlaylist(ctx context.Context, playlistFile string, folder *model.Folder) (*model.Playlist, error) {
- pls, err := s.newSyncedPlaylist(folder.AbsolutePath(), playlistFile)
- if err != nil {
- return nil, err
- }
-
- file, err := os.Open(pls.Path)
- if err != nil {
- return nil, err
- }
- defer file.Close()
-
- extension := strings.ToLower(filepath.Ext(playlistFile))
- switch extension {
- case ".nsp":
- err = s.parseNSP(ctx, pls, file)
- default:
- err = s.parseM3U(ctx, pls, folder, file)
- }
- return pls, err
-}
-
-func (s *playlists) newSyncedPlaylist(baseDir string, playlistFile string) (*model.Playlist, error) {
- playlistPath := filepath.Join(baseDir, playlistFile)
- info, err := os.Stat(playlistPath)
- if err != nil {
- return nil, err
- }
-
- var extension = filepath.Ext(playlistFile)
- var name = playlistFile[0 : len(playlistFile)-len(extension)]
-
- pls := &model.Playlist{
- Name: name,
- Comment: fmt.Sprintf("Auto-imported from '%s'", playlistFile),
- Public: false,
- Path: playlistPath,
- Sync: true,
- UpdatedAt: info.ModTime(),
- }
- return pls, nil
-}
-
-func getPositionFromOffset(data []byte, offset int64) (line, column int) {
- line = 1
- for _, b := range data[:offset] {
- if b == '\n' {
- line++
- column = 1
- } else {
- column++
- }
- }
- return
-}
-
-func (s *playlists) parseNSP(_ context.Context, pls *model.Playlist, reader io.Reader) error {
- nsp := &nspFile{}
- reader = io.LimitReader(reader, 100*1024) // Limit to 100KB
- reader = jsoncommentstrip.NewReader(reader)
- input, err := io.ReadAll(reader)
- if err != nil {
- return fmt.Errorf("reading SmartPlaylist: %w", err)
- }
- err = json.Unmarshal(input, nsp)
- if err != nil {
- var syntaxErr *json.SyntaxError
- if errors.As(err, &syntaxErr) {
- line, col := getPositionFromOffset(input, syntaxErr.Offset)
- return fmt.Errorf("JSON syntax error in SmartPlaylist at line %d, column %d: %w", line, col, err)
- }
- return fmt.Errorf("JSON parsing error in SmartPlaylist: %w", err)
- }
- pls.Rules = &nsp.Criteria
- if nsp.Name != "" {
- pls.Name = nsp.Name
- }
- if nsp.Comment != "" {
- pls.Comment = nsp.Comment
- }
- return nil
-}
-
-func (s *playlists) parseM3U(ctx context.Context, pls *model.Playlist, folder *model.Folder, reader io.Reader) error {
- mediaFileRepository := s.ds.MediaFile(ctx)
- var mfs model.MediaFiles
- for lines := range slice.CollectChunks(slice.LinesFrom(reader), 400) {
- filteredLines := make([]string, 0, len(lines))
- for _, line := range lines {
- line := strings.TrimSpace(line)
- if strings.HasPrefix(line, "#PLAYLIST:") {
- pls.Name = line[len("#PLAYLIST:"):]
- continue
- }
- // Skip empty lines and extended info
- if line == "" || strings.HasPrefix(line, "#") {
- continue
- }
- if strings.HasPrefix(line, "file://") {
- line = strings.TrimPrefix(line, "file://")
- line, _ = url.QueryUnescape(line)
- }
- if !model.IsAudioFile(line) {
- continue
- }
- filteredLines = append(filteredLines, line)
- }
- paths, err := s.normalizePaths(ctx, pls, folder, filteredLines)
- if err != nil {
- log.Warn(ctx, "Error normalizing paths in playlist", "playlist", pls.Name, err)
- continue
- }
- found, err := mediaFileRepository.FindByPaths(paths)
- if err != nil {
- log.Warn(ctx, "Error reading files from DB", "playlist", pls.Name, err)
- continue
- }
- existing := make(map[string]int, len(found))
- for idx := range found {
- existing[normalizePathForComparison(found[idx].Path)] = idx
- }
- for _, path := range paths {
- idx, ok := existing[normalizePathForComparison(path)]
- if ok {
- mfs = append(mfs, found[idx])
- } else {
- log.Warn(ctx, "Path in playlist not found", "playlist", pls.Name, "path", path)
- }
- }
- }
- if pls.Name == "" {
- pls.Name = time.Now().Format(time.RFC3339)
- }
- pls.Tracks = nil
- pls.AddMediaFiles(mfs)
-
- return nil
-}
-
-// normalizePathForComparison normalizes a file path to NFC form and converts to lowercase
-// for consistent comparison. This fixes Unicode normalization issues on macOS where
-// Apple Music creates playlists with NFC-encoded paths but the filesystem uses NFD.
-func normalizePathForComparison(path string) string {
- return strings.ToLower(norm.NFC.String(path))
-}
-
-// TODO This won't work for multiple libraries
-func (s *playlists) normalizePaths(ctx context.Context, pls *model.Playlist, folder *model.Folder, lines []string) ([]string, error) {
- libRegex, err := s.compileLibraryPaths(ctx)
- if err != nil {
- return nil, err
- }
-
- res := make([]string, 0, len(lines))
- for idx, line := range lines {
- var libPath string
- var filePath string
-
- if folder != nil && !filepath.IsAbs(line) {
- libPath = folder.LibraryPath
- filePath = filepath.Join(folder.AbsolutePath(), line)
- } else {
- cleanLine := filepath.Clean(line)
- if libPath = libRegex.FindString(cleanLine); libPath != "" {
- filePath = cleanLine
- }
- }
-
- if libPath != "" {
- if rel, err := filepath.Rel(libPath, filePath); err == nil {
- res = append(res, rel)
- } else {
- log.Debug(ctx, "Error getting relative path", "playlist", pls.Name, "path", line, "libPath", libPath,
- "filePath", filePath, err)
- }
- } else {
- log.Warn(ctx, "Path in playlist not found in any library", "path", line, "line", idx)
- }
- }
- return slice.Map(res, filepath.ToSlash), nil
-}
-
-func (s *playlists) compileLibraryPaths(ctx context.Context) (*regexp.Regexp, error) {
- libs, err := s.ds.Library(ctx).GetAll()
- if err != nil {
- return nil, err
- }
-
- // Create regex patterns for each library path
- patterns := make([]string, len(libs))
- for i, lib := range libs {
- cleanPath := filepath.Clean(lib.Path)
- escapedPath := regexp.QuoteMeta(cleanPath)
- patterns[i] = fmt.Sprintf("^%s(?:/|$)", escapedPath)
- }
- // Combine all patterns into a single regex
- combinedPattern := strings.Join(patterns, "|")
- re, err := regexp.Compile(combinedPattern)
- if err != nil {
- return nil, fmt.Errorf("compiling library paths `%s`: %w", combinedPattern, err)
- }
- return re, nil
-}
-
-func (s *playlists) updatePlaylist(ctx context.Context, newPls *model.Playlist) error {
- owner, _ := request.UserFrom(ctx)
-
- pls, err := s.ds.Playlist(ctx).FindByPath(newPls.Path)
- if err != nil && !errors.Is(err, model.ErrNotFound) {
- return err
- }
- if err == nil && !pls.Sync {
- log.Debug(ctx, "Playlist already imported and not synced", "playlist", pls.Name, "path", pls.Path)
- return nil
- }
-
- if err == nil {
- log.Info(ctx, "Updating synced playlist", "playlist", pls.Name, "path", newPls.Path)
- newPls.ID = pls.ID
- newPls.Name = pls.Name
- newPls.Comment = pls.Comment
- newPls.OwnerID = pls.OwnerID
- newPls.Public = pls.Public
- newPls.EvaluatedAt = &time.Time{}
- } else {
- log.Info(ctx, "Adding synced playlist", "playlist", newPls.Name, "path", newPls.Path, "owner", owner.UserName)
- newPls.OwnerID = owner.ID
- newPls.Public = conf.Server.DefaultPlaylistPublicVisibility
- }
- return s.ds.Playlist(ctx).Put(newPls)
-}
-
-func (s *playlists) Update(ctx context.Context, playlistID string,
- name *string, comment *string, public *bool,
- idsToAdd []string, idxToRemove []int) error {
- needsInfoUpdate := name != nil || comment != nil || public != nil
- needsTrackRefresh := len(idxToRemove) > 0
-
- return s.ds.WithTxImmediate(func(tx model.DataStore) error {
- var pls *model.Playlist
- var err error
- repo := tx.Playlist(ctx)
- tracks := repo.Tracks(playlistID, true)
- if tracks == nil {
- return fmt.Errorf("%w: playlist '%s'", model.ErrNotFound, playlistID)
- }
- if needsTrackRefresh {
- pls, err = repo.GetWithTracks(playlistID, true, false)
- pls.RemoveTracks(idxToRemove)
- pls.AddMediaFilesByID(idsToAdd)
- } else {
- if len(idsToAdd) > 0 {
- _, err = tracks.Add(idsToAdd)
- if err != nil {
- return err
- }
- }
- if needsInfoUpdate {
- pls, err = repo.Get(playlistID)
- }
- }
- if err != nil {
- return err
- }
- if !needsTrackRefresh && !needsInfoUpdate {
- return nil
- }
-
- if name != nil {
- pls.Name = *name
- }
- if comment != nil {
- pls.Comment = *comment
- }
- if public != nil {
- pls.Public = *public
- }
- // Special case: The playlist is now empty
- if len(idxToRemove) > 0 && len(pls.Tracks) == 0 {
- if err = tracks.DeleteAll(); err != nil {
- return err
- }
- }
- return repo.Put(pls)
- })
-}
-
-type nspFile struct {
- criteria.Criteria
- Name string `json:"name"`
- Comment string `json:"comment"`
-}
-
-func (i *nspFile) UnmarshalJSON(data []byte) error {
- m := map[string]interface{}{}
- err := json.Unmarshal(data, &m)
- if err != nil {
- return err
- }
- i.Name, _ = m["name"].(string)
- i.Comment, _ = m["comment"].(string)
- return json.Unmarshal(data, &i.Criteria)
-}
diff --git a/core/playlists/import.go b/core/playlists/import.go
new file mode 100644
index 000000000..4462554c7
--- /dev/null
+++ b/core/playlists/import.go
@@ -0,0 +1,120 @@
+package playlists
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/utils/ioutils"
+ "golang.org/x/text/unicode/norm"
+)
+
+func (s *playlists) ImportFile(ctx context.Context, folder *model.Folder, filename string) (*model.Playlist, error) {
+ pls, err := s.parsePlaylist(ctx, filename, folder)
+ if err != nil {
+ log.Error(ctx, "Error parsing playlist", "path", filepath.Join(folder.AbsolutePath(), filename), err)
+ return nil, err
+ }
+ log.Debug(ctx, "Found playlist", "name", pls.Name, "lastUpdated", pls.UpdatedAt, "path", pls.Path, "numTracks", len(pls.Tracks))
+ err = s.updatePlaylist(ctx, pls)
+ if err != nil {
+ log.Error(ctx, "Error updating playlist", "path", filepath.Join(folder.AbsolutePath(), filename), err)
+ }
+ return pls, err
+}
+
+func (s *playlists) ImportM3U(ctx context.Context, reader io.Reader) (*model.Playlist, error) {
+ owner, _ := request.UserFrom(ctx)
+ pls := &model.Playlist{
+ OwnerID: owner.ID,
+ Public: false,
+ Sync: false,
+ }
+ err := s.parseM3U(ctx, pls, nil, reader)
+ if err != nil {
+ log.Error(ctx, "Error parsing playlist", err)
+ return nil, err
+ }
+ err = s.ds.Playlist(ctx).Put(pls)
+ if err != nil {
+ log.Error(ctx, "Error saving playlist", err)
+ return nil, err
+ }
+ return pls, nil
+}
+
+func (s *playlists) parsePlaylist(ctx context.Context, playlistFile string, folder *model.Folder) (*model.Playlist, error) {
+ pls, err := s.newSyncedPlaylist(folder.AbsolutePath(), playlistFile)
+ if err != nil {
+ return nil, err
+ }
+
+ file, err := os.Open(pls.Path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ reader := ioutils.UTF8Reader(file)
+ extension := strings.ToLower(filepath.Ext(playlistFile))
+ switch extension {
+ case ".nsp":
+ err = s.parseNSP(ctx, pls, reader)
+ default:
+ err = s.parseM3U(ctx, pls, folder, reader)
+ }
+ return pls, err
+}
+
+func (s *playlists) updatePlaylist(ctx context.Context, newPls *model.Playlist) error {
+ owner, _ := request.UserFrom(ctx)
+
+ // Try to find existing playlist by path. Since filesystem normalization differs across
+ // platforms (macOS uses NFD, Linux/Windows use NFC), we try both forms to match
+ // playlists that may have been imported on a different platform.
+ pls, err := s.ds.Playlist(ctx).FindByPath(newPls.Path)
+ if errors.Is(err, model.ErrNotFound) {
+ // Try alternate normalization form
+ altPath := norm.NFD.String(newPls.Path)
+ if altPath == newPls.Path {
+ altPath = norm.NFC.String(newPls.Path)
+ }
+ if altPath != newPls.Path {
+ pls, err = s.ds.Playlist(ctx).FindByPath(altPath)
+ }
+ }
+ if err != nil && !errors.Is(err, model.ErrNotFound) {
+ return err
+ }
+ if err == nil && !pls.Sync {
+ log.Debug(ctx, "Playlist already imported and not synced", "playlist", pls.Name, "path", pls.Path)
+ return nil
+ }
+
+ if err == nil {
+ log.Info(ctx, "Updating synced playlist", "playlist", pls.Name, "path", newPls.Path)
+ newPls.ID = pls.ID
+ newPls.Name = pls.Name
+ newPls.Comment = pls.Comment
+ newPls.OwnerID = pls.OwnerID
+ newPls.Public = pls.Public
+ newPls.UploadedImage = pls.UploadedImage // Preserve manual upload
+ newPls.EvaluatedAt = &time.Time{}
+ } else {
+ log.Info(ctx, "Adding synced playlist", "playlist", newPls.Name, "path", newPls.Path, "owner", owner.UserName)
+ newPls.OwnerID = owner.ID
+ // For NSP files, Public may already be set from the file; for M3U, use server default
+ if !newPls.IsSmartPlaylist() {
+ newPls.Public = conf.Server.DefaultPlaylistPublicVisibility
+ }
+ }
+ return s.ds.Playlist(ctx).Put(newPls)
+}
diff --git a/core/playlists/import_test.go b/core/playlists/import_test.go
new file mode 100644
index 000000000..a6320bc7e
--- /dev/null
+++ b/core/playlists/import_test.go
@@ -0,0 +1,923 @@
+package playlists_test
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/core/playlists"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/criteria"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "golang.org/x/text/unicode/norm"
+)
+
+var _ = Describe("Playlists - Import", func() {
+ var ds *tests.MockDataStore
+ var ps playlists.Playlists
+ var mockPlsRepo *tests.MockPlaylistRepo
+ var mockLibRepo *tests.MockLibraryRepo
+ ctx := context.Background()
+
+ BeforeEach(func() {
+ mockPlsRepo = tests.CreateMockPlaylistRepo()
+ mockLibRepo = &tests.MockLibraryRepo{}
+ ds = &tests.MockDataStore{
+ MockedPlaylist: mockPlsRepo,
+ MockedLibrary: mockLibRepo,
+ }
+ ctx = request.WithUser(ctx, model.User{ID: "123"})
+ })
+
+ Describe("ImportFile", func() {
+ var folder *model.Folder
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ ds.MockedMediaFile = &mockedMediaFileRepo{}
+ libPath, _ := os.Getwd()
+ // Set up library with the actual library path that matches the folder
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: libPath}})
+ folder = &model.Folder{
+ ID: "1",
+ LibraryID: 1,
+ LibraryPath: libPath,
+ Path: "tests/fixtures",
+ Name: "playlists",
+ }
+ })
+
+ Describe("M3U", func() {
+ It("parses well-formed playlists", func() {
+ pls, err := ps.ImportFile(ctx, folder, "pls1.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.OwnerID).To(Equal("123"))
+ Expect(pls.Tracks).To(HaveLen(2))
+ Expect(pls.Tracks[0].Path).To(Equal("tests/fixtures/playlists/test.mp3"))
+ Expect(pls.Tracks[1].Path).To(Equal("tests/fixtures/playlists/test.ogg"))
+ Expect(mockPlsRepo.Last).To(Equal(pls))
+ })
+
+ It("parses playlists using LF ending", func() {
+ pls, err := ps.ImportFile(ctx, folder, "lf-ended.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(2))
+ })
+
+ It("parses playlists using CR ending (old Mac format)", func() {
+ pls, err := ps.ImportFile(ctx, folder, "cr-ended.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(2))
+ })
+
+ It("parses playlists with UTF-8 BOM marker", func() {
+ pls, err := ps.ImportFile(ctx, folder, "bom-test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.OwnerID).To(Equal("123"))
+ Expect(pls.Name).To(Equal("Test Playlist"))
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].Path).To(Equal("tests/fixtures/playlists/test.mp3"))
+ })
+
+ It("parses UTF-16 LE encoded playlists with BOM and converts to UTF-8", func() {
+ pls, err := ps.ImportFile(ctx, folder, "bom-test-utf16.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.OwnerID).To(Equal("123"))
+ Expect(pls.Name).To(Equal("UTF-16 Test Playlist"))
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].Path).To(Equal("tests/fixtures/playlists/test.mp3"))
+ })
+
+ It("parses #EXTALBUMARTURL with HTTP URL", func() {
+ conf.Server.EnableM3UExternalAlbumArt = true
+
+ pls, err := ps.ImportFile(ctx, folder, "pls-with-art-url.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(Equal("https://example.com/cover.jpg"))
+ Expect(pls.Tracks).To(HaveLen(2))
+ })
+
+ It("parses #EXTALBUMARTURL with absolute local path", func() {
+ tmpDir := GinkgoT().TempDir()
+ imgPath := filepath.Join(tmpDir, "cover.jpg")
+ Expect(os.WriteFile(imgPath, []byte("fake image"), 0600)).To(Succeed())
+
+ m3u := fmt.Sprintf("#EXTALBUMARTURL:%s\ntest.mp3\ntest.ogg\n", imgPath)
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3", "test.ogg"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(Equal(imgPath))
+ })
+
+ It("parses #EXTALBUMARTURL with relative local path", func() {
+ tmpDir := GinkgoT().TempDir()
+ Expect(os.WriteFile(filepath.Join(tmpDir, "cover.jpg"), []byte("fake image"), 0600)).To(Succeed())
+
+ m3u := "#EXTALBUMARTURL:cover.jpg\ntest.mp3\n"
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(Equal(filepath.Join(tmpDir, "cover.jpg")))
+ })
+
+ It("parses #EXTALBUMARTURL with file:// URL", func() {
+ tmpDir := GinkgoT().TempDir()
+ imgPath := filepath.Join(tmpDir, "my cover.jpg")
+ Expect(os.WriteFile(imgPath, []byte("fake image"), 0600)).To(Succeed())
+
+ m3u := fmt.Sprintf("#EXTALBUMARTURL:file://%s\ntest.mp3\n", strings.ReplaceAll(imgPath, " ", "%20"))
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(Equal(imgPath))
+ })
+
+ It("preserves + in file:// URLs (PathUnescape, not QueryUnescape)", func() {
+ tmpDir := GinkgoT().TempDir()
+ imgPath := filepath.Join(tmpDir, "A+B.jpg")
+ Expect(os.WriteFile(imgPath, []byte("fake image"), 0600)).To(Succeed())
+
+ m3u := fmt.Sprintf("#EXTALBUMARTURL:file://%s\ntest.mp3\n", imgPath)
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(Equal(imgPath))
+ })
+
+ It("rejects #EXTALBUMARTURL with absolute path outside library boundaries", func() {
+ tmpDir := GinkgoT().TempDir()
+
+ m3u := "#EXTALBUMARTURL:/etc/passwd\ntest.mp3\n"
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(BeEmpty())
+ })
+
+ It("rejects #EXTALBUMARTURL with file:// URL outside library boundaries", func() {
+ tmpDir := GinkgoT().TempDir()
+
+ m3u := "#EXTALBUMARTURL:file:///etc/passwd\ntest.mp3\n"
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(BeEmpty())
+ })
+
+ It("rejects #EXTALBUMARTURL with relative path escaping library", func() {
+ tmpDir := GinkgoT().TempDir()
+
+ m3u := "#EXTALBUMARTURL:../../etc/passwd\ntest.mp3\n"
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(BeEmpty())
+ })
+
+ It("ignores HTTP #EXTALBUMARTURL when EnableM3UExternalAlbumArt is false", func() {
+ conf.Server.EnableM3UExternalAlbumArt = false
+
+ tmpDir := GinkgoT().TempDir()
+ m3u := "#EXTALBUMARTURL:https://example.com/cover.jpg\ntest.mp3\n"
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(BeEmpty())
+ })
+
+ It("updates ExternalImageURL on re-scan even when UploadedImage is set", func() {
+ conf.Server.EnableM3UExternalAlbumArt = true
+
+ tmpDir := GinkgoT().TempDir()
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ m3u := "#EXTALBUMARTURL:https://example.com/new-cover.jpg\ntest.mp3\n"
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ existingPls := &model.Playlist{
+ ID: "existing-id",
+ Name: "Existing Playlist",
+ Path: plsFile,
+ Sync: true,
+ UploadedImage: "existing-id.jpg",
+ ExternalImageURL: "https://example.com/old-cover.jpg",
+ }
+ mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls}
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.UploadedImage).To(Equal("existing-id.jpg"))
+ Expect(pls.ExternalImageURL).To(Equal("https://example.com/new-cover.jpg"))
+ })
+
+ It("clears ExternalImageURL on re-scan when directive is removed", func() {
+ tmpDir := GinkgoT().TempDir()
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ m3u := "test.mp3\n"
+ plsFile := filepath.Join(tmpDir, "test.m3u")
+ Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed())
+
+ existingPls := &model.Playlist{
+ ID: "existing-id",
+ Name: "Existing Playlist",
+ Path: plsFile,
+ Sync: true,
+ ExternalImageURL: "https://example.com/old-cover.jpg",
+ }
+ mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls}
+
+ plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""}
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(BeEmpty())
+ })
+ })
+
+ Describe("NSP", func() {
+ It("parses well-formed playlists", func() {
+ pls, err := ps.ImportFile(ctx, folder, "recently_played.nsp")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockPlsRepo.Last).To(Equal(pls))
+ Expect(pls.OwnerID).To(Equal("123"))
+ Expect(pls.Name).To(Equal("Recently Played"))
+ Expect(pls.Comment).To(Equal("Recently played tracks"))
+ Expect(pls.Rules.Sort).To(Equal("lastPlayed"))
+ Expect(pls.Rules.Order).To(Equal("desc"))
+ Expect(pls.Rules.Limit).To(Equal(100))
+ Expect(pls.Rules.Expression).To(BeAssignableToTypeOf(criteria.All{}))
+ })
+ It("returns an error if the playlist is not well-formed", func() {
+ _, err := ps.ImportFile(ctx, folder, "invalid_json.nsp")
+ Expect(err.Error()).To(ContainSubstring("line 19, column 1: invalid character '\\n'"))
+ })
+ It("parses NSP with public: true and creates public playlist", func() {
+ pls, err := ps.ImportFile(ctx, folder, "public_playlist.nsp")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("Public Playlist"))
+ Expect(pls.Public).To(BeTrue())
+ })
+ It("parses NSP with public: false and creates private playlist", func() {
+ pls, err := ps.ImportFile(ctx, folder, "private_playlist.nsp")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("Private Playlist"))
+ Expect(pls.Public).To(BeFalse())
+ })
+ It("uses server default when public field is absent", func() {
+ conf.Server.DefaultPlaylistPublicVisibility = true
+
+ pls, err := ps.ImportFile(ctx, folder, "recently_played.nsp")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("Recently Played"))
+ Expect(pls.Public).To(BeTrue()) // Should be true since server default is true
+ })
+ })
+
+ DescribeTable("Playlist filename Unicode normalization (regression fix-playlist-filename-normalization)",
+ func(storedForm, filesystemForm string) {
+ // Use Polish characters that decompose: ó (U+00F3) -> o + combining acute (U+006F + U+0301)
+ plsNameNFC := "Piosenki_Polskie_zółć" // NFC form (composed)
+ plsNameNFD := norm.NFD.String(plsNameNFC)
+ Expect(plsNameNFD).ToNot(Equal(plsNameNFC)) // Verify they differ
+
+ nameByForm := map[string]string{"NFC": plsNameNFC, "NFD": plsNameNFD}
+ storedName := nameByForm[storedForm]
+ filesystemName := nameByForm[filesystemForm]
+
+ tmpDir := GinkgoT().TempDir()
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}})
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{}}
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ // Create the playlist file on disk with the filesystem's normalization form
+ plsFile := tmpDir + "/" + filesystemName + ".m3u"
+ Expect(os.WriteFile(plsFile, []byte("#PLAYLIST:Test\n"), 0600)).To(Succeed())
+
+ // Pre-populate mock repo with the stored normalization form
+ storedPath := tmpDir + "/" + storedName + ".m3u"
+ existingPls := &model.Playlist{
+ ID: "existing-id",
+ Name: "Existing Playlist",
+ Path: storedPath,
+ Sync: true,
+ }
+ mockPlsRepo.PathMap = map[string]*model.Playlist{storedPath: existingPls}
+
+ // Import using the filesystem's normalization form
+ plsFolder := &model.Folder{
+ ID: "1",
+ LibraryID: 1,
+ LibraryPath: tmpDir,
+ Path: "",
+ Name: "",
+ }
+ pls, err := ps.ImportFile(ctx, plsFolder, filesystemName+".m3u")
+ Expect(err).ToNot(HaveOccurred())
+
+ // Should update existing playlist, not create new one
+ Expect(pls.ID).To(Equal("existing-id"))
+ Expect(pls.Name).To(Equal("Existing Playlist"))
+ },
+ Entry("finds NFD-stored playlist when filesystem provides NFC path", "NFD", "NFC"),
+ Entry("finds NFC-stored playlist when filesystem provides NFD path", "NFC", "NFD"),
+ )
+
+ Describe("Cross-library relative paths", func() {
+ var tmpDir, plsDir, songsDir string
+
+ BeforeEach(func() {
+ // Create temp directory structure
+ tmpDir = GinkgoT().TempDir()
+ plsDir = tmpDir + "/playlists"
+ songsDir = tmpDir + "/songs"
+ Expect(os.Mkdir(plsDir, 0755)).To(Succeed())
+ Expect(os.Mkdir(songsDir, 0755)).To(Succeed())
+
+ // Setup two different libraries with paths matching our temp structure
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: songsDir},
+ {ID: 2, Path: plsDir},
+ })
+
+ // Create a mock media file repository that returns files for both libraries
+ // Note: The paths are relative to their respective library roots
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{
+ data: []string{
+ "abc.mp3", // This is songs/abc.mp3 relative to songsDir
+ "def.mp3", // This is playlists/def.mp3 relative to plsDir
+ },
+ }
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("handles relative paths that reference files in other libraries", func() {
+ // Create a temporary playlist file with relative path
+ plsContent := "#PLAYLIST:Cross Library Test\n../songs/abc.mp3\ndef.mp3"
+ plsFile := plsDir + "/test.m3u"
+ Expect(os.WriteFile(plsFile, []byte(plsContent), 0600)).To(Succeed())
+
+ // Playlist is in the Playlists library folder
+ // Important: Path should be relative to LibraryPath, and Name is the folder name
+ plsFolder := &model.Folder{
+ ID: "2",
+ LibraryID: 2,
+ LibraryPath: plsDir,
+ Path: "",
+ Name: "",
+ }
+
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(2))
+ Expect(pls.Tracks[0].Path).To(Equal("abc.mp3")) // From songsDir library
+ Expect(pls.Tracks[1].Path).To(Equal("def.mp3")) // From plsDir library
+ })
+
+ It("ignores paths that point outside all libraries", func() {
+ // Create a temporary playlist file with path outside libraries
+ plsContent := "#PLAYLIST:Outside Test\n../../outside.mp3\nabc.mp3"
+ plsFile := plsDir + "/test.m3u"
+ Expect(os.WriteFile(plsFile, []byte(plsContent), 0600)).To(Succeed())
+
+ plsFolder := &model.Folder{
+ ID: "2",
+ LibraryID: 2,
+ LibraryPath: plsDir,
+ Path: "",
+ Name: "",
+ }
+
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ // Should only find abc.mp3, not outside.mp3
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].Path).To(Equal("abc.mp3"))
+ })
+
+ It("handles relative paths with multiple '../' components", func() {
+ // Create a nested structure: tmpDir/playlists/subfolder/test.m3u
+ subFolder := plsDir + "/subfolder"
+ Expect(os.Mkdir(subFolder, 0755)).To(Succeed())
+
+ // Create the media file in the subfolder directory
+ // The mock will return it as "def.mp3" relative to plsDir
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{
+ data: []string{
+ "abc.mp3", // From songsDir library
+ "def.mp3", // From plsDir library root
+ },
+ }
+
+ // From subfolder, ../../songs/abc.mp3 should resolve to songs library
+ // ../def.mp3 should resolve to plsDir/def.mp3
+ plsContent := "#PLAYLIST:Nested Test\n../../songs/abc.mp3\n../def.mp3"
+ plsFile := subFolder + "/test.m3u"
+ Expect(os.WriteFile(plsFile, []byte(plsContent), 0600)).To(Succeed())
+
+ // The folder: AbsolutePath = LibraryPath + Path + Name
+ // So for /playlists/subfolder: LibraryPath=/playlists, Path="", Name="subfolder"
+ plsFolder := &model.Folder{
+ ID: "2",
+ LibraryID: 2,
+ LibraryPath: plsDir,
+ Path: "", // Empty because subfolder is directly under library root
+ Name: "subfolder", // The folder name
+ }
+
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(2))
+ Expect(pls.Tracks[0].Path).To(Equal("abc.mp3")) // From songsDir library
+ Expect(pls.Tracks[1].Path).To(Equal("def.mp3")) // From plsDir library root
+ })
+
+ It("correctly resolves libraries when one path is a prefix of another", func() {
+ // This tests the bug where /music would match before /music-classical
+ // Create temp directory structure with prefix conflict
+ tmpDir := GinkgoT().TempDir()
+ musicDir := tmpDir + "/music"
+ musicClassicalDir := tmpDir + "/music-classical"
+ Expect(os.Mkdir(musicDir, 0755)).To(Succeed())
+ Expect(os.Mkdir(musicClassicalDir, 0755)).To(Succeed())
+
+ // Setup two libraries where one is a prefix of the other
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: musicDir}, // /tmp/xxx/music
+ {ID: 2, Path: musicClassicalDir}, // /tmp/xxx/music-classical
+ })
+
+ // Mock will return tracks from both libraries
+ ds.MockedMediaFile = &mockedMediaFileFromListRepo{
+ data: []string{
+ "rock.mp3", // From music library
+ "bach.mp3", // From music-classical library
+ },
+ }
+
+ // Create playlist in music library that references music-classical
+ plsContent := "#PLAYLIST:Cross Prefix Test\nrock.mp3\n../music-classical/bach.mp3"
+ plsFile := musicDir + "/test.m3u"
+ Expect(os.WriteFile(plsFile, []byte(plsContent), 0600)).To(Succeed())
+
+ plsFolder := &model.Folder{
+ ID: "1",
+ LibraryID: 1,
+ LibraryPath: musicDir,
+ Path: "",
+ Name: "",
+ }
+
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(2))
+ Expect(pls.Tracks[0].Path).To(Equal("rock.mp3")) // From music library
+ Expect(pls.Tracks[1].Path).To(Equal("bach.mp3")) // From music-classical library (not music!)
+ })
+
+ It("correctly handles identical relative paths from different libraries", func() {
+ // This tests the bug where two libraries have files at the same relative path
+ // and only one appears in the playlist
+ tmpDir := GinkgoT().TempDir()
+ musicDir := tmpDir + "/music"
+ classicalDir := tmpDir + "/classical"
+ Expect(os.Mkdir(musicDir, 0755)).To(Succeed())
+ Expect(os.Mkdir(classicalDir, 0755)).To(Succeed())
+ Expect(os.MkdirAll(musicDir+"/album", 0755)).To(Succeed())
+ Expect(os.MkdirAll(classicalDir+"/album", 0755)).To(Succeed())
+ // Create placeholder files so paths resolve correctly
+ Expect(os.WriteFile(musicDir+"/album/track.mp3", []byte{}, 0600)).To(Succeed())
+ Expect(os.WriteFile(classicalDir+"/album/track.mp3", []byte{}, 0600)).To(Succeed())
+
+ // Both libraries have a file at "album/track.mp3"
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: musicDir},
+ {ID: 2, Path: classicalDir},
+ })
+
+ // Mock returns files with same relative path but different IDs and library IDs
+ // Keys use the library-qualified format: "libraryID:path"
+ ds.MockedMediaFile = &mockedMediaFileRepo{
+ data: map[string]model.MediaFile{
+ "1:album/track.mp3": {ID: "music-track", Path: "album/track.mp3", LibraryID: 1, Title: "Rock Song"},
+ "2:album/track.mp3": {ID: "classical-track", Path: "album/track.mp3", LibraryID: 2, Title: "Classical Piece"},
+ },
+ }
+ // Recreate playlists service to pick up new mock
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+
+ // Create playlist in music library that references both tracks
+ plsContent := "#PLAYLIST:Same Path Test\nalbum/track.mp3\n../classical/album/track.mp3"
+ plsFile := musicDir + "/test.m3u"
+ Expect(os.WriteFile(plsFile, []byte(plsContent), 0600)).To(Succeed())
+
+ plsFolder := &model.Folder{
+ ID: "1",
+ LibraryID: 1,
+ LibraryPath: musicDir,
+ Path: "",
+ Name: "",
+ }
+
+ pls, err := ps.ImportFile(ctx, plsFolder, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+
+ // Should have BOTH tracks, not just one
+ Expect(pls.Tracks).To(HaveLen(2), "Playlist should contain both tracks with same relative path")
+
+ // Verify we got tracks from DIFFERENT libraries (the key fix!)
+ // Collect the library IDs
+ libIDs := make(map[int]bool)
+ for _, track := range pls.Tracks {
+ libIDs[track.LibraryID] = true
+ }
+ Expect(libIDs).To(HaveLen(2), "Tracks should come from two different libraries")
+ Expect(libIDs[1]).To(BeTrue(), "Should have track from library 1")
+ Expect(libIDs[2]).To(BeTrue(), "Should have track from library 2")
+
+ // Both tracks should have the same relative path
+ Expect(pls.Tracks[0].Path).To(Equal("album/track.mp3"))
+ Expect(pls.Tracks[1].Path).To(Equal("album/track.mp3"))
+ })
+ })
+ })
+
+ Describe("ImportM3U", func() {
+ var repo *mockedMediaFileFromListRepo
+ BeforeEach(func() {
+ repo = &mockedMediaFileFromListRepo{}
+ ds.MockedMediaFile = repo
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ mockLibRepo.SetData([]model.Library{{ID: 1, Path: "/music"}, {ID: 2, Path: "/new"}})
+ ctx = request.WithUser(ctx, model.User{ID: "123"})
+ })
+
+ It("parses well-formed playlists", func() {
+ repo.data = []string{
+ "tests/test.mp3",
+ "tests/test.ogg",
+ "tests/01 Invisible (RED) Edit Version.mp3",
+ "downloads/newfile.flac",
+ }
+ m3u := strings.Join([]string{
+ "#PLAYLIST:playlist 1",
+ "/music/tests/test.mp3",
+ "/music/tests/test.ogg",
+ "/new/downloads/newfile.flac",
+ "file:///music/tests/01%20Invisible%20(RED)%20Edit%20Version.mp3",
+ }, "\n")
+ f := strings.NewReader(m3u)
+
+ pls, err := ps.ImportM3U(ctx, f)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.OwnerID).To(Equal("123"))
+ Expect(pls.Name).To(Equal("playlist 1"))
+ Expect(pls.Sync).To(BeFalse())
+ Expect(pls.Tracks).To(HaveLen(4))
+ Expect(pls.Tracks[0].Path).To(Equal("tests/test.mp3"))
+ Expect(pls.Tracks[1].Path).To(Equal("tests/test.ogg"))
+ Expect(pls.Tracks[2].Path).To(Equal("downloads/newfile.flac"))
+ Expect(pls.Tracks[3].Path).To(Equal("tests/01 Invisible (RED) Edit Version.mp3"))
+ Expect(mockPlsRepo.Last).To(Equal(pls))
+ })
+
+ It("sets the playlist name as a timestamp if the #PLAYLIST directive is not present", func() {
+ repo.data = []string{
+ "tests/test.mp3",
+ "tests/test.ogg",
+ "/tests/01 Invisible (RED) Edit Version.mp3",
+ }
+ m3u := strings.Join([]string{
+ "/music/tests/test.mp3",
+ "/music/tests/test.ogg",
+ }, "\n")
+ f := strings.NewReader(m3u)
+ pls, err := ps.ImportM3U(ctx, f)
+ Expect(err).ToNot(HaveOccurred())
+ _, err = time.Parse(time.RFC3339, pls.Name)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(2))
+ })
+
+ It("returns only tracks that exist in the database and in the same order as the m3u", func() {
+ repo.data = []string{
+ "album1/test1.mp3",
+ "album2/test2.mp3",
+ "album3/test3.mp3",
+ }
+ m3u := strings.Join([]string{
+ "/music/album3/test3.mp3",
+ "/music/album1/test1.mp3",
+ "/music/album4/test4.mp3",
+ "/music/album2/test2.mp3",
+ }, "\n")
+ f := strings.NewReader(m3u)
+ pls, err := ps.ImportM3U(ctx, f)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(3))
+ Expect(pls.Tracks[0].Path).To(Equal("album3/test3.mp3"))
+ Expect(pls.Tracks[1].Path).To(Equal("album1/test1.mp3"))
+ Expect(pls.Tracks[2].Path).To(Equal("album2/test2.mp3"))
+ })
+
+ It("is case-insensitive when comparing paths", func() {
+ repo.data = []string{
+ "abc/tEsT1.Mp3",
+ }
+ m3u := strings.Join([]string{
+ "/music/ABC/TeSt1.mP3",
+ }, "\n")
+ f := strings.NewReader(m3u)
+ pls, err := ps.ImportM3U(ctx, f)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].Path).To(Equal("abc/tEsT1.Mp3"))
+ })
+
+ It("parses #EXTALBUMARTURL with HTTP URL via ImportM3U", func() {
+ conf.Server.EnableM3UExternalAlbumArt = true
+
+ repo.data = []string{"tests/test.mp3"}
+ m3u := "#EXTALBUMARTURL:https://example.com/cover.jpg\n/music/tests/test.mp3\n"
+ pls, err := ps.ImportM3U(ctx, strings.NewReader(m3u))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(Equal("https://example.com/cover.jpg"))
+ })
+
+ It("ignores relative #EXTALBUMARTURL when imported via API (no folder context)", func() {
+ repo.data = []string{"tests/test.mp3"}
+ m3u := "#EXTALBUMARTURL:cover.jpg\n/music/tests/test.mp3\n"
+ pls, err := ps.ImportM3U(ctx, strings.NewReader(m3u))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ExternalImageURL).To(BeEmpty())
+ })
+
+ // Fullwidth characters (e.g., ABCD) are not handled by SQLite's NOCASE collation,
+ // so we need exact matching for non-ASCII characters.
+ It("matches fullwidth characters exactly (SQLite NOCASE limitation)", func() {
+ // Fullwidth uppercase ACROSS (U+FF21, U+FF23, U+FF32, U+FF2F, U+FF33, U+FF33)
+ repo.data = []string{
+ "plex/02 - ACROSS.flac",
+ }
+ m3u := "/music/plex/02 - ACROSS.flac\n"
+ f := strings.NewReader(m3u)
+ pls, err := ps.ImportM3U(ctx, f)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].Path).To(Equal("plex/02 - ACROSS.flac"))
+ })
+
+ // Unicode normalization tests: NFC (composed) vs NFD (decomposed) forms
+ // macOS stores paths in NFD, Linux/Windows use NFC. Playlists may use either form.
+ DescribeTable("matches paths across Unicode NFC/NFD normalization",
+ func(description, pathNFC string, dbForm, playlistForm norm.Form) {
+ pathNFD := norm.NFD.String(pathNFC)
+ Expect(pathNFD).ToNot(Equal(pathNFC), "test path should have decomposable characters")
+
+ // Set up DB with specified normalization form
+ var dbPath string
+ if dbForm == norm.NFC {
+ dbPath = pathNFC
+ } else {
+ dbPath = pathNFD
+ }
+ repo.data = []string{dbPath}
+
+ // Set up playlist with specified normalization form
+ var playlistPath string
+ if playlistForm == norm.NFC {
+ playlistPath = pathNFC
+ } else {
+ playlistPath = pathNFD
+ }
+ m3u := "/music/" + playlistPath + "\n"
+ f := strings.NewReader(m3u)
+
+ pls, err := ps.ImportM3U(ctx, f)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].Path).To(Equal(dbPath))
+ },
+ // French: è (U+00E8) decomposes to e + combining grave (U+0065 + U+0300)
+ Entry("French diacritics - DB:NFD, playlist:NFC",
+ "macOS DB with Apple Music playlist",
+ "artist/Michèle/song.mp3", norm.NFD, norm.NFC),
+
+ // Japanese Katakana: ド (U+30C9) decomposes to ト (U+30C8) + combining dakuten (U+3099)
+ Entry("Japanese Katakana with dakuten - DB:NFC, playlist:NFC (#4884)",
+ "Linux/Windows DB with NFC playlist",
+ "artist/\u30a2\u30a4\u30c9\u30eb/\u30c9\u30ea\u30fc\u30e0\u30bd\u30f3\u30b0.mp3", norm.NFC, norm.NFC),
+ Entry("Japanese Katakana with dakuten - DB:NFD, playlist:NFC (#4884)",
+ "macOS DB with NFC playlist",
+ "artist/\u30a2\u30a4\u30c9\u30eb/\u30c9\u30ea\u30fc\u30e0\u30bd\u30f3\u30b0.mp3", norm.NFD, norm.NFC),
+
+ // Cyrillic: й (U+0439) decomposes to и (U+0438) + combining breve (U+0306)
+ Entry("Cyrillic characters - DB:NFD, playlist:NFC (#4791)",
+ "macOS DB with NFC playlist",
+ "Жуки/Батарейка/01 - Разлюбила.mp3", norm.NFD, norm.NFC),
+
+ // Polish: ó (U+00F3) decomposes to o + combining acute (U+0301)
+ Entry("Polish diacritics - DB:NFD, playlist:NFC (#4663)",
+ "macOS DB with NFC playlist",
+ "Zespół/Człowiek/Piosenka o miłości.mp3", norm.NFD, norm.NFC),
+ Entry("Polish diacritics - DB:NFC, playlist:NFD",
+ "Linux/Windows DB with macOS-exported playlist",
+ "Zespół/Człowiek/Piosenka o miłości.mp3", norm.NFC, norm.NFD),
+ )
+
+ })
+
+ Describe("InPath", func() {
+ var folder model.Folder
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ folder = model.Folder{
+ LibraryPath: "/music",
+ Path: "playlists/abc",
+ Name: "folder1",
+ }
+ })
+
+ It("returns true if PlaylistsPath is empty", func() {
+ conf.Server.PlaylistsPath = ""
+ Expect(playlists.InPath(folder)).To(BeTrue())
+ })
+
+ It("returns true if PlaylistsPath is any (**/**)", func() {
+ conf.Server.PlaylistsPath = "**/**"
+ Expect(playlists.InPath(folder)).To(BeTrue())
+ })
+
+ It("returns true if folder is in PlaylistsPath", func() {
+ conf.Server.PlaylistsPath = "other/**:playlists/**"
+ Expect(playlists.InPath(folder)).To(BeTrue())
+ })
+
+ It("returns false if folder is not in PlaylistsPath", func() {
+ conf.Server.PlaylistsPath = "other"
+ Expect(playlists.InPath(folder)).To(BeFalse())
+ })
+
+ It("returns true if for a playlist in root of MusicFolder if PlaylistsPath is '.'", func() {
+ conf.Server.PlaylistsPath = "."
+ Expect(playlists.InPath(folder)).To(BeFalse())
+
+ folder2 := model.Folder{
+ LibraryPath: "/music",
+ Path: "",
+ Name: ".",
+ }
+
+ Expect(playlists.InPath(folder2)).To(BeTrue())
+ })
+ })
+})
+
+// mockedMediaFileRepo's FindByPaths method returns MediaFiles for the given paths.
+// If data map is provided, looks up files by key; otherwise creates them from paths.
+type mockedMediaFileRepo struct {
+ model.MediaFileRepository
+ data map[string]model.MediaFile
+}
+
+func (r *mockedMediaFileRepo) FindByPaths(paths []string) (model.MediaFiles, error) {
+ var mfs model.MediaFiles
+
+ // If data map provided, look up files
+ if r.data != nil {
+ for _, path := range paths {
+ if mf, ok := r.data[path]; ok {
+ mfs = append(mfs, mf)
+ }
+ }
+ return mfs, nil
+ }
+
+ // Otherwise, create MediaFiles from paths
+ for idx, path := range paths {
+ // Strip library qualifier if present (format: "libraryID:path")
+ actualPath := path
+ libraryID := 1
+ if parts := strings.SplitN(path, ":", 2); len(parts) == 2 {
+ if id, err := strconv.Atoi(parts[0]); err == nil {
+ libraryID = id
+ actualPath = parts[1]
+ }
+ }
+
+ mfs = append(mfs, model.MediaFile{
+ ID: strconv.Itoa(idx),
+ Path: actualPath,
+ LibraryID: libraryID,
+ })
+ }
+ return mfs, nil
+}
+
+// mockedMediaFileFromListRepo's FindByPaths method returns a list of MediaFiles based on the data field
+type mockedMediaFileFromListRepo struct {
+ model.MediaFileRepository
+ data []string
+}
+
+func (r *mockedMediaFileFromListRepo) FindByPaths(paths []string) (model.MediaFiles, error) {
+ var mfs model.MediaFiles
+
+ for idx, dataPath := range r.data {
+ for _, requestPath := range paths {
+ // Strip library qualifier if present (format: "libraryID:path")
+ actualPath := requestPath
+ libraryID := 1
+ if parts := strings.SplitN(requestPath, ":", 2); len(parts) == 2 {
+ if id, err := strconv.Atoi(parts[0]); err == nil {
+ libraryID = id
+ actualPath = parts[1]
+ }
+ }
+
+ // Case-insensitive comparison (like SQL's "collate nocase"), but with no
+ // implicit Unicode normalization (SQLite does not normalize NFC/NFD).
+ if strings.EqualFold(actualPath, dataPath) {
+ mfs = append(mfs, model.MediaFile{
+ ID: strconv.Itoa(idx),
+ Path: dataPath, // Return original path from DB
+ LibraryID: libraryID,
+ })
+ break
+ }
+ }
+ }
+ return mfs, nil
+}
diff --git a/core/playlists/parse_m3u.go b/core/playlists/parse_m3u.go
new file mode 100644
index 000000000..b9f5c92a2
--- /dev/null
+++ b/core/playlists/parse_m3u.go
@@ -0,0 +1,324 @@
+package playlists
+
+import (
+ "cmp"
+ "context"
+ "fmt"
+ "io"
+ "net/url"
+ "path/filepath"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/utils/slice"
+ "golang.org/x/text/unicode/norm"
+)
+
+func (s *playlists) parseM3U(ctx context.Context, pls *model.Playlist, folder *model.Folder, reader io.Reader) error {
+ mediaFileRepository := s.ds.MediaFile(ctx)
+ resolver, err := newPathResolver(ctx, s.ds)
+ if err != nil {
+ return err
+ }
+ var mfs model.MediaFiles
+ // Chunk size of 100 lines, as each line can generate up to 4 lookup candidates
+ // (NFC/NFD × raw/lowercase), and SQLite has a max expression tree depth of 1000.
+ for lines := range slice.CollectChunks(slice.LinesFrom(reader), 100) {
+ filteredLines := make([]string, 0, len(lines))
+ for _, line := range lines {
+ line := strings.TrimSpace(line)
+ if after, ok := strings.CutPrefix(line, "#PLAYLIST:"); ok {
+ pls.Name = after
+ continue
+ }
+ if after, ok := strings.CutPrefix(line, "#EXTALBUMARTURL:"); ok {
+ pls.ExternalImageURL = resolveImageURL(after, folder, resolver.matcher)
+ continue
+ }
+ // Skip empty lines and extended info
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ if after, ok := strings.CutPrefix(line, "file://"); ok {
+ line = after
+ line, _ = url.PathUnescape(line)
+ }
+ if !model.IsAudioFile(line) {
+ continue
+ }
+ filteredLines = append(filteredLines, line)
+ }
+ resolvedPaths, err := resolver.resolvePaths(ctx, folder, filteredLines)
+ if err != nil {
+ log.Warn(ctx, "Error resolving paths in playlist", "playlist", pls.Name, err)
+ continue
+ }
+
+ // SQLite comparisons do not perform Unicode normalization, and filesystem normalization
+ // differs across platforms (macOS often yields NFD, while Linux/Windows typically use NFC).
+ // Generate lookup candidates for both forms so playlist entries match DB paths regardless
+ // of the original normalization. See https://github.com/navidrome/navidrome/issues/4884
+ //
+ // We also include the original (non-lowercased) paths because SQLite's COLLATE NOCASE
+ // only handles ASCII case-insensitivity. Non-ASCII characters like fullwidth letters
+ // (e.g., ABCD vs abcd) are not matched case-insensitively by NOCASE.
+ lookupCandidates := make([]string, 0, len(resolvedPaths)*4)
+ seen := make(map[string]struct{}, len(resolvedPaths)*4)
+ for _, path := range resolvedPaths {
+ // Add original paths first (for exact matching of non-ASCII characters)
+ nfcRaw := norm.NFC.String(path)
+ if _, ok := seen[nfcRaw]; !ok {
+ seen[nfcRaw] = struct{}{}
+ lookupCandidates = append(lookupCandidates, nfcRaw)
+ }
+ nfdRaw := norm.NFD.String(path)
+ if _, ok := seen[nfdRaw]; !ok {
+ seen[nfdRaw] = struct{}{}
+ lookupCandidates = append(lookupCandidates, nfdRaw)
+ }
+
+ // Add lowercased paths (for ASCII case-insensitive matching via NOCASE)
+ nfc := strings.ToLower(nfcRaw)
+ if _, ok := seen[nfc]; !ok {
+ seen[nfc] = struct{}{}
+ lookupCandidates = append(lookupCandidates, nfc)
+ }
+ nfd := strings.ToLower(nfdRaw)
+ if _, ok := seen[nfd]; !ok {
+ seen[nfd] = struct{}{}
+ lookupCandidates = append(lookupCandidates, nfd)
+ }
+ }
+
+ found, err := mediaFileRepository.FindByPaths(lookupCandidates)
+ if err != nil {
+ log.Warn(ctx, "Error reading files from DB", "playlist", pls.Name, err)
+ continue
+ }
+
+ // Build lookup map with library-qualified keys, normalized for comparison.
+ // Canonicalize to NFC so NFD/NFC become comparable.
+ existing := make(map[string]int, len(found))
+ for idx := range found {
+ key := fmt.Sprintf("%d:%s", found[idx].LibraryID, strings.ToLower(norm.NFC.String(found[idx].Path)))
+ existing[key] = idx
+ }
+
+ // Find media files in the order of the resolved paths, to keep playlist order.
+ // Both `existing` keys and `resolvedPaths` use the library-qualified format "libraryID:relativePath",
+ // so normalizing the full string produces matching keys (digits and ':' are ASCII-invariant).
+ for _, path := range resolvedPaths {
+ key := strings.ToLower(norm.NFC.String(path))
+ idx, ok := existing[key]
+ if ok {
+ mfs = append(mfs, found[idx])
+ } else {
+ // Prefer logging a composed representation when possible to avoid confusing output
+ // with decomposed combining marks.
+ log.Warn(ctx, "Path in playlist not found", "playlist", pls.Name, "path", norm.NFC.String(path))
+ }
+ }
+ }
+ if pls.Name == "" {
+ pls.Name = time.Now().Format(time.RFC3339)
+ }
+ pls.Tracks = nil
+ pls.AddMediaFiles(mfs)
+
+ return nil
+}
+
+// pathResolution holds the result of resolving a playlist path to a library-relative path.
+type pathResolution struct {
+ absolutePath string
+ libraryPath string
+ libraryID int
+ valid bool
+}
+
+// ToQualifiedString converts the path resolution to a library-qualified string with forward slashes.
+// Format: "libraryID:relativePath" with forward slashes for path separators.
+func (r pathResolution) ToQualifiedString() (string, error) {
+ if !r.valid {
+ return "", fmt.Errorf("invalid path resolution")
+ }
+ relativePath, err := filepath.Rel(r.libraryPath, r.absolutePath)
+ if err != nil {
+ return "", err
+ }
+ // Convert path separators to forward slashes
+ return fmt.Sprintf("%d:%s", r.libraryID, filepath.ToSlash(relativePath)), nil
+}
+
+// libraryMatcher holds sorted libraries with cleaned paths for efficient path matching.
+type libraryMatcher struct {
+ libraries model.Libraries
+ cleanedPaths []string
+}
+
+// findLibraryForPath finds which library contains the given absolute path.
+// Returns library ID and path, or 0 and empty string if not found.
+func (lm *libraryMatcher) findLibraryForPath(absolutePath string) (int, string) {
+ // Check sorted libraries (longest path first) to find the best match
+ for i, cleanLibPath := range lm.cleanedPaths {
+ // Check if absolutePath is under this library path
+ if strings.HasPrefix(absolutePath, cleanLibPath) {
+ // Ensure it's a proper path boundary (not just a prefix)
+ if len(absolutePath) == len(cleanLibPath) || absolutePath[len(cleanLibPath)] == filepath.Separator {
+ return lm.libraries[i].ID, cleanLibPath
+ }
+ }
+ }
+ return 0, ""
+}
+
+// newLibraryMatcher creates a libraryMatcher with libraries sorted by path length (longest first).
+// This ensures correct matching when library paths are prefixes of each other.
+// Example: /music-classical must be checked before /music
+// Otherwise, /music-classical/track.mp3 would match /music instead of /music-classical
+func newLibraryMatcher(libs model.Libraries) *libraryMatcher {
+ // Sort libraries by path length (descending) to ensure longest paths match first.
+ slices.SortFunc(libs, func(i, j model.Library) int {
+ return cmp.Compare(len(j.Path), len(i.Path)) // Reverse order for descending
+ })
+
+ // Pre-clean all library paths once for efficient matching
+ cleanedPaths := make([]string, len(libs))
+ for i, lib := range libs {
+ cleanedPaths[i] = filepath.Clean(lib.Path)
+ }
+ return &libraryMatcher{
+ libraries: libs,
+ cleanedPaths: cleanedPaths,
+ }
+}
+
+// pathResolver handles path resolution logic for playlist imports.
+type pathResolver struct {
+ matcher *libraryMatcher
+}
+
+// newPathResolver creates a pathResolver with libraries loaded from the datastore.
+func newPathResolver(ctx context.Context, ds model.DataStore) (*pathResolver, error) {
+ libs, err := ds.Library(ctx).GetAll()
+ if err != nil {
+ return nil, err
+ }
+ matcher := newLibraryMatcher(libs)
+ return &pathResolver{matcher: matcher}, nil
+}
+
+// resolvePath determines the absolute path and library path for a playlist entry.
+// For absolute paths, it uses them directly.
+// For relative paths, it resolves them relative to the playlist's folder location.
+// Example: playlist at /music/playlists/test.m3u with line "../songs/abc.mp3"
+//
+// resolves to /music/songs/abc.mp3
+func (r *pathResolver) resolvePath(line string, folder *model.Folder) pathResolution {
+ var absolutePath string
+ if folder != nil && !filepath.IsAbs(line) {
+ // Resolve relative path to absolute path based on playlist location
+ absolutePath = filepath.Clean(filepath.Join(folder.AbsolutePath(), line))
+ } else {
+ // Use absolute path directly after cleaning
+ absolutePath = filepath.Clean(line)
+ }
+
+ return r.findInLibraries(absolutePath)
+}
+
+// findInLibraries matches an absolute path against all known libraries and returns
+// a pathResolution with the library information. Returns an invalid resolution if
+// the path is not found in any library.
+func (r *pathResolver) findInLibraries(absolutePath string) pathResolution {
+ libID, libPath := r.matcher.findLibraryForPath(absolutePath)
+ if libID == 0 {
+ return pathResolution{valid: false}
+ }
+ return pathResolution{
+ absolutePath: absolutePath,
+ libraryPath: libPath,
+ libraryID: libID,
+ valid: true,
+ }
+}
+
+// resolvePaths converts playlist file paths to library-qualified paths (format: "libraryID:relativePath").
+// For relative paths, it resolves them to absolute paths first, then determines which
+// library they belong to. This allows playlists to reference files across library boundaries.
+func (r *pathResolver) resolvePaths(ctx context.Context, folder *model.Folder, lines []string) ([]string, error) {
+ results := make([]string, 0, len(lines))
+ for idx, line := range lines {
+ resolution := r.resolvePath(line, folder)
+
+ if !resolution.valid {
+ log.Warn(ctx, "Path in playlist not found in any library", "path", line, "line", idx)
+ continue
+ }
+
+ qualifiedPath, err := resolution.ToQualifiedString()
+ if err != nil {
+ log.Debug(ctx, "Error getting library-qualified path", "path", line,
+ "libPath", resolution.libraryPath, "filePath", resolution.absolutePath, err)
+ continue
+ }
+
+ results = append(results, qualifiedPath)
+ }
+
+ return results, nil
+}
+
+// resolveImageURL resolves an #EXTALBUMARTURL value to a storable string.
+// HTTP(S) URLs are stored as-is (gated by EnableM3UExternalAlbumArt).
+// Local paths (file://, absolute, or relative) are resolved to an absolute path
+// and validated against known library boundaries via matcher.
+func resolveImageURL(value string, folder *model.Folder, matcher *libraryMatcher) string {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return ""
+ }
+
+ // HTTP(S) URLs — store as-is, but only if external album art is enabled
+ if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") {
+ if !conf.Server.EnableM3UExternalAlbumArt {
+ return ""
+ }
+ return value
+ }
+
+ // Resolve to local absolute path
+ localPath, ok := resolveLocalPath(value, folder)
+ if !ok {
+ return ""
+ }
+
+ // Validate path is within a known library
+ if libID, _ := matcher.findLibraryForPath(localPath); libID == 0 {
+ return ""
+ }
+ return localPath
+}
+
+// resolveLocalPath converts a file://, absolute, or relative path to a clean absolute path.
+// Returns ("", false) if the path cannot be resolved.
+func resolveLocalPath(value string, folder *model.Folder) (string, bool) {
+ if after, ok := strings.CutPrefix(value, "file://"); ok {
+ decoded, err := url.PathUnescape(after)
+ if err != nil {
+ return "", false
+ }
+ return filepath.Clean(decoded), true
+ }
+ if filepath.IsAbs(value) {
+ return filepath.Clean(value), true
+ }
+ if folder == nil {
+ return "", false
+ }
+ return filepath.Clean(filepath.Join(folder.AbsolutePath(), value)), true
+}
diff --git a/core/playlists/parse_m3u_test.go b/core/playlists/parse_m3u_test.go
new file mode 100644
index 000000000..05e1c30e1
--- /dev/null
+++ b/core/playlists/parse_m3u_test.go
@@ -0,0 +1,406 @@
+package playlists
+
+import (
+ "context"
+
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("libraryMatcher", func() {
+ var ds *tests.MockDataStore
+ var mockLibRepo *tests.MockLibraryRepo
+ ctx := context.Background()
+
+ BeforeEach(func() {
+ mockLibRepo = &tests.MockLibraryRepo{}
+ ds = &tests.MockDataStore{
+ MockedLibrary: mockLibRepo,
+ }
+ })
+
+ // Helper function to create a libraryMatcher from the mock datastore
+ createMatcher := func(ds model.DataStore) *libraryMatcher {
+ libs, err := ds.Library(ctx).GetAll()
+ Expect(err).ToNot(HaveOccurred())
+ return newLibraryMatcher(libs)
+ }
+
+ Describe("Longest library path matching", func() {
+ It("matches the longest library path when multiple libraries share a prefix", func() {
+ // Setup libraries with prefix conflicts
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/music"},
+ {ID: 2, Path: "/music-classical"},
+ {ID: 3, Path: "/music-classical/opera"},
+ })
+
+ matcher := createMatcher(ds)
+
+ // Test that longest path matches first and returns correct library ID
+ testCases := []struct {
+ path string
+ expectedLibID int
+ expectedLibPath string
+ }{
+ {"/music-classical/opera/track.mp3", 3, "/music-classical/opera"},
+ {"/music-classical/track.mp3", 2, "/music-classical"},
+ {"/music/track.mp3", 1, "/music"},
+ {"/music-classical/opera/subdir/file.mp3", 3, "/music-classical/opera"},
+ }
+
+ for _, tc := range testCases {
+ libID, libPath := matcher.findLibraryForPath(tc.path)
+ Expect(libID).To(Equal(tc.expectedLibID), "Path %s should match library ID %d, but got %d", tc.path, tc.expectedLibID, libID)
+ Expect(libPath).To(Equal(tc.expectedLibPath), "Path %s should match library path %s, but got %s", tc.path, tc.expectedLibPath, libPath)
+ }
+ })
+
+ It("handles libraries with similar prefixes but different structures", func() {
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/home/user/music"},
+ {ID: 2, Path: "/home/user/music-backup"},
+ })
+
+ matcher := createMatcher(ds)
+
+ // Test that music-backup library is matched correctly
+ libID, libPath := matcher.findLibraryForPath("/home/user/music-backup/track.mp3")
+ Expect(libID).To(Equal(2))
+ Expect(libPath).To(Equal("/home/user/music-backup"))
+
+ // Test that music library is still matched correctly
+ libID, libPath = matcher.findLibraryForPath("/home/user/music/track.mp3")
+ Expect(libID).To(Equal(1))
+ Expect(libPath).To(Equal("/home/user/music"))
+ })
+
+ It("matches path that is exactly the library root", func() {
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/music"},
+ {ID: 2, Path: "/music-classical"},
+ })
+
+ matcher := createMatcher(ds)
+
+ // Exact library path should match
+ libID, libPath := matcher.findLibraryForPath("/music-classical")
+ Expect(libID).To(Equal(2))
+ Expect(libPath).To(Equal("/music-classical"))
+ })
+
+ It("handles complex nested library structures", func() {
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/media"},
+ {ID: 2, Path: "/media/audio"},
+ {ID: 3, Path: "/media/audio/classical"},
+ {ID: 4, Path: "/media/audio/classical/baroque"},
+ })
+
+ matcher := createMatcher(ds)
+
+ testCases := []struct {
+ path string
+ expectedLibID int
+ expectedLibPath string
+ }{
+ {"/media/audio/classical/baroque/bach/track.mp3", 4, "/media/audio/classical/baroque"},
+ {"/media/audio/classical/mozart/track.mp3", 3, "/media/audio/classical"},
+ {"/media/audio/rock/track.mp3", 2, "/media/audio"},
+ {"/media/video/movie.mp4", 1, "/media"},
+ }
+
+ for _, tc := range testCases {
+ libID, libPath := matcher.findLibraryForPath(tc.path)
+ Expect(libID).To(Equal(tc.expectedLibID), "Path %s should match library ID %d", tc.path, tc.expectedLibID)
+ Expect(libPath).To(Equal(tc.expectedLibPath), "Path %s should match library path %s", tc.path, tc.expectedLibPath)
+ }
+ })
+ })
+
+ Describe("Edge cases", func() {
+ It("handles empty library list", func() {
+ mockLibRepo.SetData([]model.Library{})
+
+ matcher := createMatcher(ds)
+ Expect(matcher).ToNot(BeNil())
+
+ // Should not match anything
+ libID, libPath := matcher.findLibraryForPath("/music/track.mp3")
+ Expect(libID).To(Equal(0))
+ Expect(libPath).To(BeEmpty())
+ })
+
+ It("handles single library", func() {
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/music"},
+ })
+
+ matcher := createMatcher(ds)
+
+ libID, libPath := matcher.findLibraryForPath("/music/track.mp3")
+ Expect(libID).To(Equal(1))
+ Expect(libPath).To(Equal("/music"))
+ })
+
+ It("handles libraries with special characters in paths", func() {
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/music[test]"},
+ {ID: 2, Path: "/music(backup)"},
+ })
+
+ matcher := createMatcher(ds)
+ Expect(matcher).ToNot(BeNil())
+
+ // Special characters should match literally
+ libID, libPath := matcher.findLibraryForPath("/music[test]/track.mp3")
+ Expect(libID).To(Equal(1))
+ Expect(libPath).To(Equal("/music[test]"))
+ })
+ })
+
+ Describe("Path matching order", func() {
+ It("ensures longest paths match first", func() {
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/a"},
+ {ID: 2, Path: "/ab"},
+ {ID: 3, Path: "/abc"},
+ })
+
+ matcher := createMatcher(ds)
+
+ // Verify that longer paths match correctly (not cut off by shorter prefix)
+ testCases := []struct {
+ path string
+ expectedLibID int
+ }{
+ {"/abc/file.mp3", 3},
+ {"/ab/file.mp3", 2},
+ {"/a/file.mp3", 1},
+ }
+
+ for _, tc := range testCases {
+ libID, _ := matcher.findLibraryForPath(tc.path)
+ Expect(libID).To(Equal(tc.expectedLibID), "Path %s should match library ID %d", tc.path, tc.expectedLibID)
+ }
+ })
+ })
+})
+
+var _ = Describe("pathResolver", func() {
+ var ds *tests.MockDataStore
+ var mockLibRepo *tests.MockLibraryRepo
+ var resolver *pathResolver
+ ctx := context.Background()
+
+ BeforeEach(func() {
+ mockLibRepo = &tests.MockLibraryRepo{}
+ ds = &tests.MockDataStore{
+ MockedLibrary: mockLibRepo,
+ }
+
+ // Setup test libraries
+ mockLibRepo.SetData([]model.Library{
+ {ID: 1, Path: "/music"},
+ {ID: 2, Path: "/music-classical"},
+ {ID: 3, Path: "/podcasts"},
+ })
+
+ var err error
+ resolver, err = newPathResolver(ctx, ds)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ Describe("resolvePath", func() {
+ Context("basic", func() {
+ It("resolves absolute paths", func() {
+ resolution := resolver.resolvePath("/music/artist/album/track.mp3", nil)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(1))
+ Expect(resolution.libraryPath).To(Equal("/music"))
+ Expect(resolution.absolutePath).To(Equal("/music/artist/album/track.mp3"))
+ })
+
+ It("resolves relative paths when folder is provided", func() {
+ folder := &model.Folder{
+ Path: "playlists",
+ LibraryPath: "/music",
+ LibraryID: 1,
+ }
+
+ resolution := resolver.resolvePath("../artist/album/track.mp3", folder)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(1))
+ Expect(resolution.absolutePath).To(Equal("/music/artist/album/track.mp3"))
+ })
+
+ It("returns invalid resolution for paths outside any library", func() {
+ resolution := resolver.resolvePath("/outside/library/track.mp3", nil)
+
+ Expect(resolution.valid).To(BeFalse())
+ })
+ })
+
+ Context("cross-library", func() {
+ It("resolves path within a library", func() {
+ resolution := resolver.resolvePath("/music/track.mp3", nil)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(1))
+ Expect(resolution.libraryPath).To(Equal("/music"))
+ Expect(resolution.absolutePath).To(Equal("/music/track.mp3"))
+ })
+
+ It("resolves path to the longest matching library", func() {
+ resolution := resolver.resolvePath("/music-classical/track.mp3", nil)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(2))
+ Expect(resolution.libraryPath).To(Equal("/music-classical"))
+ })
+
+ It("returns invalid resolution for path outside libraries", func() {
+ resolution := resolver.resolvePath("/videos/movie.mp4", nil)
+
+ Expect(resolution.valid).To(BeFalse())
+ })
+
+ It("cleans the path before matching", func() {
+ resolution := resolver.resolvePath("/music//artist/../artist/track.mp3", nil)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.absolutePath).To(Equal("/music/artist/track.mp3"))
+ })
+ })
+
+ Context("With relative paths", func() {
+ It("resolves relative path within same library", func() {
+ folder := &model.Folder{
+ Path: "playlists",
+ LibraryPath: "/music",
+ LibraryID: 1,
+ }
+
+ resolution := resolver.resolvePath("../songs/track.mp3", folder)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(1))
+ Expect(resolution.absolutePath).To(Equal("/music/songs/track.mp3"))
+ })
+
+ It("resolves relative path to different library", func() {
+ folder := &model.Folder{
+ Path: "playlists",
+ LibraryPath: "/music",
+ LibraryID: 1,
+ }
+
+ // Path goes up and into a different library
+ resolution := resolver.resolvePath("../../podcasts/episode.mp3", folder)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(3))
+ Expect(resolution.libraryPath).To(Equal("/podcasts"))
+ })
+
+ It("uses matcher to find correct library for resolved path", func() {
+ folder := &model.Folder{
+ Path: "playlists",
+ LibraryPath: "/music",
+ LibraryID: 1,
+ }
+
+ // This relative path resolves to music-classical library
+ resolution := resolver.resolvePath("../../music-classical/track.mp3", folder)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(2))
+ Expect(resolution.libraryPath).To(Equal("/music-classical"))
+ })
+
+ It("returns invalid for relative paths escaping all libraries", func() {
+ folder := &model.Folder{
+ Path: "playlists",
+ LibraryPath: "/music",
+ LibraryID: 1,
+ }
+
+ resolution := resolver.resolvePath("../../../../etc/passwd", folder)
+
+ Expect(resolution.valid).To(BeFalse())
+ })
+ })
+ })
+
+ Describe("Cross-library resolution scenarios", func() {
+ It("handles playlist in library A referencing file in library B", func() {
+ // Playlist is in /music/playlists
+ folder := &model.Folder{
+ Path: "playlists",
+ LibraryPath: "/music",
+ LibraryID: 1,
+ }
+
+ // Relative path that goes to /podcasts library
+ resolution := resolver.resolvePath("../../podcasts/show/episode.mp3", folder)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(3), "Should resolve to podcasts library")
+ Expect(resolution.libraryPath).To(Equal("/podcasts"))
+ })
+
+ It("prefers longer library paths when resolving", func() {
+ // Ensure /music-classical is matched instead of /music
+ resolution := resolver.resolvePath("/music-classical/baroque/track.mp3", nil)
+
+ Expect(resolution.valid).To(BeTrue())
+ Expect(resolution.libraryID).To(Equal(2), "Should match /music-classical, not /music")
+ })
+ })
+})
+
+var _ = Describe("pathResolution", func() {
+ Describe("ToQualifiedString", func() {
+ It("converts valid resolution to qualified string with forward slashes", func() {
+ resolution := pathResolution{
+ absolutePath: "/music/artist/album/track.mp3",
+ libraryPath: "/music",
+ libraryID: 1,
+ valid: true,
+ }
+
+ qualifiedStr, err := resolution.ToQualifiedString()
+
+ Expect(err).ToNot(HaveOccurred())
+ Expect(qualifiedStr).To(Equal("1:artist/album/track.mp3"))
+ })
+
+ It("handles Windows-style paths by converting to forward slashes", func() {
+ resolution := pathResolution{
+ absolutePath: "/music/artist/album/track.mp3",
+ libraryPath: "/music",
+ libraryID: 2,
+ valid: true,
+ }
+
+ qualifiedStr, err := resolution.ToQualifiedString()
+
+ Expect(err).ToNot(HaveOccurred())
+ // Should always use forward slashes regardless of OS
+ Expect(qualifiedStr).To(ContainSubstring("2:"))
+ Expect(qualifiedStr).ToNot(ContainSubstring("\\"))
+ })
+
+ It("returns error for invalid resolution", func() {
+ resolution := pathResolution{valid: false}
+
+ _, err := resolution.ToQualifiedString()
+
+ Expect(err).To(HaveOccurred())
+ })
+ })
+})
diff --git a/core/playlists/parse_nsp.go b/core/playlists/parse_nsp.go
new file mode 100644
index 000000000..56c80a950
--- /dev/null
+++ b/core/playlists/parse_nsp.go
@@ -0,0 +1,103 @@
+package playlists
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/criteria"
+ "github.com/navidrome/navidrome/utils/jsoncommentstrip"
+)
+
+func (s *playlists) newSyncedPlaylist(baseDir string, playlistFile string) (*model.Playlist, error) {
+ playlistPath := filepath.Join(baseDir, playlistFile)
+ info, err := os.Stat(playlistPath)
+ if err != nil {
+ return nil, err
+ }
+
+ var extension = filepath.Ext(playlistFile)
+ var name = playlistFile[0 : len(playlistFile)-len(extension)]
+
+ pls := &model.Playlist{
+ Name: name,
+ Comment: fmt.Sprintf("Auto-imported from '%s'", playlistFile),
+ Public: false,
+ Path: playlistPath,
+ Sync: true,
+ UpdatedAt: info.ModTime(),
+ }
+ return pls, nil
+}
+
+func getPositionFromOffset(data []byte, offset int64) (line, column int) {
+ line = 1
+ for _, b := range data[:offset] {
+ if b == '\n' {
+ line++
+ column = 1
+ } else {
+ column++
+ }
+ }
+ return
+}
+
+func (s *playlists) parseNSP(_ context.Context, pls *model.Playlist, reader io.Reader) error {
+ nsp := &nspFile{}
+ reader = io.LimitReader(reader, 100*1024) // Limit to 100KB
+ reader = jsoncommentstrip.NewReader(reader)
+ input, err := io.ReadAll(reader)
+ if err != nil {
+ return fmt.Errorf("reading SmartPlaylist: %w", err)
+ }
+ err = json.Unmarshal(input, nsp)
+ if err != nil {
+ var syntaxErr *json.SyntaxError
+ if errors.As(err, &syntaxErr) {
+ line, col := getPositionFromOffset(input, syntaxErr.Offset)
+ return fmt.Errorf("JSON syntax error in SmartPlaylist at line %d, column %d: %w", line, col, err)
+ }
+ return fmt.Errorf("JSON parsing error in SmartPlaylist: %w", err)
+ }
+ pls.Rules = &nsp.Criteria
+ if nsp.Name != "" {
+ pls.Name = nsp.Name
+ }
+ if nsp.Comment != "" {
+ pls.Comment = nsp.Comment
+ }
+ if nsp.Public != nil {
+ pls.Public = *nsp.Public
+ } else {
+ pls.Public = conf.Server.DefaultPlaylistPublicVisibility
+ }
+ return nil
+}
+
+type nspFile struct {
+ criteria.Criteria
+ Name string `json:"name"`
+ Comment string `json:"comment"`
+ Public *bool `json:"public"`
+}
+
+func (i *nspFile) UnmarshalJSON(data []byte) error {
+ m := map[string]any{}
+ err := json.Unmarshal(data, &m)
+ if err != nil {
+ return err
+ }
+ i.Name, _ = m["name"].(string)
+ i.Comment, _ = m["comment"].(string)
+ if public, ok := m["public"].(bool); ok {
+ i.Public = &public
+ }
+ return json.Unmarshal(data, &i.Criteria)
+}
diff --git a/core/playlists/parse_nsp_test.go b/core/playlists/parse_nsp_test.go
new file mode 100644
index 000000000..516a5355d
--- /dev/null
+++ b/core/playlists/parse_nsp_test.go
@@ -0,0 +1,228 @@
+package playlists
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/criteria"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("parseNSP", func() {
+ var s *playlists
+ ctx := context.Background()
+
+ BeforeEach(func() {
+ s = &playlists{}
+ })
+
+ It("parses a well-formed NSP with all fields", func() {
+ nsp := `{
+ "name": "My Smart Playlist",
+ "comment": "A test playlist",
+ "public": true,
+ "all": [{"is": {"loved": true}}],
+ "sort": "title",
+ "order": "asc",
+ "limit": 50
+ }`
+ pls := &model.Playlist{Name: "default-name"}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("My Smart Playlist"))
+ Expect(pls.Comment).To(Equal("A test playlist"))
+ Expect(pls.Public).To(BeTrue())
+ Expect(pls.Rules).ToNot(BeNil())
+ Expect(pls.Rules.Sort).To(Equal("title"))
+ Expect(pls.Rules.Order).To(Equal("asc"))
+ Expect(pls.Rules.Limit).To(Equal(50))
+ Expect(pls.Rules.Expression).To(BeAssignableToTypeOf(criteria.All{}))
+ })
+
+ It("keeps existing name when NSP has no name field", func() {
+ nsp := `{"all": [{"is": {"loved": true}}]}`
+ pls := &model.Playlist{Name: "Original Name"}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("Original Name"))
+ })
+
+ It("keeps existing comment when NSP has no comment field", func() {
+ nsp := `{"all": [{"is": {"loved": true}}]}`
+ pls := &model.Playlist{Comment: "Original Comment"}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Comment).To(Equal("Original Comment"))
+ })
+
+ It("strips JSON comments before parsing", func() {
+ nsp := `{
+ // Line comment
+ "name": "Commented Playlist",
+ /* Block comment */
+ "all": [{"is": {"loved": true}}]
+ }`
+ pls := &model.Playlist{}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("Commented Playlist"))
+ })
+
+ It("uses server default when public field is absent", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultPlaylistPublicVisibility = true
+
+ nsp := `{"all": [{"is": {"loved": true}}]}`
+ pls := &model.Playlist{}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Public).To(BeTrue())
+ })
+
+ It("honors explicit public: false over server default", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultPlaylistPublicVisibility = true
+
+ nsp := `{"public": false, "all": [{"is": {"loved": true}}]}`
+ pls := &model.Playlist{}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Public).To(BeFalse())
+ })
+
+ It("returns a syntax error with line and column info", func() {
+ nsp := "{\n \"name\": \"Bad\",\n \"all\": [INVALID]\n}"
+ pls := &model.Playlist{}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("JSON syntax error in SmartPlaylist"))
+ Expect(err.Error()).To(MatchRegexp(`line \d+, column \d+`))
+ })
+
+ It("returns a parsing error for completely invalid JSON", func() {
+ nsp := `not json at all`
+ pls := &model.Playlist{}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("SmartPlaylist"))
+ })
+
+ It("gracefully handles non-string name field", func() {
+ nsp := `{"name": 123, "all": [{"is": {"loved": true}}]}`
+ pls := &model.Playlist{Name: "Original"}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ // Type assertion in UnmarshalJSON fails silently; name stays as original
+ Expect(pls.Name).To(Equal("Original"))
+ })
+
+ It("parses limitPercent from NSP", func() {
+ nsp := `{
+ "all": [{"is": {"loved": true}}],
+ "sort": "playCount",
+ "order": "desc",
+ "limitPercent": 25
+ }`
+ pls := &model.Playlist{}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Rules).ToNot(BeNil())
+ Expect(pls.Rules.LimitPercent).To(Equal(25))
+ Expect(pls.Rules.Limit).To(Equal(0))
+ })
+
+ It("parses criteria with multiple rules", func() {
+ nsp := `{
+ "all": [
+ {"is": {"loved": true}},
+ {"contains": {"title": "rock"}}
+ ],
+ "sort": "lastPlayed",
+ "order": "desc",
+ "limit": 100
+ }`
+ pls := &model.Playlist{}
+ err := s.parseNSP(ctx, pls, strings.NewReader(nsp))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Rules).ToNot(BeNil())
+ Expect(pls.Rules.Sort).To(Equal("lastPlayed"))
+ Expect(pls.Rules.Order).To(Equal("desc"))
+ Expect(pls.Rules.Limit).To(Equal(100))
+ })
+})
+
+var _ = Describe("getPositionFromOffset", func() {
+ It("returns correct position on first line", func() {
+ data := []byte("hello world")
+ line, col := getPositionFromOffset(data, 5)
+ Expect(line).To(Equal(1))
+ Expect(col).To(Equal(5))
+ })
+
+ It("returns correct position after newlines", func() {
+ data := []byte("line1\nline2\nline3")
+ // Offsets: l(0) i(1) n(2) e(3) 1(4) \n(5) l(6) i(7) n(8)
+ line, col := getPositionFromOffset(data, 8)
+ Expect(line).To(Equal(2))
+ Expect(col).To(Equal(3))
+ })
+
+ It("returns correct position at start of new line", func() {
+ data := []byte("line1\nline2")
+ // After \n at offset 5, col resets to 1; offset 6 is 'l' -> col=1
+ line, col := getPositionFromOffset(data, 6)
+ Expect(line).To(Equal(2))
+ Expect(col).To(Equal(1))
+ })
+
+ It("handles multiple newlines", func() {
+ data := []byte("a\nb\nc\nd")
+ // a(0) \n(1) b(2) \n(3) c(4) \n(5) d(6)
+ line, col := getPositionFromOffset(data, 6)
+ Expect(line).To(Equal(4))
+ Expect(col).To(Equal(1))
+ })
+})
+
+var _ = Describe("newSyncedPlaylist", func() {
+ var s *playlists
+
+ BeforeEach(func() {
+ s = &playlists{}
+ })
+
+ It("creates a synced playlist with correct attributes", func() {
+ tmpDir := GinkgoT().TempDir()
+ Expect(os.WriteFile(filepath.Join(tmpDir, "test.m3u"), []byte("content"), 0600)).To(Succeed())
+
+ pls, err := s.newSyncedPlaylist(tmpDir, "test.m3u")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("test"))
+ Expect(pls.Comment).To(Equal("Auto-imported from 'test.m3u'"))
+ Expect(pls.Public).To(BeFalse())
+ Expect(pls.Path).To(Equal(filepath.Join(tmpDir, "test.m3u")))
+ Expect(pls.Sync).To(BeTrue())
+ Expect(pls.UpdatedAt).ToNot(BeZero())
+ })
+
+ It("strips extension from filename to derive name", func() {
+ tmpDir := GinkgoT().TempDir()
+ Expect(os.WriteFile(filepath.Join(tmpDir, "My Favorites.nsp"), []byte("{}"), 0600)).To(Succeed())
+
+ pls, err := s.newSyncedPlaylist(tmpDir, "My Favorites.nsp")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.Name).To(Equal("My Favorites"))
+ })
+
+ It("returns error for non-existent file", func() {
+ tmpDir := GinkgoT().TempDir()
+ _, err := s.newSyncedPlaylist(tmpDir, "nonexistent.m3u")
+ Expect(err).To(HaveOccurred())
+ })
+})
diff --git a/core/playlists/playlists.go b/core/playlists/playlists.go
new file mode 100644
index 000000000..a0086cd2d
--- /dev/null
+++ b/core/playlists/playlists.go
@@ -0,0 +1,321 @@
+package playlists
+
+import (
+ "context"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/bmatcuk/doublestar/v4"
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+)
+
+type Playlists interface {
+ // Reads
+ GetAll(ctx context.Context, options ...model.QueryOptions) (model.Playlists, error)
+ Get(ctx context.Context, id string) (*model.Playlist, error)
+ GetWithTracks(ctx context.Context, id string) (*model.Playlist, error)
+ GetPlaylists(ctx context.Context, mediaFileId string) (model.Playlists, error)
+
+ // Mutations
+ Create(ctx context.Context, playlistId string, name string, ids []string) (string, error)
+ Delete(ctx context.Context, id string) error
+ Update(ctx context.Context, playlistID string, name *string, comment *string, public *bool, idsToAdd []string, idxToRemove []int) error
+
+ // Track management
+ AddTracks(ctx context.Context, playlistID string, ids []string) (int, error)
+ AddAlbums(ctx context.Context, playlistID string, albumIds []string) (int, error)
+ AddArtists(ctx context.Context, playlistID string, artistIds []string) (int, error)
+ AddDiscs(ctx context.Context, playlistID string, discs []model.DiscID) (int, error)
+ RemoveTracks(ctx context.Context, playlistID string, trackIds []string) error
+ ReorderTrack(ctx context.Context, playlistID string, pos int, newPos int) error
+
+ // Cover art
+ SetImage(ctx context.Context, playlistID string, reader io.Reader, ext string) error
+ RemoveImage(ctx context.Context, playlistID string) error
+
+ // Import
+ ImportFile(ctx context.Context, folder *model.Folder, filename string) (*model.Playlist, error)
+ ImportM3U(ctx context.Context, reader io.Reader) (*model.Playlist, error)
+
+ // REST adapters (follows Share/Library pattern)
+ NewRepository(ctx context.Context) rest.Repository
+ TracksRepository(ctx context.Context, playlistId string, refreshSmartPlaylist bool) rest.Repository
+}
+
+// ImageUploadService is a local interface satisfied by core.ImageUploadService.
+// Defined here to avoid an import cycle between core and core/playlists.
+type ImageUploadService interface {
+ SetImage(ctx context.Context, entityType string, entityID string, name string, oldPath string, reader io.Reader, ext string) (filename string, err error)
+ RemoveImage(ctx context.Context, path string) error
+}
+
+type playlists struct {
+ ds model.DataStore
+ imgUpload ImageUploadService
+}
+
+func NewPlaylists(ds model.DataStore, imgUpload ImageUploadService) Playlists {
+ return &playlists{ds: ds, imgUpload: imgUpload}
+}
+
+func InPath(folder model.Folder) bool {
+ if conf.Server.PlaylistsPath == "" {
+ return true
+ }
+ rel, _ := filepath.Rel(folder.LibraryPath, folder.AbsolutePath())
+ for path := range strings.SplitSeq(conf.Server.PlaylistsPath, string(filepath.ListSeparator)) {
+ if match, _ := doublestar.Match(path, rel); match {
+ return true
+ }
+ }
+ return false
+}
+
+// --- Read operations ---
+
+func (s *playlists) GetAll(ctx context.Context, options ...model.QueryOptions) (model.Playlists, error) {
+ return s.ds.Playlist(ctx).GetAll(options...)
+}
+
+func (s *playlists) Get(ctx context.Context, id string) (*model.Playlist, error) {
+ return s.ds.Playlist(ctx).Get(id)
+}
+
+func (s *playlists) GetWithTracks(ctx context.Context, id string) (*model.Playlist, error) {
+ return s.ds.Playlist(ctx).GetWithTracks(id, true, false)
+}
+
+func (s *playlists) GetPlaylists(ctx context.Context, mediaFileId string) (model.Playlists, error) {
+ return s.ds.Playlist(ctx).GetPlaylists(mediaFileId)
+}
+
+// --- Mutation operations ---
+
+// Create creates a new playlist (when name is provided) or replaces tracks on an existing
+// playlist (when playlistId is provided). This matches the Subsonic createPlaylist semantics.
+func (s *playlists) Create(ctx context.Context, playlistId string, name string, ids []string) (string, error) {
+ usr, _ := request.UserFrom(ctx)
+ err := s.ds.WithTxImmediate(func(tx model.DataStore) error {
+ var pls *model.Playlist
+ var err error
+
+ if playlistId != "" {
+ pls, err = tx.Playlist(ctx).Get(playlistId)
+ if err != nil {
+ return err
+ }
+ if pls.IsSmartPlaylist() {
+ return model.ErrNotAuthorized
+ }
+ if !usr.IsAdmin && pls.OwnerID != usr.ID {
+ return model.ErrNotAuthorized
+ }
+ } else {
+ pls = &model.Playlist{Name: name}
+ pls.OwnerID = usr.ID
+ }
+ pls.Tracks = nil
+ pls.AddMediaFilesByID(ids)
+
+ err = tx.Playlist(ctx).Put(pls)
+ playlistId = pls.ID
+ return err
+ })
+ return playlistId, err
+}
+
+func (s *playlists) Delete(ctx context.Context, id string) error {
+ pls, err := s.checkWritable(ctx, id)
+ if err != nil {
+ return err
+ }
+
+ // Clean up custom cover image file if one exists
+ if path := pls.UploadedImagePath(); path != "" {
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ log.Warn(ctx, "Failed to remove playlist image on delete", "path", path, err)
+ }
+ }
+
+ return s.ds.Playlist(ctx).Delete(id)
+}
+
+func (s *playlists) Update(ctx context.Context, playlistID string,
+ name *string, comment *string, public *bool,
+ idsToAdd []string, idxToRemove []int) error {
+ var pls *model.Playlist
+ var err error
+ hasTrackChanges := len(idsToAdd) > 0 || len(idxToRemove) > 0
+ if hasTrackChanges {
+ pls, err = s.checkTracksEditable(ctx, playlistID)
+ } else {
+ pls, err = s.checkWritable(ctx, playlistID)
+ }
+ if err != nil {
+ return err
+ }
+ return s.ds.WithTxImmediate(func(tx model.DataStore) error {
+ repo := tx.Playlist(ctx)
+
+ if len(idxToRemove) > 0 {
+ tracksRepo := repo.Tracks(playlistID, false)
+ // Convert 0-based indices to 1-based position IDs and delete them directly,
+ // avoiding the need to load all tracks into memory.
+ positions := make([]string, len(idxToRemove))
+ for i, idx := range idxToRemove {
+ positions[i] = strconv.Itoa(idx + 1)
+ }
+ if err := tracksRepo.Delete(positions...); err != nil {
+ return err
+ }
+ if len(idsToAdd) > 0 {
+ if _, err := tracksRepo.Add(idsToAdd); err != nil {
+ return err
+ }
+ }
+ return s.updateMetadata(ctx, tx, pls, name, comment, public)
+ }
+
+ if len(idsToAdd) > 0 {
+ if _, err := repo.Tracks(playlistID, false).Add(idsToAdd); err != nil {
+ return err
+ }
+ }
+ if name == nil && comment == nil && public == nil {
+ return nil
+ }
+ // Reuse the playlist from checkWritable (no tracks loaded, so Put only refreshes counters)
+ return s.updateMetadata(ctx, tx, pls, name, comment, public)
+ })
+}
+
+// --- Permission helpers ---
+
+// checkWritable fetches the playlist and verifies the current user can modify it.
+func (s *playlists) checkWritable(ctx context.Context, id string) (*model.Playlist, error) {
+ pls, err := s.ds.Playlist(ctx).Get(id)
+ if err != nil {
+ return nil, err
+ }
+ usr, _ := request.UserFrom(ctx)
+ if !usr.IsAdmin && pls.OwnerID != usr.ID {
+ return nil, model.ErrNotAuthorized
+ }
+ return pls, nil
+}
+
+// checkTracksEditable verifies the user can modify tracks (ownership + not smart playlist).
+func (s *playlists) checkTracksEditable(ctx context.Context, playlistID string) (*model.Playlist, error) {
+ pls, err := s.checkWritable(ctx, playlistID)
+ if err != nil {
+ return nil, err
+ }
+ if pls.IsSmartPlaylist() {
+ return nil, model.ErrNotAuthorized
+ }
+ return pls, nil
+}
+
+// updateMetadata applies optional metadata changes to a playlist and persists it.
+// Accepts a DataStore parameter so it can be used inside transactions.
+// The caller is responsible for permission checks.
+func (s *playlists) updateMetadata(ctx context.Context, ds model.DataStore, pls *model.Playlist, name *string, comment *string, public *bool) error {
+ if name != nil {
+ pls.Name = *name
+ }
+ if comment != nil {
+ pls.Comment = *comment
+ }
+ if public != nil {
+ pls.Public = *public
+ }
+ return ds.Playlist(ctx).Put(pls)
+}
+
+// --- Track management operations ---
+
+func (s *playlists) AddTracks(ctx context.Context, playlistID string, ids []string) (int, error) {
+ if _, err := s.checkTracksEditable(ctx, playlistID); err != nil {
+ return 0, err
+ }
+ return s.ds.Playlist(ctx).Tracks(playlistID, false).Add(ids)
+}
+
+func (s *playlists) AddAlbums(ctx context.Context, playlistID string, albumIds []string) (int, error) {
+ if _, err := s.checkTracksEditable(ctx, playlistID); err != nil {
+ return 0, err
+ }
+ return s.ds.Playlist(ctx).Tracks(playlistID, false).AddAlbums(albumIds)
+}
+
+func (s *playlists) AddArtists(ctx context.Context, playlistID string, artistIds []string) (int, error) {
+ if _, err := s.checkTracksEditable(ctx, playlistID); err != nil {
+ return 0, err
+ }
+ return s.ds.Playlist(ctx).Tracks(playlistID, false).AddArtists(artistIds)
+}
+
+func (s *playlists) AddDiscs(ctx context.Context, playlistID string, discs []model.DiscID) (int, error) {
+ if _, err := s.checkTracksEditable(ctx, playlistID); err != nil {
+ return 0, err
+ }
+ return s.ds.Playlist(ctx).Tracks(playlistID, false).AddDiscs(discs)
+}
+
+func (s *playlists) RemoveTracks(ctx context.Context, playlistID string, trackIds []string) error {
+ if _, err := s.checkTracksEditable(ctx, playlistID); err != nil {
+ return err
+ }
+ return s.ds.WithTx(func(tx model.DataStore) error {
+ return tx.Playlist(ctx).Tracks(playlistID, false).Delete(trackIds...)
+ })
+}
+
+func (s *playlists) ReorderTrack(ctx context.Context, playlistID string, pos int, newPos int) error {
+ if _, err := s.checkTracksEditable(ctx, playlistID); err != nil {
+ return err
+ }
+ return s.ds.WithTx(func(tx model.DataStore) error {
+ return tx.Playlist(ctx).Tracks(playlistID, false).Reorder(pos, newPos)
+ })
+}
+
+// --- Cover art operations ---
+
+func (s *playlists) SetImage(ctx context.Context, playlistID string, reader io.Reader, ext string) error {
+ pls, err := s.checkWritable(ctx, playlistID)
+ if err != nil {
+ return err
+ }
+
+ oldPath := pls.UploadedImagePath()
+ filename, err := s.imgUpload.SetImage(ctx, consts.EntityPlaylist, pls.ID, pls.Name, oldPath, reader, ext)
+ if err != nil {
+ return err
+ }
+
+ pls.UploadedImage = filename
+ return s.ds.Playlist(ctx).Put(pls)
+}
+
+func (s *playlists) RemoveImage(ctx context.Context, playlistID string) error {
+ pls, err := s.checkWritable(ctx, playlistID)
+ if err != nil {
+ return err
+ }
+
+ if err := s.imgUpload.RemoveImage(ctx, pls.UploadedImagePath()); err != nil {
+ return err
+ }
+
+ pls.UploadedImage = ""
+ return s.ds.Playlist(ctx).Put(pls)
+}
diff --git a/core/playlists/playlists_suite_test.go b/core/playlists/playlists_suite_test.go
new file mode 100644
index 000000000..b57248490
--- /dev/null
+++ b/core/playlists/playlists_suite_test.go
@@ -0,0 +1,17 @@
+package playlists_test
+
+import (
+ "testing"
+
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+func TestPlaylists(t *testing.T) {
+ tests.Init(t, false)
+ log.SetLevel(log.LevelFatal)
+ RegisterFailHandler(Fail)
+ RunSpecs(t, "Playlists Suite")
+}
diff --git a/core/playlists/playlists_test.go b/core/playlists/playlists_test.go
new file mode 100644
index 000000000..52d5c88d8
--- /dev/null
+++ b/core/playlists/playlists_test.go
@@ -0,0 +1,418 @@
+package playlists_test
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/core/playlists"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/criteria"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Playlists", func() {
+ var ds *tests.MockDataStore
+ var ps playlists.Playlists
+ var mockPlsRepo *tests.MockPlaylistRepo
+ ctx := context.Background()
+
+ BeforeEach(func() {
+ mockPlsRepo = tests.CreateMockPlaylistRepo()
+ ds = &tests.MockDataStore{
+ MockedPlaylist: mockPlsRepo,
+ MockedLibrary: &tests.MockLibraryRepo{},
+ }
+ ctx = request.WithUser(ctx, model.User{ID: "123"})
+ })
+
+ Describe("Delete", func() {
+ var mockTracks *tests.MockPlaylistTrackRepo
+
+ BeforeEach(func() {
+ mockTracks = &tests.MockPlaylistTrackRepo{AddCount: 3}
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"},
+ }
+ mockPlsRepo.TracksRepo = mockTracks
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("allows owner to delete their playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.Delete(ctx, "pls-1")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockPlsRepo.Deleted).To(ContainElement("pls-1"))
+ })
+
+ It("allows admin to delete any playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true})
+ err := ps.Delete(ctx, "pls-1")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockPlsRepo.Deleted).To(ContainElement("pls-1"))
+ })
+
+ It("denies non-owner, non-admin from deleting", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ err := ps.Delete(ctx, "pls-1")
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ Expect(mockPlsRepo.Deleted).To(BeEmpty())
+ })
+
+ It("returns error when playlist not found", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.Delete(ctx, "nonexistent")
+ Expect(err).To(Equal(model.ErrNotFound))
+ })
+ })
+
+ Describe("Create", func() {
+ BeforeEach(func() {
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "Existing", OwnerID: "user-1"},
+ "pls-2": {ID: "pls-2", Name: "Other's", OwnerID: "other-user"},
+ "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1",
+ Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}},
+ }
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("creates a new playlist with owner set from context", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ id, err := ps.Create(ctx, "", "New Playlist", []string{"song-1", "song-2"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(id).ToNot(BeEmpty())
+ Expect(mockPlsRepo.Last.Name).To(Equal("New Playlist"))
+ Expect(mockPlsRepo.Last.OwnerID).To(Equal("user-1"))
+ })
+
+ It("replaces tracks on existing playlist when owner matches", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ id, err := ps.Create(ctx, "pls-1", "", []string{"song-3"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(id).To(Equal("pls-1"))
+ Expect(mockPlsRepo.Last.Tracks).To(HaveLen(1))
+ })
+
+ It("allows admin to replace tracks on any playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true})
+ id, err := ps.Create(ctx, "pls-2", "", []string{"song-3"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(id).To(Equal("pls-2"))
+ })
+
+ It("denies non-owner, non-admin from replacing tracks on existing playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ _, err := ps.Create(ctx, "pls-2", "", []string{"song-3"})
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("returns error when existing playlistId not found", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ _, err := ps.Create(ctx, "nonexistent", "", []string{"song-1"})
+ Expect(err).To(Equal(model.ErrNotFound))
+ })
+
+ It("denies replacing tracks on a smart playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ _, err := ps.Create(ctx, "pls-smart", "", []string{"song-1"})
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+ })
+
+ Describe("Update", func() {
+ var mockTracks *tests.MockPlaylistTrackRepo
+
+ BeforeEach(func() {
+ mockTracks = &tests.MockPlaylistTrackRepo{AddCount: 2}
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"},
+ "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"},
+ "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1",
+ Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}},
+ }
+ mockPlsRepo.TracksRepo = mockTracks
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("allows owner to update their playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ newName := "Updated Name"
+ err := ps.Update(ctx, "pls-1", &newName, nil, nil, nil, nil)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("allows admin to update any playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true})
+ newName := "Updated Name"
+ err := ps.Update(ctx, "pls-other", &newName, nil, nil, nil, nil)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("denies non-owner, non-admin from updating", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ newName := "Updated Name"
+ err := ps.Update(ctx, "pls-1", &newName, nil, nil, nil, nil)
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("returns error when playlist not found", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ newName := "Updated Name"
+ err := ps.Update(ctx, "nonexistent", &newName, nil, nil, nil, nil)
+ Expect(err).To(Equal(model.ErrNotFound))
+ })
+
+ It("denies adding tracks to a smart playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.Update(ctx, "pls-smart", nil, nil, nil, []string{"song-1"}, nil)
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("denies removing tracks from a smart playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.Update(ctx, "pls-smart", nil, nil, nil, nil, []int{0})
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("allows metadata updates on a smart playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ newName := "Updated Smart"
+ err := ps.Update(ctx, "pls-smart", &newName, nil, nil, nil, nil)
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
+
+ Describe("AddTracks", func() {
+ var mockTracks *tests.MockPlaylistTrackRepo
+
+ BeforeEach(func() {
+ mockTracks = &tests.MockPlaylistTrackRepo{AddCount: 2}
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"},
+ "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1",
+ Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}},
+ "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"},
+ }
+ mockPlsRepo.TracksRepo = mockTracks
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("allows owner to add tracks", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ count, err := ps.AddTracks(ctx, "pls-1", []string{"song-1", "song-2"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(count).To(Equal(2))
+ Expect(mockTracks.AddedIds).To(ConsistOf("song-1", "song-2"))
+ })
+
+ It("allows admin to add tracks to any playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true})
+ count, err := ps.AddTracks(ctx, "pls-other", []string{"song-1"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(count).To(Equal(2))
+ })
+
+ It("denies non-owner, non-admin", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ _, err := ps.AddTracks(ctx, "pls-1", []string{"song-1"})
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("denies editing smart playlists", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ _, err := ps.AddTracks(ctx, "pls-smart", []string{"song-1"})
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("returns error when playlist not found", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ _, err := ps.AddTracks(ctx, "nonexistent", []string{"song-1"})
+ Expect(err).To(Equal(model.ErrNotFound))
+ })
+ })
+
+ Describe("RemoveTracks", func() {
+ var mockTracks *tests.MockPlaylistTrackRepo
+
+ BeforeEach(func() {
+ mockTracks = &tests.MockPlaylistTrackRepo{}
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"},
+ "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1",
+ Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}},
+ }
+ mockPlsRepo.TracksRepo = mockTracks
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("allows owner to remove tracks", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.RemoveTracks(ctx, "pls-1", []string{"track-1", "track-2"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockTracks.DeletedIds).To(ConsistOf("track-1", "track-2"))
+ })
+
+ It("denies on smart playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.RemoveTracks(ctx, "pls-smart", []string{"track-1"})
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("denies non-owner", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ err := ps.RemoveTracks(ctx, "pls-1", []string{"track-1"})
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+ })
+
+ Describe("ReorderTrack", func() {
+ var mockTracks *tests.MockPlaylistTrackRepo
+
+ BeforeEach(func() {
+ mockTracks = &tests.MockPlaylistTrackRepo{}
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"},
+ "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1",
+ Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}},
+ }
+ mockPlsRepo.TracksRepo = mockTracks
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("allows owner to reorder", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.ReorderTrack(ctx, "pls-1", 1, 3)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockTracks.Reordered).To(BeTrue())
+ })
+
+ It("denies on smart playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.ReorderTrack(ctx, "pls-smart", 1, 3)
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+ })
+
+ Describe("SetImage", func() {
+ var tmpDir string
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ tmpDir = GinkgoT().TempDir()
+ conf.Server.DataFolder = tmpDir
+
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"},
+ "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"},
+ }
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("saves image file and updates UploadedImage", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ reader := strings.NewReader("fake image data")
+ err := ps.SetImage(ctx, "pls-1", reader, ".jpg")
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(mockPlsRepo.Last.UploadedImage).To(Equal("pls-1_my_playlist.jpg"))
+ absPath := filepath.Join(tmpDir, "artwork", "playlist", "pls-1_my_playlist.jpg")
+ data, err := os.ReadFile(absPath)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(data)).To(Equal("fake image data"))
+ })
+
+ It("removes old image when replacing", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+
+ // Upload first image
+ err := ps.SetImage(ctx, "pls-1", strings.NewReader("first"), ".png")
+ Expect(err).ToNot(HaveOccurred())
+ oldPath := filepath.Join(tmpDir, "artwork", "playlist", "pls-1_my_playlist.png")
+ Expect(oldPath).To(BeAnExistingFile())
+
+ // Upload replacement image
+ err = ps.SetImage(ctx, "pls-1", strings.NewReader("second"), ".jpg")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(oldPath).ToNot(BeAnExistingFile())
+ newPath := filepath.Join(tmpDir, "artwork", "playlist", "pls-1_my_playlist.jpg")
+ Expect(newPath).To(BeAnExistingFile())
+ })
+
+ It("allows admin to set image on any playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true})
+ err := ps.SetImage(ctx, "pls-other", strings.NewReader("data"), ".jpg")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("denies non-owner", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ err := ps.SetImage(ctx, "pls-1", strings.NewReader("data"), ".jpg")
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("returns error when playlist not found", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.SetImage(ctx, "nonexistent", strings.NewReader("data"), ".jpg")
+ Expect(err).To(Equal(model.ErrNotFound))
+ })
+ })
+
+ Describe("RemoveImage", func() {
+ var tmpDir string
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ tmpDir = GinkgoT().TempDir()
+ conf.Server.DataFolder = tmpDir
+
+ // Create a real image file on disk
+ imgDir := filepath.Join(tmpDir, "artwork", "playlist")
+ Expect(os.MkdirAll(imgDir, 0755)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(imgDir, "pls-1.jpg"), []byte("img data"), 0600)).To(Succeed())
+
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", UploadedImage: "pls-1.jpg"},
+ "pls-empty": {ID: "pls-empty", Name: "No Cover", OwnerID: "user-1"},
+ "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"},
+ }
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ It("removes file and clears UploadedImage", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.RemoveImage(ctx, "pls-1")
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(mockPlsRepo.Last.UploadedImage).To(BeEmpty())
+ absPath := filepath.Join(tmpDir, "artwork", "playlist", "pls-1.jpg")
+ Expect(absPath).ToNot(BeAnExistingFile())
+ })
+
+ It("succeeds even if playlist has no image", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.RemoveImage(ctx, "pls-empty")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockPlsRepo.Last.UploadedImage).To(BeEmpty())
+ })
+
+ It("denies non-owner", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ err := ps.RemoveImage(ctx, "pls-1")
+ Expect(err).To(MatchError(model.ErrNotAuthorized))
+ })
+
+ It("returns error when playlist not found", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ err := ps.RemoveImage(ctx, "nonexistent")
+ Expect(err).To(Equal(model.ErrNotFound))
+ })
+ })
+})
diff --git a/core/playlists/rest_adapter.go b/core/playlists/rest_adapter.go
new file mode 100644
index 000000000..3fecda0d5
--- /dev/null
+++ b/core/playlists/rest_adapter.go
@@ -0,0 +1,103 @@
+package playlists
+
+import (
+ "context"
+ "errors"
+
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+)
+
+// --- REST adapter (follows Share/Library pattern) ---
+
+func (s *playlists) NewRepository(ctx context.Context) rest.Repository {
+ return &playlistRepositoryWrapper{
+ ctx: ctx,
+ PlaylistRepository: s.ds.Playlist(ctx),
+ service: s,
+ }
+}
+
+// playlistRepositoryWrapper wraps the playlist repository as a thin REST-to-service adapter.
+// It satisfies rest.Repository through the embedded PlaylistRepository (via ResourceRepository),
+// and rest.Persistable by delegating to service methods for all mutations.
+type playlistRepositoryWrapper struct {
+ model.PlaylistRepository
+ ctx context.Context
+ service *playlists
+}
+
+func (r *playlistRepositoryWrapper) Save(entity any) (string, error) {
+ return r.service.savePlaylist(r.ctx, entity.(*model.Playlist))
+}
+
+func (r *playlistRepositoryWrapper) Update(id string, entity any, cols ...string) error {
+ return r.service.updatePlaylistEntity(r.ctx, id, entity.(*model.Playlist), cols...)
+}
+
+func (r *playlistRepositoryWrapper) Delete(id string) error {
+ err := r.service.Delete(r.ctx, id)
+ switch {
+ case errors.Is(err, model.ErrNotFound):
+ return rest.ErrNotFound
+ case errors.Is(err, model.ErrNotAuthorized):
+ return rest.ErrPermissionDenied
+ default:
+ return err
+ }
+}
+
+func (s *playlists) TracksRepository(ctx context.Context, playlistId string, refreshSmartPlaylist bool) rest.Repository {
+ repo := s.ds.Playlist(ctx)
+ tracks := repo.Tracks(playlistId, refreshSmartPlaylist)
+ if tracks == nil {
+ return nil
+ }
+ return tracks.(rest.Repository)
+}
+
+// savePlaylist creates a new playlist, assigning the owner from context.
+// Only Name, Comment, Public, and Rules are user-settable via the REST API.
+func (s *playlists) savePlaylist(ctx context.Context, pls *model.Playlist) (string, error) {
+ usr, _ := request.UserFrom(ctx)
+ pls.OwnerID = usr.ID
+ pls.ID = "" // Force new creation
+ pls.Path = "" // Server-managed (M3U file path)
+ pls.Sync = false // Server-managed (M3U sync flag)
+ pls.UploadedImage = "" // Managed by image upload endpoint
+ pls.ExternalImageURL = "" // Managed by M3U import / plugins only
+ pls.EvaluatedAt = nil // Server-managed
+ err := s.ds.Playlist(ctx).Put(pls)
+ if err != nil {
+ return "", err
+ }
+ return pls.ID, nil
+}
+
+// updatePlaylistEntity updates playlist metadata with permission checks.
+// Used by the REST API wrapper.
+func (s *playlists) updatePlaylistEntity(ctx context.Context, id string, entity *model.Playlist, cols ...string) error {
+ current, err := s.checkWritable(ctx, id)
+ if err != nil {
+ switch {
+ case errors.Is(err, model.ErrNotFound):
+ return rest.ErrNotFound
+ case errors.Is(err, model.ErrNotAuthorized):
+ return rest.ErrPermissionDenied
+ default:
+ return err
+ }
+ }
+ usr, _ := request.UserFrom(ctx)
+ if !usr.IsAdmin && entity.OwnerID != "" && entity.OwnerID != current.OwnerID {
+ return rest.ErrPermissionDenied
+ }
+ // Apply ownership change (admin only)
+ if entity.OwnerID != "" {
+ current.OwnerID = entity.OwnerID
+ }
+ // Apply smart playlist rules update
+ current.Rules = entity.Rules
+ return s.updateMetadata(ctx, s.ds, current, &entity.Name, &entity.Comment, &entity.Public)
+}
diff --git a/core/playlists/rest_adapter_test.go b/core/playlists/rest_adapter_test.go
new file mode 100644
index 000000000..097bc6310
--- /dev/null
+++ b/core/playlists/rest_adapter_test.go
@@ -0,0 +1,171 @@
+package playlists_test
+
+import (
+ "context"
+ "time"
+
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/core/playlists"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/criteria"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("REST Adapter", func() {
+ var ds *tests.MockDataStore
+ var ps playlists.Playlists
+ var mockPlsRepo *tests.MockPlaylistRepo
+ ctx := context.Background()
+
+ BeforeEach(func() {
+ mockPlsRepo = tests.CreateMockPlaylistRepo()
+ ds = &tests.MockDataStore{
+ MockedPlaylist: mockPlsRepo,
+ MockedLibrary: &tests.MockLibraryRepo{},
+ }
+ ctx = request.WithUser(ctx, model.User{ID: "123"})
+ })
+
+ Describe("NewRepository", func() {
+ var repo rest.Persistable
+
+ BeforeEach(func() {
+ mockPlsRepo.Data = map[string]*model.Playlist{
+ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"},
+ }
+ ps = playlists.NewPlaylists(ds, core.NewImageUploadService())
+ })
+
+ Describe("Save", func() {
+ It("sets the owner from the context user", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ pls := &model.Playlist{Name: "New Playlist"}
+ id, err := repo.Save(pls)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(id).ToNot(BeEmpty())
+ Expect(pls.OwnerID).To(Equal("user-1"))
+ })
+
+ It("forces a new creation by clearing ID", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ pls := &model.Playlist{ID: "should-be-cleared", Name: "New"}
+ _, err := repo.Save(pls)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pls.ID).ToNot(Equal("should-be-cleared"))
+ })
+
+ It("clears server-managed fields to prevent injection via REST API", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ now := time.Now()
+ pls := &model.Playlist{
+ Name: "Legit Playlist",
+ Comment: "A comment",
+ Public: true,
+ Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}},
+ Path: "/some/path/playlist.m3u",
+ Sync: true,
+ UploadedImage: "injected-image-path",
+ ExternalImageURL: "http://evil.example.com/ssrf",
+ EvaluatedAt: &now,
+ }
+ _, err := repo.Save(pls)
+ Expect(err).ToNot(HaveOccurred())
+
+ saved := mockPlsRepo.Last
+ // User-settable fields are preserved
+ Expect(saved.Name).To(Equal("Legit Playlist"))
+ Expect(saved.Comment).To(Equal("A comment"))
+ Expect(saved.Public).To(BeTrue())
+ Expect(saved.Rules).ToNot(BeNil())
+ // Server-managed fields are cleared
+ Expect(saved.Path).To(BeEmpty())
+ Expect(saved.Sync).To(BeFalse())
+ Expect(saved.UploadedImage).To(BeEmpty())
+ Expect(saved.ExternalImageURL).To(BeEmpty())
+ Expect(saved.EvaluatedAt).To(BeNil())
+ })
+ })
+
+ Describe("Update", func() {
+ It("allows owner to update their playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ pls := &model.Playlist{Name: "Updated"}
+ err := repo.Update("pls-1", pls)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("allows admin to update any playlist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ pls := &model.Playlist{Name: "Updated"}
+ err := repo.Update("pls-1", pls)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("denies non-owner, non-admin", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ pls := &model.Playlist{Name: "Updated"}
+ err := repo.Update("pls-1", pls)
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+
+ It("denies regular user from changing ownership", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ pls := &model.Playlist{Name: "Updated", OwnerID: "other-user"}
+ err := repo.Update("pls-1", pls)
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+
+ It("updates smart playlist rules", func() {
+ mockPlsRepo.Data["smart-1"] = &model.Playlist{
+ ID: "smart-1",
+ Name: "Smart Playlist",
+ OwnerID: "user-1",
+ Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "old"}},
+ }
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ newRules := &criteria.Criteria{Expression: criteria.Contains{"title": "new"}}
+ pls := &model.Playlist{Name: "Smart Playlist", Rules: newRules}
+ err := repo.Update("smart-1", pls)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockPlsRepo.Last.Rules).To(Equal(newRules))
+ })
+
+ It("returns rest.ErrNotFound when playlist doesn't exist", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ pls := &model.Playlist{Name: "Updated"}
+ err := repo.Update("nonexistent", pls)
+ Expect(err).To(Equal(rest.ErrNotFound))
+ })
+ })
+
+ Describe("Delete", func() {
+ It("delegates to service Delete with permission checks", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ err := repo.Delete("pls-1")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mockPlsRepo.Deleted).To(ContainElement("pls-1"))
+ })
+
+ It("denies non-owner", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false})
+ repo = ps.NewRepository(ctx).(rest.Persistable)
+ err := repo.Delete("pls-1")
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+ })
+})
diff --git a/core/playlists_test.go b/core/playlists_test.go
deleted file mode 100644
index 399210ac8..000000000
--- a/core/playlists_test.go
+++ /dev/null
@@ -1,332 +0,0 @@
-package core
-
-import (
- "context"
- "os"
- "strconv"
- "strings"
- "time"
-
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/conf/configtest"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/model/criteria"
- "github.com/navidrome/navidrome/model/request"
- "github.com/navidrome/navidrome/tests"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
- "golang.org/x/text/unicode/norm"
-)
-
-var _ = Describe("Playlists", func() {
- var ds *tests.MockDataStore
- var ps Playlists
- var mockPlsRepo mockedPlaylistRepo
- var mockLibRepo *tests.MockLibraryRepo
- ctx := context.Background()
-
- BeforeEach(func() {
- mockPlsRepo = mockedPlaylistRepo{}
- mockLibRepo = &tests.MockLibraryRepo{}
- ds = &tests.MockDataStore{
- MockedPlaylist: &mockPlsRepo,
- MockedLibrary: mockLibRepo,
- }
- ctx = request.WithUser(ctx, model.User{ID: "123"})
- // Path should be libPath, but we want to match the root folder referenced in the m3u, which is `/`
- mockLibRepo.SetData([]model.Library{{ID: 1, Path: "/"}})
- })
-
- Describe("ImportFile", func() {
- var folder *model.Folder
- BeforeEach(func() {
- ps = NewPlaylists(ds)
- ds.MockedMediaFile = &mockedMediaFileRepo{}
- libPath, _ := os.Getwd()
- folder = &model.Folder{
- ID: "1",
- LibraryID: 1,
- LibraryPath: libPath,
- Path: "tests/fixtures",
- Name: "playlists",
- }
- })
-
- Describe("M3U", func() {
- It("parses well-formed playlists", func() {
- pls, err := ps.ImportFile(ctx, folder, "pls1.m3u")
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.OwnerID).To(Equal("123"))
- Expect(pls.Tracks).To(HaveLen(2))
- Expect(pls.Tracks[0].Path).To(Equal("tests/fixtures/playlists/test.mp3"))
- Expect(pls.Tracks[1].Path).To(Equal("tests/fixtures/playlists/test.ogg"))
- Expect(mockPlsRepo.last).To(Equal(pls))
- })
-
- It("parses playlists using LF ending", func() {
- pls, err := ps.ImportFile(ctx, folder, "lf-ended.m3u")
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.Tracks).To(HaveLen(2))
- })
-
- It("parses playlists using CR ending (old Mac format)", func() {
- pls, err := ps.ImportFile(ctx, folder, "cr-ended.m3u")
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.Tracks).To(HaveLen(2))
- })
- })
-
- Describe("NSP", func() {
- It("parses well-formed playlists", func() {
- pls, err := ps.ImportFile(ctx, folder, "recently_played.nsp")
- Expect(err).ToNot(HaveOccurred())
- Expect(mockPlsRepo.last).To(Equal(pls))
- Expect(pls.OwnerID).To(Equal("123"))
- Expect(pls.Name).To(Equal("Recently Played"))
- Expect(pls.Comment).To(Equal("Recently played tracks"))
- Expect(pls.Rules.Sort).To(Equal("lastPlayed"))
- Expect(pls.Rules.Order).To(Equal("desc"))
- Expect(pls.Rules.Limit).To(Equal(100))
- Expect(pls.Rules.Expression).To(BeAssignableToTypeOf(criteria.All{}))
- })
- It("returns an error if the playlist is not well-formed", func() {
- _, err := ps.ImportFile(ctx, folder, "invalid_json.nsp")
- Expect(err.Error()).To(ContainSubstring("line 19, column 1: invalid character '\\n'"))
- })
- })
- })
-
- Describe("ImportM3U", func() {
- var repo *mockedMediaFileFromListRepo
- BeforeEach(func() {
- repo = &mockedMediaFileFromListRepo{}
- ds.MockedMediaFile = repo
- ps = NewPlaylists(ds)
- mockLibRepo.SetData([]model.Library{{ID: 1, Path: "/music"}, {ID: 2, Path: "/new"}})
- ctx = request.WithUser(ctx, model.User{ID: "123"})
- })
-
- It("parses well-formed playlists", func() {
- repo.data = []string{
- "tests/test.mp3",
- "tests/test.ogg",
- "tests/01 Invisible (RED) Edit Version.mp3",
- "downloads/newfile.flac",
- }
- m3u := strings.Join([]string{
- "#PLAYLIST:playlist 1",
- "/music/tests/test.mp3",
- "/music/tests/test.ogg",
- "/new/downloads/newfile.flac",
- "file:///music/tests/01%20Invisible%20(RED)%20Edit%20Version.mp3",
- }, "\n")
- f := strings.NewReader(m3u)
-
- pls, err := ps.ImportM3U(ctx, f)
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.OwnerID).To(Equal("123"))
- Expect(pls.Name).To(Equal("playlist 1"))
- Expect(pls.Sync).To(BeFalse())
- Expect(pls.Tracks).To(HaveLen(4))
- Expect(pls.Tracks[0].Path).To(Equal("tests/test.mp3"))
- Expect(pls.Tracks[1].Path).To(Equal("tests/test.ogg"))
- Expect(pls.Tracks[2].Path).To(Equal("downloads/newfile.flac"))
- Expect(pls.Tracks[3].Path).To(Equal("tests/01 Invisible (RED) Edit Version.mp3"))
- Expect(mockPlsRepo.last).To(Equal(pls))
- })
-
- It("sets the playlist name as a timestamp if the #PLAYLIST directive is not present", func() {
- repo.data = []string{
- "tests/test.mp3",
- "tests/test.ogg",
- "/tests/01 Invisible (RED) Edit Version.mp3",
- }
- m3u := strings.Join([]string{
- "/music/tests/test.mp3",
- "/music/tests/test.ogg",
- }, "\n")
- f := strings.NewReader(m3u)
- pls, err := ps.ImportM3U(ctx, f)
- Expect(err).ToNot(HaveOccurred())
- _, err = time.Parse(time.RFC3339, pls.Name)
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.Tracks).To(HaveLen(2))
- })
-
- It("returns only tracks that exist in the database and in the same other as the m3u", func() {
- repo.data = []string{
- "album1/test1.mp3",
- "album2/test2.mp3",
- "album3/test3.mp3",
- }
- m3u := strings.Join([]string{
- "/music/album3/test3.mp3",
- "/music/album1/test1.mp3",
- "/music/album4/test4.mp3",
- "/music/album2/test2.mp3",
- }, "\n")
- f := strings.NewReader(m3u)
- pls, err := ps.ImportM3U(ctx, f)
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.Tracks).To(HaveLen(3))
- Expect(pls.Tracks[0].Path).To(Equal("album3/test3.mp3"))
- Expect(pls.Tracks[1].Path).To(Equal("album1/test1.mp3"))
- Expect(pls.Tracks[2].Path).To(Equal("album2/test2.mp3"))
- })
-
- It("is case-insensitive when comparing paths", func() {
- repo.data = []string{
- "abc/tEsT1.Mp3",
- }
- m3u := strings.Join([]string{
- "/music/ABC/TeSt1.mP3",
- }, "\n")
- f := strings.NewReader(m3u)
- pls, err := ps.ImportM3U(ctx, f)
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.Tracks).To(HaveLen(1))
- Expect(pls.Tracks[0].Path).To(Equal("abc/tEsT1.Mp3"))
- })
-
- It("handles Unicode normalization when comparing paths", func() {
- // Test case for Apple Music playlists that use NFC encoding vs macOS filesystem NFD
- // The character "è" can be represented as NFC (single codepoint) or NFD (e + combining accent)
-
- const pathWithAccents = "artist/Michèle Desrosiers/album/Noël.m4a"
-
- // Simulate a database entry with NFD encoding (as stored by macOS filesystem)
- nfdPath := norm.NFD.String(pathWithAccents)
- repo.data = []string{nfdPath}
-
- // Simulate an Apple Music M3U playlist entry with NFC encoding
- nfcPath := norm.NFC.String("/music/" + pathWithAccents)
- m3u := strings.Join([]string{
- nfcPath,
- }, "\n")
- f := strings.NewReader(m3u)
-
- pls, err := ps.ImportM3U(ctx, f)
- Expect(err).ToNot(HaveOccurred())
- Expect(pls.Tracks).To(HaveLen(1), "Should find the track despite Unicode normalization differences")
- Expect(pls.Tracks[0].Path).To(Equal(nfdPath))
- })
- })
-
- Describe("normalizePathForComparison", func() {
- It("normalizes Unicode characters to NFC form and converts to lowercase", func() {
- // Test with NFD (decomposed) input - as would come from macOS filesystem
- nfdPath := norm.NFD.String("Michèle") // Explicitly convert to NFD form
- normalized := normalizePathForComparison(nfdPath)
- Expect(normalized).To(Equal("michèle"))
-
- // Test with NFC (composed) input - as would come from Apple Music M3U
- nfcPath := "Michèle" // This might be in NFC form
- normalizedNfc := normalizePathForComparison(nfcPath)
-
- // Ensure the two paths are not equal in their original forms
- Expect(nfdPath).ToNot(Equal(nfcPath))
-
- // Both should normalize to the same result
- Expect(normalized).To(Equal(normalizedNfc))
- })
-
- It("handles paths with mixed case and Unicode characters", func() {
- path := "Artist/Noël Coward/Album/Song.mp3"
- normalized := normalizePathForComparison(path)
- Expect(normalized).To(Equal("artist/noël coward/album/song.mp3"))
- })
- })
-
- Describe("InPlaylistsPath", func() {
- var folder model.Folder
-
- BeforeEach(func() {
- DeferCleanup(configtest.SetupConfig())
- folder = model.Folder{
- LibraryPath: "/music",
- Path: "playlists/abc",
- Name: "folder1",
- }
- })
-
- It("returns true if PlaylistsPath is empty", func() {
- conf.Server.PlaylistsPath = ""
- Expect(InPlaylistsPath(folder)).To(BeTrue())
- })
-
- It("returns true if PlaylistsPath is any (**/**)", func() {
- conf.Server.PlaylistsPath = "**/**"
- Expect(InPlaylistsPath(folder)).To(BeTrue())
- })
-
- It("returns true if folder is in PlaylistsPath", func() {
- conf.Server.PlaylistsPath = "other/**:playlists/**"
- Expect(InPlaylistsPath(folder)).To(BeTrue())
- })
-
- It("returns false if folder is not in PlaylistsPath", func() {
- conf.Server.PlaylistsPath = "other"
- Expect(InPlaylistsPath(folder)).To(BeFalse())
- })
-
- It("returns true if for a playlist in root of MusicFolder if PlaylistsPath is '.'", func() {
- conf.Server.PlaylistsPath = "."
- Expect(InPlaylistsPath(folder)).To(BeFalse())
-
- folder2 := model.Folder{
- LibraryPath: "/music",
- Path: "",
- Name: ".",
- }
-
- Expect(InPlaylistsPath(folder2)).To(BeTrue())
- })
- })
-})
-
-// mockedMediaFileRepo's FindByPaths method returns a list of MediaFiles with the same paths as the input
-type mockedMediaFileRepo struct {
- model.MediaFileRepository
-}
-
-func (r *mockedMediaFileRepo) FindByPaths(paths []string) (model.MediaFiles, error) {
- var mfs model.MediaFiles
- for idx, path := range paths {
- mfs = append(mfs, model.MediaFile{
- ID: strconv.Itoa(idx),
- Path: path,
- })
- }
- return mfs, nil
-}
-
-// mockedMediaFileFromListRepo's FindByPaths method returns a list of MediaFiles based on the data field
-type mockedMediaFileFromListRepo struct {
- model.MediaFileRepository
- data []string
-}
-
-func (r *mockedMediaFileFromListRepo) FindByPaths([]string) (model.MediaFiles, error) {
- var mfs model.MediaFiles
- for idx, path := range r.data {
- mfs = append(mfs, model.MediaFile{
- ID: strconv.Itoa(idx),
- Path: path,
- })
- }
- return mfs, nil
-}
-
-type mockedPlaylistRepo struct {
- last *model.Playlist
- model.PlaylistRepository
-}
-
-func (r *mockedPlaylistRepo) FindByPath(string) (*model.Playlist, error) {
- return nil, model.ErrNotFound
-}
-
-func (r *mockedPlaylistRepo) Put(pls *model.Playlist) error {
- r.last = pls
- return nil
-}
diff --git a/core/publicurl/publicurl.go b/core/publicurl/publicurl.go
new file mode 100644
index 000000000..c1b8e01c4
--- /dev/null
+++ b/core/publicurl/publicurl.go
@@ -0,0 +1,81 @@
+package publicurl
+
+import (
+ "cmp"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/core/auth"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+)
+
+// ImageURL generates a public URL for artwork images.
+// It creates a signed token for the artwork ID and builds a complete public URL.
+func ImageURL(req *http.Request, artID model.ArtworkID, size int) string {
+ token, _ := auth.CreatePublicToken(auth.Claims{ID: artID.String()})
+ uri := path.Join(consts.URLPathPublicImages, token)
+ params := url.Values{}
+ if size > 0 {
+ params.Add("size", strconv.Itoa(size))
+ }
+ return PublicURL(req, uri, params)
+}
+
+// PublicURL builds a full URL for public-facing resources.
+// It uses ShareURL from config if available, otherwise falls back to extracting
+// the scheme and host from the provided http.Request.
+// If req is nil and ShareURL is not set, it defaults to http://localhost.
+func PublicURL(req *http.Request, u string, params url.Values) string {
+ if conf.Server.ShareURL == "" {
+ return AbsoluteURL(req, u, params)
+ }
+ shareUrl, err := url.Parse(conf.Server.ShareURL)
+ if err != nil {
+ return AbsoluteURL(req, u, params)
+ }
+ buildUrl, err := url.Parse(u)
+ if err != nil {
+ return AbsoluteURL(req, u, params)
+ }
+ buildUrl.Scheme = shareUrl.Scheme
+ buildUrl.Host = shareUrl.Host
+ if len(params) > 0 {
+ buildUrl.RawQuery = params.Encode()
+ }
+ return buildUrl.String()
+}
+
+// AbsoluteURL builds an absolute URL from a relative path.
+// It uses BaseHost/BaseScheme from config if available, otherwise extracts
+// the scheme and host from the http.Request.
+// If req is nil and BaseHost is not set, it defaults to http://localhost.
+func AbsoluteURL(req *http.Request, u string, params url.Values) string {
+ buildUrl, err := url.Parse(u)
+ if err != nil {
+ log.Error(req.Context(), "Failed to parse URL path", "url", u, err)
+ return ""
+ }
+ if strings.HasPrefix(u, "/") {
+ buildUrl.Path = path.Join(conf.Server.BasePath, buildUrl.Path)
+ if conf.Server.BaseHost != "" {
+ buildUrl.Scheme = cmp.Or(conf.Server.BaseScheme, "http")
+ buildUrl.Host = conf.Server.BaseHost
+ } else if req != nil {
+ buildUrl.Scheme = req.URL.Scheme
+ buildUrl.Host = req.Host
+ } else {
+ buildUrl.Scheme = "http"
+ buildUrl.Host = "localhost"
+ }
+ }
+ if len(params) > 0 {
+ buildUrl.RawQuery = params.Encode()
+ }
+ return buildUrl.String()
+}
diff --git a/core/publicurl/publicurl_test.go b/core/publicurl/publicurl_test.go
new file mode 100644
index 000000000..18f8f8129
--- /dev/null
+++ b/core/publicurl/publicurl_test.go
@@ -0,0 +1,174 @@
+package publicurl_test
+
+import (
+ "net/http"
+ "net/url"
+ "testing"
+
+ "github.com/go-chi/jwtauth/v5"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/core/auth"
+ "github.com/navidrome/navidrome/core/publicurl"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+func TestPublicURL(t *testing.T) {
+ tests.Init(t, false)
+ log.SetLevel(log.LevelFatal)
+ RegisterFailHandler(Fail)
+ RunSpecs(t, "Public URL Suite")
+}
+
+var _ = Describe("Public URL Utilities", func() {
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ })
+
+ Describe("PublicURL", func() {
+ When("ShareURL is set", func() {
+ BeforeEach(func() {
+ conf.Server.ShareURL = "https://share.example.com"
+ })
+
+ It("uses ShareURL as the base", func() {
+ r, _ := http.NewRequest("GET", "http://localhost/test", nil)
+ result := publicurl.PublicURL(r, "/path/to/resource", nil)
+ Expect(result).To(Equal("https://share.example.com/path/to/resource"))
+ })
+
+ It("includes query parameters", func() {
+ r, _ := http.NewRequest("GET", "http://localhost/test", nil)
+ params := url.Values{"size": []string{"300"}, "format": []string{"png"}}
+ result := publicurl.PublicURL(r, "/image/123", params)
+ Expect(result).To(ContainSubstring("https://share.example.com/image/123"))
+ Expect(result).To(ContainSubstring("size=300"))
+ Expect(result).To(ContainSubstring("format=png"))
+ })
+
+ It("works without a request", func() {
+ result := publicurl.PublicURL(nil, "/path/to/resource", nil)
+ Expect(result).To(Equal("https://share.example.com/path/to/resource"))
+ })
+ })
+
+ When("ShareURL is not set", func() {
+ BeforeEach(func() {
+ conf.Server.ShareURL = ""
+ })
+
+ It("falls back to AbsoluteURL with request", func() {
+ r, _ := http.NewRequest("GET", "https://myserver.com/test", nil)
+ r.Host = "myserver.com"
+ result := publicurl.PublicURL(r, "/path/to/resource", nil)
+ Expect(result).To(Equal("https://myserver.com/path/to/resource"))
+ })
+
+ It("falls back to localhost without request", func() {
+ result := publicurl.PublicURL(nil, "/path/to/resource", nil)
+ Expect(result).To(Equal("http://localhost/path/to/resource"))
+ })
+ })
+ })
+
+ Describe("AbsoluteURL", func() {
+ When("BaseHost is set", func() {
+ BeforeEach(func() {
+ conf.Server.BaseHost = "configured.example.com"
+ conf.Server.BaseScheme = "https"
+ conf.Server.BasePath = ""
+ })
+
+ It("uses BaseHost and BaseScheme", func() {
+ r, _ := http.NewRequest("GET", "http://localhost/test", nil)
+ result := publicurl.AbsoluteURL(r, "/path/to/resource", nil)
+ Expect(result).To(Equal("https://configured.example.com/path/to/resource"))
+ })
+
+ It("defaults to http scheme if BaseScheme is empty", func() {
+ conf.Server.BaseScheme = ""
+ r, _ := http.NewRequest("GET", "http://localhost/test", nil)
+ result := publicurl.AbsoluteURL(r, "/path/to/resource", nil)
+ Expect(result).To(Equal("http://configured.example.com/path/to/resource"))
+ })
+ })
+
+ When("BaseHost is not set", func() {
+ BeforeEach(func() {
+ conf.Server.BaseHost = ""
+ conf.Server.BasePath = ""
+ })
+
+ It("extracts host from request", func() {
+ r, _ := http.NewRequest("GET", "https://request.example.com/test", nil)
+ r.Host = "request.example.com"
+ result := publicurl.AbsoluteURL(r, "/path/to/resource", nil)
+ Expect(result).To(Equal("https://request.example.com/path/to/resource"))
+ })
+
+ It("falls back to localhost without request", func() {
+ result := publicurl.AbsoluteURL(nil, "/path/to/resource", nil)
+ Expect(result).To(Equal("http://localhost/path/to/resource"))
+ })
+ })
+
+ When("BasePath is set", func() {
+ BeforeEach(func() {
+ conf.Server.BasePath = "/navidrome"
+ conf.Server.BaseHost = "example.com"
+ conf.Server.BaseScheme = "https"
+ })
+
+ It("prepends BasePath to the URL", func() {
+ r, _ := http.NewRequest("GET", "http://localhost/test", nil)
+ result := publicurl.AbsoluteURL(r, "/path/to/resource", nil)
+ Expect(result).To(Equal("https://example.com/navidrome/path/to/resource"))
+ })
+ })
+
+ It("passes through absolute URLs unchanged", func() {
+ r, _ := http.NewRequest("GET", "http://localhost/test", nil)
+ result := publicurl.AbsoluteURL(r, "https://other.example.com/path", nil)
+ Expect(result).To(Equal("https://other.example.com/path"))
+ })
+
+ It("includes query parameters", func() {
+ conf.Server.BaseHost = "example.com"
+ conf.Server.BaseScheme = "https"
+ r, _ := http.NewRequest("GET", "http://localhost/test", nil)
+ params := url.Values{"key": []string{"value"}}
+ result := publicurl.AbsoluteURL(r, "/path", params)
+ Expect(result).To(Equal("https://example.com/path?key=value"))
+ })
+ })
+
+ Describe("ImageURL", func() {
+ BeforeEach(func() {
+ conf.Server.ShareURL = "https://share.example.com"
+ // Initialize JWT auth for token generation
+ auth.TokenAuth = jwtauth.New("HS256", []byte("test secret"), nil)
+ })
+
+ It("generates a URL with the artwork token", func() {
+ artID := model.NewArtworkID(model.KindAlbumArtwork, "album-123", nil)
+ result := publicurl.ImageURL(nil, artID, 0)
+ Expect(result).To(HavePrefix("https://share.example.com/share/img/"))
+ })
+
+ It("includes size parameter when provided", func() {
+ artID := model.NewArtworkID(model.KindArtistArtwork, "artist-1", nil)
+ result := publicurl.ImageURL(nil, artID, 300)
+ Expect(result).To(ContainSubstring("size=300"))
+ })
+
+ It("omits size parameter when zero", func() {
+ artID := model.NewArtworkID(model.KindMediaFileArtwork, "track-1", nil)
+ result := publicurl.ImageURL(nil, artID, 0)
+ Expect(result).ToNot(ContainSubstring("size="))
+ })
+ })
+})
diff --git a/core/scrobbler/buffered_scrobbler.go b/core/scrobbler/buffered_scrobbler.go
index 4f64a3c2b..be36e1f24 100644
--- a/core/scrobbler/buffered_scrobbler.go
+++ b/core/scrobbler/buffered_scrobbler.go
@@ -9,11 +9,27 @@ import (
"github.com/navidrome/navidrome/model"
)
+// Loader is a function that loads a scrobbler by name.
+// It returns the scrobbler and true if found, or nil and false if not available.
+// This allows the buffered scrobbler to always get the current plugin instance.
+type Loader func() (Scrobbler, bool)
+
+// newBufferedScrobbler creates a buffered scrobbler that wraps a static scrobbler instance.
+// Use this for builtin scrobblers that don't change.
func newBufferedScrobbler(ds model.DataStore, s Scrobbler, service string) *bufferedScrobbler {
+ return newBufferedScrobblerWithLoader(ds, service, func() (Scrobbler, bool) {
+ return s, true
+ })
+}
+
+// newBufferedScrobblerWithLoader creates a buffered scrobbler that dynamically loads
+// the underlying scrobbler on each call. Use this for plugin scrobblers that may be
+// reloaded (e.g., after configuration changes).
+func newBufferedScrobblerWithLoader(ds model.DataStore, service string, loader Loader) *bufferedScrobbler {
ctx, cancel := context.WithCancel(context.Background())
b := &bufferedScrobbler{
ds: ds,
- wrapped: s,
+ loader: loader,
service: service,
wakeSignal: make(chan struct{}, 1),
ctx: ctx,
@@ -25,7 +41,7 @@ func newBufferedScrobbler(ds model.DataStore, s Scrobbler, service string) *buff
type bufferedScrobbler struct {
ds model.DataStore
- wrapped Scrobbler
+ loader Loader
service string
wakeSignal chan struct{}
ctx context.Context
@@ -39,11 +55,19 @@ func (b *bufferedScrobbler) Stop() {
}
func (b *bufferedScrobbler) IsAuthorized(ctx context.Context, userId string) bool {
- return b.wrapped.IsAuthorized(ctx, userId)
+ s, ok := b.loader()
+ if !ok {
+ return false
+ }
+ return s.IsAuthorized(ctx, userId)
}
func (b *bufferedScrobbler) NowPlaying(ctx context.Context, userId string, track *model.MediaFile, position int) error {
- return b.wrapped.NowPlaying(ctx, userId, track, position)
+ s, ok := b.loader()
+ if !ok {
+ return errors.New("scrobbler not available")
+ }
+ return s.NowPlaying(ctx, userId, track, position)
}
func (b *bufferedScrobbler) Scrobble(ctx context.Context, userId string, s Scrobble) error {
@@ -107,8 +131,13 @@ func (b *bufferedScrobbler) processUserQueue(ctx context.Context, userId string)
if entry == nil {
return true
}
+ s, ok := b.loader()
+ if !ok {
+ log.Warn(ctx, "Scrobbler not available, will retry later", "scrobbler", b.service)
+ return false
+ }
log.Debug(ctx, "Sending scrobble", "scrobbler", b.service, "track", entry.Title, "artist", entry.Artist)
- err = b.wrapped.Scrobble(ctx, entry.UserID, Scrobble{
+ err = s.Scrobble(ctx, entry.UserID, Scrobble{
MediaFile: entry.MediaFile,
TimeStamp: entry.PlayTime,
})
diff --git a/core/scrobbler/buffered_scrobbler_test.go b/core/scrobbler/buffered_scrobbler_test.go
index c1440046d..9fbca6f71 100644
--- a/core/scrobbler/buffered_scrobbler_test.go
+++ b/core/scrobbler/buffered_scrobbler_test.go
@@ -38,9 +38,9 @@ var _ = Describe("BufferedScrobbler", func() {
It("forwards NowPlaying calls", func() {
track := &model.MediaFile{ID: "123", Title: "Test Track"}
Expect(bs.NowPlaying(ctx, "user1", track, 0)).To(Succeed())
- Expect(scr.NowPlayingCalled).To(BeTrue())
- Expect(scr.UserID).To(Equal("user1"))
- Expect(scr.Track).To(Equal(track))
+ Expect(scr.GetNowPlayingCalled()).To(BeTrue())
+ Expect(scr.GetUserID()).To(Equal("user1"))
+ Expect(scr.GetTrack()).To(Equal(track))
})
It("enqueues scrobbles to buffer", func() {
@@ -51,9 +51,10 @@ var _ = Describe("BufferedScrobbler", func() {
Expect(scr.ScrobbleCalled.Load()).To(BeFalse())
Expect(bs.Scrobble(ctx, "user1", scrobble)).To(Succeed())
- Expect(buffer.Length()).To(Equal(int64(1)))
- // Wait for the scrobble to be sent
+ // Wait for the background goroutine to process the scrobble.
+ // We don't check buffer.Length() here because the background goroutine
+ // may dequeue the entry before we can observe it.
Eventually(scr.ScrobbleCalled.Load).Should(BeTrue())
lastScrobble := scr.LastScrobble.Load()
diff --git a/core/scrobbler/play_tracker.go b/core/scrobbler/play_tracker.go
index 3b71a2100..d1338ca39 100644
--- a/core/scrobbler/play_tracker.go
+++ b/core/scrobbler/play_tracker.go
@@ -31,6 +31,13 @@ type Submission struct {
Timestamp time.Time
}
+type nowPlayingEntry struct {
+ ctx context.Context
+ userId string
+ track *model.MediaFile
+ position int
+}
+
type PlayTracker interface {
NowPlaying(ctx context.Context, playerId string, playerName string, trackId string, position int) error
GetNowPlaying(ctx context.Context) ([]NowPlayingInfo, error)
@@ -52,6 +59,11 @@ type playTracker struct {
pluginScrobblers map[string]Scrobbler
pluginLoader PluginLoader
mu sync.RWMutex
+ npQueue map[string]nowPlayingEntry
+ npMu sync.Mutex
+ npSignal chan struct{}
+ shutdown chan struct{}
+ workerDone chan struct{}
}
func GetPlayTracker(ds model.DataStore, broker events.Broker, pluginManager PluginLoader) PlayTracker {
@@ -71,6 +83,10 @@ func newPlayTracker(ds model.DataStore, broker events.Broker, pluginManager Plug
builtinScrobblers: make(map[string]Scrobbler),
pluginScrobblers: make(map[string]Scrobbler),
pluginLoader: pluginManager,
+ npQueue: make(map[string]nowPlayingEntry),
+ npSignal: make(chan struct{}, 1),
+ shutdown: make(chan struct{}),
+ workerDone: make(chan struct{}),
}
if conf.Server.EnableNowPlaying {
m.OnExpiration(func(_ string, _ NowPlayingInfo) {
@@ -90,10 +106,17 @@ func newPlayTracker(ds model.DataStore, broker events.Broker, pluginManager Plug
p.builtinScrobblers[name] = s
}
log.Debug("List of builtin scrobblers enabled", "names", enabled)
+ go p.nowPlayingWorker()
return p
}
-// pluginNamesMatchScrobblers returns true if the set of pluginNames matches the keys in pluginScrobblers
+// stopNowPlayingWorker stops the background worker. This is primarily for testing.
+func (p *playTracker) stopNowPlayingWorker() {
+ close(p.shutdown)
+ <-p.workerDone // Wait for worker to finish
+}
+
+// pluginNamesMatchScrobblers returns true if the set of pluginNames matches the keys in pluginScrobblers.
func pluginNamesMatchScrobblers(pluginNames []string, scrobblers map[string]Scrobbler) bool {
if len(pluginNames) != len(scrobblers) {
return false
@@ -106,7 +129,9 @@ func pluginNamesMatchScrobblers(pluginNames []string, scrobblers map[string]Scro
return true
}
-// refreshPluginScrobblers updates the pluginScrobblers map to match the current set of plugin scrobblers
+// refreshPluginScrobblers updates the pluginScrobblers map to match the current set of plugin scrobblers.
+// The buffered scrobblers use a loader function to dynamically get the current plugin instance,
+// so we only need to add/remove scrobblers when plugins are added/removed (not when reloaded).
func (p *playTracker) refreshPluginScrobblers() {
p.mu.Lock()
defer p.mu.Unlock()
@@ -125,15 +150,16 @@ func (p *playTracker) refreshPluginScrobblers() {
// Build a set of current plugins for faster lookups
current := make(map[string]struct{}, len(pluginNames))
- // Process additions - add new plugins
+ // Process additions - add new plugins with a loader that dynamically fetches the current instance
for _, name := range pluginNames {
current[name] = struct{}{}
- // Only create a new scrobbler if it doesn't exist
if _, exists := p.pluginScrobblers[name]; !exists {
- s, ok := p.pluginLoader.LoadScrobbler(name)
- if ok && s != nil {
- p.pluginScrobblers[name] = newBufferedScrobbler(p.ds, s, name)
- }
+ // Capture the name for the closure
+ pluginName := name
+ loader := p.pluginLoader
+ p.pluginScrobblers[name] = newBufferedScrobblerWithLoader(p.ds, name, func() (Scrobbler, bool) {
+ return loader.LoadScrobbler(pluginName)
+ })
}
}
@@ -186,10 +212,7 @@ func (p *playTracker) NowPlaying(ctx context.Context, playerId string, playerNam
// Calculate TTL based on remaining track duration. If position exceeds track duration,
// remaining is set to 0 to avoid negative TTL.
- remaining := int(mf.Duration) - position
- if remaining < 0 {
- remaining = 0
- }
+ remaining := max(int(mf.Duration)-position, 0)
// Add 5 seconds buffer to ensure the NowPlaying info is available slightly longer than the track duration.
ttl := time.Duration(remaining+5) * time.Second
_ = p.playMap.AddWithTTL(playerId, info, ttl)
@@ -198,11 +221,60 @@ func (p *playTracker) NowPlaying(ctx context.Context, playerId string, playerNam
}
player, _ := request.PlayerFrom(ctx)
if player.ScrobbleEnabled {
- p.dispatchNowPlaying(ctx, user.ID, mf, position)
+ p.enqueueNowPlaying(ctx, playerId, user.ID, mf, position)
}
return nil
}
+func (p *playTracker) enqueueNowPlaying(ctx context.Context, playerId string, userId string, track *model.MediaFile, position int) {
+ p.npMu.Lock()
+ defer p.npMu.Unlock()
+ ctx = context.WithoutCancel(ctx) // Prevent cancellation from affecting background processing
+ p.npQueue[playerId] = nowPlayingEntry{
+ ctx: ctx,
+ userId: userId,
+ track: track,
+ position: position,
+ }
+ p.sendNowPlayingSignal()
+}
+
+func (p *playTracker) sendNowPlayingSignal() {
+ // Don't block if the previous signal was not read yet
+ select {
+ case p.npSignal <- struct{}{}:
+ default:
+ }
+}
+
+func (p *playTracker) nowPlayingWorker() {
+ defer close(p.workerDone)
+ for {
+ select {
+ case <-p.shutdown:
+ return
+ case <-time.After(time.Second):
+ case <-p.npSignal:
+ }
+
+ p.npMu.Lock()
+ if len(p.npQueue) == 0 {
+ p.npMu.Unlock()
+ continue
+ }
+
+ // Keep a copy of the entries to process and clear the queue
+ entries := p.npQueue
+ p.npQueue = make(map[string]nowPlayingEntry)
+ p.npMu.Unlock()
+
+ // Process entries without holding lock
+ for _, entry := range entries {
+ p.dispatchNowPlaying(entry.ctx, entry.userId, entry.track, entry.position)
+ }
+ }
+}
+
func (p *playTracker) dispatchNowPlaying(ctx context.Context, userId string, t *model.MediaFile, position int) {
if t.Artist == consts.UnknownArtist {
log.Debug(ctx, "Ignoring external NowPlaying update for track with unknown artist", "track", t.Title, "artist", t.Artist)
@@ -276,8 +348,14 @@ func (p *playTracker) incPlay(ctx context.Context, track *model.MediaFile, times
}
for _, artist := range track.Participants[model.RoleArtist] {
err = tx.Artist(ctx).IncPlayCount(artist.ID, timestamp)
+ if err != nil {
+ return err
+ }
}
- return err
+ if conf.Server.EnableScrobbleHistory {
+ return tx.Scrobble(ctx).RecordScrobble(track.ID, timestamp)
+ }
+ return nil
})
}
diff --git a/core/scrobbler/play_tracker_test.go b/core/scrobbler/play_tracker_test.go
index 7b4785bb5..f7edecdfd 100644
--- a/core/scrobbler/play_tracker_test.go
+++ b/core/scrobbler/play_tracker_test.go
@@ -24,15 +24,26 @@ import (
// Moved to top-level scope to avoid linter issues
type mockPluginLoader struct {
+ mu sync.RWMutex
names []string
scrobblers map[string]Scrobbler
}
func (m *mockPluginLoader) PluginNames(service string) []string {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
return m.names
}
+func (m *mockPluginLoader) SetNames(names []string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.names = names
+}
+
func (m *mockPluginLoader) LoadScrobbler(name string) (Scrobbler, bool) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
s, ok := m.scrobblers[name]
return s, ok
}
@@ -46,24 +57,24 @@ var _ = Describe("PlayTracker", func() {
var album model.Album
var artist1 model.Artist
var artist2 model.Artist
- var fake fakeScrobbler
+ var fake *fakeScrobbler
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
- ctx = context.Background()
+ ctx = GinkgoT().Context()
ctx = request.WithUser(ctx, model.User{ID: "u-1"})
ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true})
ds = &tests.MockDataStore{}
- fake = fakeScrobbler{Authorized: true}
+ fake = &fakeScrobbler{Authorized: true}
Register("fake", func(model.DataStore) Scrobbler {
- return &fake
+ return fake
})
Register("disabled", func(model.DataStore) Scrobbler {
return nil
})
eventBroker = &fakeEventBroker{}
tracker = newPlayTracker(ds, eventBroker, nil)
- tracker.(*playTracker).builtinScrobblers["fake"] = &fake // Bypass buffering for tests
+ tracker.(*playTracker).builtinScrobblers["fake"] = fake // Bypass buffering for tests
track = model.MediaFile{
ID: "123",
@@ -86,6 +97,11 @@ var _ = Describe("PlayTracker", func() {
_ = ds.Album(ctx).(*tests.MockAlbumRepo).Put(&album)
})
+ AfterEach(func() {
+ // Stop the worker goroutine to prevent data races between tests
+ tracker.(*playTracker).stopNowPlayingWorker()
+ })
+
It("does not register disabled scrobblers", func() {
Expect(tracker.(*playTracker).builtinScrobblers).To(HaveKey("fake"))
Expect(tracker.(*playTracker).builtinScrobblers).ToNot(HaveKey("disabled"))
@@ -95,10 +111,10 @@ var _ = Describe("PlayTracker", func() {
It("sends track to agent", func() {
err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
Expect(err).ToNot(HaveOccurred())
- Expect(fake.NowPlayingCalled).To(BeTrue())
- Expect(fake.UserID).To(Equal("u-1"))
- Expect(fake.Track.ID).To(Equal("123"))
- Expect(fake.Track.Participants).To(Equal(track.Participants))
+ Eventually(func() bool { return fake.GetNowPlayingCalled() }).Should(BeTrue())
+ Expect(fake.GetUserID()).To(Equal("u-1"))
+ Expect(fake.GetTrack().ID).To(Equal("123"))
+ Expect(fake.GetTrack().Participants).To(Equal(track.Participants))
})
It("does not send track to agent if user has not authorized", func() {
fake.Authorized = false
@@ -106,7 +122,7 @@ var _ = Describe("PlayTracker", func() {
err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
Expect(err).ToNot(HaveOccurred())
- Expect(fake.NowPlayingCalled).To(BeFalse())
+ Expect(fake.GetNowPlayingCalled()).To(BeFalse())
})
It("does not send track to agent if player is not enabled to send scrobbles", func() {
ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: false})
@@ -114,7 +130,7 @@ var _ = Describe("PlayTracker", func() {
err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
Expect(err).ToNot(HaveOccurred())
- Expect(fake.NowPlayingCalled).To(BeFalse())
+ Expect(fake.GetNowPlayingCalled()).To(BeFalse())
})
It("does not send track to agent if artist is unknown", func() {
track.Artist = consts.UnknownArtist
@@ -122,7 +138,7 @@ var _ = Describe("PlayTracker", func() {
err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
Expect(err).ToNot(HaveOccurred())
- Expect(fake.NowPlayingCalled).To(BeFalse())
+ Expect(fake.GetNowPlayingCalled()).To(BeFalse())
})
It("stores position when greater than zero", func() {
@@ -130,11 +146,12 @@ var _ = Describe("PlayTracker", func() {
err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", pos)
Expect(err).ToNot(HaveOccurred())
+ Eventually(func() int { return fake.GetPosition() }).Should(Equal(pos))
+
playing, err := tracker.GetNowPlaying(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(playing).To(HaveLen(1))
Expect(playing[0].Position).To(Equal(pos))
- Expect(fake.Position).To(Equal(pos))
})
It("sends event with count", func() {
@@ -153,6 +170,17 @@ var _ = Describe("PlayTracker", func() {
Expect(err).ToNot(HaveOccurred())
Expect(eventBroker.getEvents()).To(BeEmpty())
})
+
+ It("passes user to scrobbler via context (fix for issue #4787)", func() {
+ ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "testuser"})
+ ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true})
+
+ err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
+ Expect(err).ToNot(HaveOccurred())
+ Eventually(func() bool { return fake.GetNowPlayingCalled() }).Should(BeTrue())
+ // Verify the username was passed through async dispatch via context
+ Eventually(func() string { return fake.GetUsername() }).Should(Equal("testuser"))
+ })
})
Describe("GetNowPlaying", func() {
@@ -160,9 +188,9 @@ var _ = Describe("PlayTracker", func() {
track2 := track
track2.ID = "456"
_ = ds.MediaFile(ctx).Put(&track2)
- ctx = request.WithUser(context.Background(), model.User{UserName: "user-1"})
+ ctx = request.WithUser(GinkgoT().Context(), model.User{UserName: "user-1"})
_ = tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
- ctx = request.WithUser(context.Background(), model.User{UserName: "user-2"})
+ ctx = request.WithUser(GinkgoT().Context(), model.User{UserName: "user-2"})
_ = tracker.NowPlaying(ctx, "player-2", "player-two", "456", 0)
playing, err := tracker.GetNowPlaying(ctx)
@@ -210,7 +238,7 @@ var _ = Describe("PlayTracker", func() {
Expect(err).ToNot(HaveOccurred())
Expect(fake.ScrobbleCalled.Load()).To(BeTrue())
- Expect(fake.UserID).To(Equal("u-1"))
+ Expect(fake.GetUserID()).To(Equal("u-1"))
lastScrobble := fake.LastScrobble.Load()
Expect(lastScrobble.TimeStamp).To(BeTemporally("~", ts, 1*time.Second))
Expect(lastScrobble.ID).To(Equal("123"))
@@ -274,49 +302,82 @@ var _ = Describe("PlayTracker", func() {
Expect(artist1.PlayCount).To(Equal(int64(1)))
Expect(artist2.PlayCount).To(Equal(int64(1)))
})
+
+ Context("Scrobble History", func() {
+ It("records scrobble in repository", func() {
+ conf.Server.EnableScrobbleHistory = true
+ ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "user-1"})
+ ts := time.Now()
+
+ err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: ts}})
+
+ Expect(err).ToNot(HaveOccurred())
+
+ mockDS := ds.(*tests.MockDataStore)
+ mockScrobble := mockDS.Scrobble(ctx).(*tests.MockScrobbleRepo)
+ Expect(mockScrobble.RecordedScrobbles).To(HaveLen(1))
+ Expect(mockScrobble.RecordedScrobbles[0].MediaFileID).To(Equal("123"))
+ Expect(mockScrobble.RecordedScrobbles[0].UserID).To(Equal("u-1"))
+ Expect(mockScrobble.RecordedScrobbles[0].SubmissionTime).To(Equal(ts))
+ })
+
+ It("does not record scrobble when history is disabled", func() {
+ conf.Server.EnableScrobbleHistory = false
+ ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "user-1"})
+ ts := time.Now()
+
+ err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: ts}})
+
+ Expect(err).ToNot(HaveOccurred())
+ mockDS := ds.(*tests.MockDataStore)
+ mockScrobble := mockDS.Scrobble(ctx).(*tests.MockScrobbleRepo)
+ Expect(mockScrobble.RecordedScrobbles).To(HaveLen(0))
+ })
+ })
})
Describe("Plugin scrobbler logic", func() {
var pluginLoader *mockPluginLoader
- var pluginFake fakeScrobbler
+ var pluginFake *fakeScrobbler
BeforeEach(func() {
- pluginFake = fakeScrobbler{Authorized: true}
+ pluginFake = &fakeScrobbler{Authorized: true}
pluginLoader = &mockPluginLoader{
names: []string{"plugin1"},
- scrobblers: map[string]Scrobbler{"plugin1": &pluginFake},
+ scrobblers: map[string]Scrobbler{"plugin1": pluginFake},
}
tracker = newPlayTracker(ds, events.GetBroker(), pluginLoader)
// Bypass buffering for both built-in and plugin scrobblers
- tracker.(*playTracker).builtinScrobblers["fake"] = &fake
- tracker.(*playTracker).pluginScrobblers["plugin1"] = &pluginFake
+ tracker.(*playTracker).builtinScrobblers["fake"] = fake
+ tracker.(*playTracker).pluginScrobblers["plugin1"] = pluginFake
})
It("registers and uses plugin scrobbler for NowPlaying", func() {
err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
Expect(err).ToNot(HaveOccurred())
- Expect(pluginFake.NowPlayingCalled).To(BeTrue())
+ Eventually(func() bool { return pluginFake.GetNowPlayingCalled() }).Should(BeTrue())
})
It("removes plugin scrobbler if not present anymore", func() {
// First call: plugin present
_ = tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
- Expect(pluginFake.NowPlayingCalled).To(BeTrue())
- pluginFake.NowPlayingCalled = false
+ Eventually(func() bool { return pluginFake.GetNowPlayingCalled() }).Should(BeTrue())
+ pluginFake.nowPlayingCalled.Store(false)
// Remove plugin
- pluginLoader.names = []string{}
+ pluginLoader.SetNames([]string{})
_ = tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
- Expect(pluginFake.NowPlayingCalled).To(BeFalse())
+ // Should not be called since plugin was removed
+ Consistently(func() bool { return pluginFake.GetNowPlayingCalled() }).Should(BeFalse())
})
It("calls both builtin and plugin scrobblers for NowPlaying", func() {
- fake.NowPlayingCalled = false
- pluginFake.NowPlayingCalled = false
+ fake.nowPlayingCalled.Store(false)
+ pluginFake.nowPlayingCalled.Store(false)
err := tracker.NowPlaying(ctx, "player-1", "player-one", "123", 0)
Expect(err).ToNot(HaveOccurred())
- Expect(fake.NowPlayingCalled).To(BeTrue())
- Expect(pluginFake.NowPlayingCalled).To(BeTrue())
+ Eventually(func() bool { return fake.GetNowPlayingCalled() }).Should(BeTrue())
+ Eventually(func() bool { return pluginFake.GetNowPlayingCalled() }).Should(BeTrue())
})
It("calls plugin scrobbler for Submit", func() {
@@ -334,7 +395,7 @@ var _ = Describe("PlayTracker", func() {
var mockedBS *mockBufferedScrobbler
BeforeEach(func() {
- ctx = context.Background()
+ ctx = GinkgoT().Context()
ctx = request.WithUser(ctx, model.User{ID: "u-1"})
ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true})
ds = &tests.MockDataStore{}
@@ -359,7 +420,7 @@ var _ = Describe("PlayTracker", func() {
It("calls Stop on scrobblers when removing them", func() {
// Change the plugin names to simulate a plugin being removed
- mockPlugin.names = []string{}
+ mockPlugin.SetNames([]string{})
// Call refreshPluginScrobblers which should detect the removed plugin
pTracker.refreshPluginScrobblers()
@@ -371,36 +432,189 @@ var _ = Describe("PlayTracker", func() {
Expect(pTracker.pluginScrobblers).NotTo(HaveKey("plugin1"))
})
})
+
+ Describe("Plugin reload (config update) behavior", func() {
+ var mockPlugin *mockPluginLoader
+ var pTracker *playTracker
+ var originalScrobbler *fakeScrobbler
+ var reloadedScrobbler *fakeScrobbler
+
+ BeforeEach(func() {
+ ctx = GinkgoT().Context()
+ ctx = request.WithUser(ctx, model.User{ID: "u-1"})
+ ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true})
+ ds = &tests.MockDataStore{}
+
+ // Setup initial plugin scrobbler
+ originalScrobbler = &fakeScrobbler{Authorized: true}
+ reloadedScrobbler = &fakeScrobbler{Authorized: true}
+
+ mockPlugin = &mockPluginLoader{
+ names: []string{"plugin1"},
+ scrobblers: map[string]Scrobbler{"plugin1": originalScrobbler},
+ }
+
+ // Create tracker - this will create buffered scrobblers with loaders
+ pTracker = newPlayTracker(ds, events.GetBroker(), mockPlugin)
+
+ // Trigger initial plugin registration
+ pTracker.refreshPluginScrobblers()
+ })
+
+ AfterEach(func() {
+ pTracker.stopNowPlayingWorker()
+ })
+
+ It("uses the new plugin instance after reload (simulating config update)", func() {
+ // First call should use the original scrobbler
+ scrobblers := pTracker.getActiveScrobblers()
+ pluginScr := scrobblers["plugin1"]
+ Expect(pluginScr).ToNot(BeNil())
+
+ err := pluginScr.NowPlaying(ctx, "u-1", &track, 0)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(originalScrobbler.GetNowPlayingCalled()).To(BeTrue())
+ Expect(reloadedScrobbler.GetNowPlayingCalled()).To(BeFalse())
+
+ // Simulate plugin reload (config update): replace the scrobbler in the loader
+ // This is what happens when UpdatePluginConfig is called - the plugin manager
+ // unloads the old plugin and loads a new instance
+ mockPlugin.mu.Lock()
+ mockPlugin.scrobblers["plugin1"] = reloadedScrobbler
+ mockPlugin.mu.Unlock()
+
+ // Reset call tracking
+ originalScrobbler.nowPlayingCalled.Store(false)
+
+ // Get scrobblers again - should still return the same buffered scrobbler
+ // but subsequent calls should use the new plugin instance via the loader
+ scrobblers = pTracker.getActiveScrobblers()
+ pluginScr = scrobblers["plugin1"]
+
+ err = pluginScr.NowPlaying(ctx, "u-1", &track, 0)
+ Expect(err).ToNot(HaveOccurred())
+
+ // The new scrobbler should be called, not the old one
+ Expect(reloadedScrobbler.GetNowPlayingCalled()).To(BeTrue())
+ Expect(originalScrobbler.GetNowPlayingCalled()).To(BeFalse())
+ })
+
+ It("handles plugin becoming unavailable temporarily", func() {
+ // First verify plugin works
+ scrobblers := pTracker.getActiveScrobblers()
+ pluginScr := scrobblers["plugin1"]
+
+ err := pluginScr.NowPlaying(ctx, "u-1", &track, 0)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(originalScrobbler.GetNowPlayingCalled()).To(BeTrue())
+
+ // Simulate plugin becoming unavailable (e.g., during reload)
+ mockPlugin.mu.Lock()
+ delete(mockPlugin.scrobblers, "plugin1")
+ mockPlugin.mu.Unlock()
+
+ originalScrobbler.nowPlayingCalled.Store(false)
+
+ // NowPlaying should return error when plugin unavailable
+ err = pluginScr.NowPlaying(ctx, "u-1", &track, 0)
+ Expect(err).To(HaveOccurred())
+ Expect(originalScrobbler.GetNowPlayingCalled()).To(BeFalse())
+
+ // Simulate plugin becoming available again
+ mockPlugin.mu.Lock()
+ mockPlugin.scrobblers["plugin1"] = reloadedScrobbler
+ mockPlugin.mu.Unlock()
+
+ // Should work again with new instance
+ err = pluginScr.NowPlaying(ctx, "u-1", &track, 0)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(reloadedScrobbler.GetNowPlayingCalled()).To(BeTrue())
+ })
+
+ It("IsAuthorized uses the current plugin instance", func() {
+ scrobblers := pTracker.getActiveScrobblers()
+ pluginScr := scrobblers["plugin1"]
+
+ // Original is authorized
+ Expect(pluginScr.IsAuthorized(ctx, "u-1")).To(BeTrue())
+
+ // Replace with unauthorized scrobbler
+ unauthorizedScrobbler := &fakeScrobbler{Authorized: false}
+ mockPlugin.mu.Lock()
+ mockPlugin.scrobblers["plugin1"] = unauthorizedScrobbler
+ mockPlugin.mu.Unlock()
+
+ // Should reflect the new scrobbler's authorization status
+ Expect(pluginScr.IsAuthorized(ctx, "u-1")).To(BeFalse())
+ })
+ })
})
type fakeScrobbler struct {
Authorized bool
- NowPlayingCalled bool
+ nowPlayingCalled atomic.Bool
ScrobbleCalled atomic.Bool
- UserID string
- Track *model.MediaFile
- Position int
+ userID atomic.Pointer[string]
+ username atomic.Pointer[string]
+ track atomic.Pointer[model.MediaFile]
+ position atomic.Int32
LastScrobble atomic.Pointer[Scrobble]
Error error
}
+func (f *fakeScrobbler) GetNowPlayingCalled() bool {
+ return f.nowPlayingCalled.Load()
+}
+
+func (f *fakeScrobbler) GetUserID() string {
+ if p := f.userID.Load(); p != nil {
+ return *p
+ }
+ return ""
+}
+
+func (f *fakeScrobbler) GetTrack() *model.MediaFile {
+ return f.track.Load()
+}
+
+func (f *fakeScrobbler) GetPosition() int {
+ return int(f.position.Load())
+}
+
+func (f *fakeScrobbler) GetUsername() string {
+ if p := f.username.Load(); p != nil {
+ return *p
+ }
+ return ""
+}
+
func (f *fakeScrobbler) IsAuthorized(ctx context.Context, userId string) bool {
return f.Error == nil && f.Authorized
}
func (f *fakeScrobbler) NowPlaying(ctx context.Context, userId string, track *model.MediaFile, position int) error {
- f.NowPlayingCalled = true
+ f.nowPlayingCalled.Store(true)
if f.Error != nil {
return f.Error
}
- f.UserID = userId
- f.Track = track
- f.Position = position
+ f.userID.Store(&userId)
+ // Capture username from context (this is what plugin scrobblers do)
+ username, _ := request.UsernameFrom(ctx)
+ if username == "" {
+ if u, ok := request.UserFrom(ctx); ok {
+ username = u.UserName
+ }
+ }
+ if username != "" {
+ f.username.Store(&username)
+ }
+ f.track.Store(track)
+ f.position.Store(int32(position))
return nil
}
func (f *fakeScrobbler) Scrobble(ctx context.Context, userId string, s Scrobble) error {
- f.UserID = userId
+ f.userID.Store(&userId)
f.LastScrobble.Store(&s)
f.ScrobbleCalled.Store(true)
if f.Error != nil {
diff --git a/core/share.go b/core/share.go
index 202c27d89..a6d06a018 100644
--- a/core/share.go
+++ b/core/share.go
@@ -7,12 +7,13 @@ import (
"github.com/Masterminds/squirrel"
"github.com/deluan/rest"
- gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
. "github.com/navidrome/navidrome/utils/gg"
+ "github.com/navidrome/navidrome/utils/nanoid"
"github.com/navidrome/navidrome/utils/slice"
+ "github.com/navidrome/navidrome/utils/str"
)
type Share interface {
@@ -72,7 +73,7 @@ type shareRepositoryWrapper struct {
func (r *shareRepositoryWrapper) newId() (string, error) {
for {
- id, err := gonanoid.Generate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 10)
+ id, err := nanoid.Generate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 10)
if err != nil {
return "", err
}
@@ -86,7 +87,7 @@ func (r *shareRepositoryWrapper) newId() (string, error) {
}
}
-func (r *shareRepositoryWrapper) Save(entity interface{}) (string, error) {
+func (r *shareRepositoryWrapper) Save(entity any) (string, error) {
s := entity.(*model.Share)
id, err := r.newId()
if err != nil {
@@ -119,15 +120,14 @@ func (r *shareRepositoryWrapper) Save(entity interface{}) (string, error) {
log.Error(r.ctx, "Invalid Resource ID", "id", firstId)
return "", model.ErrNotFound
}
- if len(s.Contents) > 30 {
- s.Contents = s.Contents[:26] + "..."
- }
+
+ s.Contents = str.TruncateRunes(s.Contents, 30, "...")
id, err = r.Persistable.Save(s)
return id, err
}
-func (r *shareRepositoryWrapper) Update(id string, entity interface{}, _ ...string) error {
+func (r *shareRepositoryWrapper) Update(id string, entity any, _ ...string) error {
cols := []string{"description", "downloadable"}
// TODO Better handling of Share expiration
diff --git a/core/share_test.go b/core/share_test.go
index 21069bb59..475d40ec9 100644
--- a/core/share_test.go
+++ b/core/share_test.go
@@ -38,6 +38,38 @@ var _ = Describe("Share", func() {
Expect(id).ToNot(BeEmpty())
Expect(entity.ID).To(Equal(id))
})
+
+ It("does not truncate ASCII labels shorter than 30 characters", func() {
+ _ = ds.MediaFile(ctx).Put(&model.MediaFile{ID: "456", Title: "Example Media File"})
+ entity := &model.Share{Description: "test", ResourceIDs: "456"}
+ _, err := repo.Save(entity)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(entity.Contents).To(Equal("Example Media File"))
+ })
+
+ It("truncates ASCII labels longer than 30 characters", func() {
+ _ = ds.MediaFile(ctx).Put(&model.MediaFile{ID: "789", Title: "Example Media File But The Title Is Really Long For Testing Purposes"})
+ entity := &model.Share{Description: "test", ResourceIDs: "789"}
+ _, err := repo.Save(entity)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(entity.Contents).To(Equal("Example Media File But The ..."))
+ })
+
+ It("does not truncate CJK labels shorter than 30 runes", func() {
+ _ = ds.MediaFile(ctx).Put(&model.MediaFile{ID: "456", Title: "青春コンプレックス"})
+ entity := &model.Share{Description: "test", ResourceIDs: "456"}
+ _, err := repo.Save(entity)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(entity.Contents).To(Equal("青春コンプレックス"))
+ })
+
+ It("truncates CJK labels longer than 30 runes", func() {
+ _ = ds.MediaFile(ctx).Put(&model.MediaFile{ID: "789", Title: "私の中の幻想的世界観及びその顕現を想起させたある現実での出来事に関する一考察"})
+ entity := &model.Share{Description: "test", ResourceIDs: "789"}
+ _, err := repo.Save(entity)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(entity.Contents).To(Equal("私の中の幻想的世界観及びその顕現を想起させたある現実で..."))
+ })
})
Describe("Update", func() {
diff --git a/core/storage/local/local.go b/core/storage/local/local.go
index 5c335ddb9..cd60c9ef1 100644
--- a/core/storage/local/local.go
+++ b/core/storage/local/local.go
@@ -44,7 +44,7 @@ func newLocalStorage(u url.URL) storage.Storage {
func (s *localStorage) FS() (storage.MusicFS, error) {
path := s.u.Path
- if _, err := os.Stat(path); err != nil {
+ if _, err := os.Stat(path); err != nil { //nolint:gosec
return nil, fmt.Errorf("%w: %s", err, path)
}
return &localFS{FS: os.DirFS(path), extractor: s.extractor}, nil
diff --git a/core/storage/local/watcher.go b/core/storage/local/watcher.go
index e2418f4cb..1b8a4e0c8 100644
--- a/core/storage/local/watcher.go
+++ b/core/storage/local/watcher.go
@@ -17,8 +17,8 @@ func (s *localStorage) Start(ctx context.Context) (<-chan string, error) {
if !s.watching.CompareAndSwap(false, true) {
return nil, errors.New("watcher already started")
}
- input := make(chan notify.EventInfo, 1)
- output := make(chan string, 1)
+ input := make(chan notify.EventInfo, 500)
+ output := make(chan string, 500)
started := make(chan struct{})
go func() {
diff --git a/core/storage/storagetest/fake_storage.go b/core/storage/storagetest/fake_storage.go
index 009b37d2d..1b0d1a6c1 100644
--- a/core/storage/storagetest/fake_storage.go
+++ b/core/storage/storagetest/fake_storage.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io/fs"
+ "maps"
"net/url"
"path"
"testing/fstest"
@@ -135,9 +136,7 @@ func (ffs *FakeFS) UpdateTags(filePath string, newTags map[string]any, when ...t
if err != nil {
panic(err)
}
- for k, v := range newTags {
- tags[k] = v
- }
+ maps.Copy(tags, newTags)
data, _ := json.Marshal(tags)
f.Data = data
ffs.Touch(filePath, when...)
@@ -180,9 +179,7 @@ func Track(num int, title string, tags ...map[string]any) map[string]any {
ts["title"] = title
ts["track"] = num
for _, t := range tags {
- for k, v := range t {
- ts[k] = v
- }
+ maps.Copy(ts, t)
}
return ts
}
@@ -200,9 +197,7 @@ func MP3(tags ...map[string]any) *fstest.MapFile {
func File(tags ...map[string]any) *fstest.MapFile {
ts := map[string]any{}
for _, t := range tags {
- for k, v := range t {
- ts[k] = v
- }
+ maps.Copy(ts, t)
}
modTime := time.Now()
if mt, ok := ts[fakeFileInfoModTime]; !ok {
@@ -289,6 +284,9 @@ func (ffs *FakeFS) parseFile(filePath string) (*metadata.Info, error) {
p.AudioProperties.BitDepth = getInt("bitdepth")
p.AudioProperties.SampleRate = getInt("samplerate")
p.AudioProperties.Channels = getInt("channels")
+ if codec, ok := data["codec"].(string); ok {
+ p.AudioProperties.Codec = codec
+ }
for k, v := range data {
p.Tags[k] = []string{fmt.Sprintf("%v", v)}
}
diff --git a/core/stream/aliases.go b/core/stream/aliases.go
new file mode 100644
index 000000000..af42ac076
--- /dev/null
+++ b/core/stream/aliases.go
@@ -0,0 +1,92 @@
+package stream
+
+import (
+ "slices"
+ "strings"
+)
+
+// containerAliasGroups maps each container alias to a canonical group name.
+var containerAliasGroups = func() map[string]string {
+ groups := [][]string{
+ {"aac", "adts", "m4a", "mp4", "m4b", "m4p"},
+ {"mpeg", "mp3", "mp2"},
+ {"ogg", "oga", "opus"},
+ {"aif", "aiff"},
+ {"asf", "wma"},
+ {"mpc", "mpp"},
+ {"wv"},
+ }
+ m := make(map[string]string)
+ for _, g := range groups {
+ canonical := g[0]
+ for _, name := range g {
+ m[name] = canonical
+ }
+ }
+ return m
+}()
+
+// codecAliasGroups maps each codec alias to a canonical group name.
+// Codecs within the same group are considered equivalent.
+var codecAliasGroups = func() map[string]string {
+ groups := [][]string{
+ {"aac", "adts"},
+ {"ac3", "ac-3"},
+ {"eac3", "e-ac3", "e-ac-3", "eac-3"},
+ {"mpc7", "musepack7"},
+ {"mpc8", "musepack8"},
+ {"wma1", "wmav1"},
+ {"wma2", "wmav2"},
+ {"wmalossless", "wma9lossless"},
+ {"wmapro", "wma9pro"},
+ {"shn", "shorten"},
+ {"mp4als", "als"},
+ }
+ m := make(map[string]string)
+ for _, g := range groups {
+ for _, name := range g {
+ m[name] = g[0] // canonical = first entry
+ }
+ }
+ return m
+}()
+
+// matchesWithAliases checks if a value matches any entry in candidates,
+// consulting the alias map for equivalent names.
+func matchesWithAliases(value string, candidates []string, aliases map[string]string) bool {
+ value = strings.ToLower(value)
+ canonical := aliases[value]
+ for _, c := range candidates {
+ c = strings.ToLower(c)
+ if c == value {
+ return true
+ }
+ if canonical != "" && aliases[c] == canonical {
+ return true
+ }
+ }
+ return false
+}
+
+// matchesContainer checks if a file suffix matches any of the container names,
+// including common aliases.
+func matchesContainer(suffix string, containers []string) bool {
+ return matchesWithAliases(suffix, containers, containerAliasGroups)
+}
+
+// matchesCodec checks if a codec matches any of the codec names,
+// including common aliases.
+func matchesCodec(codec string, codecs []string) bool {
+ return matchesWithAliases(codec, codecs, codecAliasGroups)
+}
+
+// IsAACCodec returns true if the given codec or container name resolves to AAC.
+func IsAACCodec(name string) bool {
+ return matchesCodec(name, []string{"aac"}) || matchesContainer(name, []string{"aac"})
+}
+
+func containsIgnoreCase(slice []string, s string) bool {
+ return slices.ContainsFunc(slice, func(item string) bool {
+ return strings.EqualFold(item, s)
+ })
+}
diff --git a/core/stream/aliases_test.go b/core/stream/aliases_test.go
new file mode 100644
index 000000000..72f061810
--- /dev/null
+++ b/core/stream/aliases_test.go
@@ -0,0 +1,30 @@
+package stream
+
+import (
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Aliases", func() {
+ Describe("IsAACCodec", func() {
+ It("returns true for AAC and its aliases", func() {
+ Expect(IsAACCodec("aac")).To(BeTrue())
+ Expect(IsAACCodec("AAC")).To(BeTrue())
+ Expect(IsAACCodec("adts")).To(BeTrue())
+ Expect(IsAACCodec("m4a")).To(BeTrue())
+ Expect(IsAACCodec("mp4")).To(BeTrue())
+ Expect(IsAACCodec("m4b")).To(BeTrue())
+ })
+
+ It("returns false for non-AAC formats", func() {
+ Expect(IsAACCodec("mp3")).To(BeFalse())
+ Expect(IsAACCodec("opus")).To(BeFalse())
+ Expect(IsAACCodec("flac")).To(BeFalse())
+ Expect(IsAACCodec("ogg")).To(BeFalse())
+ })
+
+ It("returns false for empty string", func() {
+ Expect(IsAACCodec("")).To(BeFalse())
+ })
+ })
+})
diff --git a/core/stream/codec.go b/core/stream/codec.go
new file mode 100644
index 000000000..88d1ae45d
--- /dev/null
+++ b/core/stream/codec.go
@@ -0,0 +1,77 @@
+package stream
+
+import "strings"
+
+// normalizeProbeCodec maps ffprobe codec_name values to the simplified internal
+// codec names used throughout Navidrome (matching inferCodecFromSuffix output).
+// Most ffprobe names match directly; this handles the exceptions.
+func normalizeProbeCodec(codec string) string {
+ c := strings.ToLower(codec)
+ // DSD variants: dsd_lsbf_planar, dsd_msbf_planar, dsd_lsbf, dsd_msbf
+ if strings.HasPrefix(c, "dsd") {
+ return "dsd"
+ }
+ // PCM variants: pcm_s16le, pcm_s24le, pcm_s32be, pcm_f32le, etc.
+ if strings.HasPrefix(c, "pcm_") {
+ return "pcm"
+ }
+ return c
+}
+
+// isLosslessFormat returns true if the format is a known lossless audio codec/format.
+// Detection is based on codec name only, not bit depth — some lossy codecs (e.g. ADPCM)
+// report non-zero bits_per_sample in ffprobe, so bit depth alone is not a reliable signal.
+//
+// Note: core/ffmpeg has a separate isLosslessOutputFormat that covers only formats
+// ffmpeg can produce as output (a smaller set).
+func isLosslessFormat(format string) bool {
+ switch strings.ToLower(format) {
+ case "flac", "alac", "wav", "aiff", "ape", "wv", "wavpack", "tta", "tak", "shn", "dsd", "pcm":
+ return true
+ }
+ return false
+}
+
+// normalizeSourceSampleRate adjusts the source sample rate for codecs that store
+// it differently than PCM. Currently handles DSD (÷8):
+// DSD64=2822400→352800, DSD128=5644800→705600, etc.
+// For other codecs, returns the rate unchanged.
+func normalizeSourceSampleRate(sampleRate int, codec string) int {
+ if strings.EqualFold(codec, "dsd") && sampleRate > 0 {
+ return sampleRate / 8
+ }
+ return sampleRate
+}
+
+// normalizeSourceBitDepth adjusts the source bit depth for codecs that use
+// non-standard bit depths. Currently handles DSD (1-bit → 24-bit PCM, which is
+// what ffmpeg produces). For other codecs, returns the depth unchanged.
+func normalizeSourceBitDepth(bitDepth int, codec string) int {
+ if strings.EqualFold(codec, "dsd") && bitDepth == 1 {
+ return 24
+ }
+ return bitDepth
+}
+
+// codecFixedOutputSampleRate returns the mandatory output sample rate for codecs
+// that always resample regardless of input (e.g., Opus always outputs 48000Hz).
+// Returns 0 if the codec has no fixed output rate.
+func codecFixedOutputSampleRate(codec string) int {
+ switch strings.ToLower(codec) {
+ case "opus":
+ return 48000
+ }
+ return 0
+}
+
+// codecMaxSampleRate returns the hard maximum output sample rate for a codec.
+// Returns 0 if the codec has no hard limit.
+func codecMaxSampleRate(codec string) int {
+ switch strings.ToLower(codec) {
+ case "mp3":
+ return 48000
+ case "aac":
+ return 96000
+ }
+ return 0
+}
diff --git a/core/stream/codec_test.go b/core/stream/codec_test.go
new file mode 100644
index 000000000..4c76b3ecd
--- /dev/null
+++ b/core/stream/codec_test.go
@@ -0,0 +1,69 @@
+package stream
+
+import (
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Codec", func() {
+ Describe("isLosslessFormat", func() {
+ It("returns true for known lossless codecs", func() {
+ Expect(isLosslessFormat("flac")).To(BeTrue())
+ Expect(isLosslessFormat("alac")).To(BeTrue())
+ Expect(isLosslessFormat("pcm")).To(BeTrue())
+ Expect(isLosslessFormat("wav")).To(BeTrue())
+ Expect(isLosslessFormat("dsd")).To(BeTrue())
+ Expect(isLosslessFormat("ape")).To(BeTrue())
+ Expect(isLosslessFormat("wv")).To(BeTrue())
+ Expect(isLosslessFormat("wavpack")).To(BeTrue()) // ffprobe codec_name for WavPack
+ })
+
+ It("returns false for lossy codecs", func() {
+ Expect(isLosslessFormat("mp3")).To(BeFalse())
+ Expect(isLosslessFormat("aac")).To(BeFalse())
+ Expect(isLosslessFormat("opus")).To(BeFalse())
+ Expect(isLosslessFormat("vorbis")).To(BeFalse())
+ })
+
+ It("returns false for unknown codecs", func() {
+ Expect(isLosslessFormat("unknown_codec")).To(BeFalse())
+ })
+
+ It("is case-insensitive", func() {
+ Expect(isLosslessFormat("FLAC")).To(BeTrue())
+ Expect(isLosslessFormat("Alac")).To(BeTrue())
+ })
+ })
+
+ Describe("normalizeProbeCodec", func() {
+ It("passes through common codec names unchanged", func() {
+ Expect(normalizeProbeCodec("mp3")).To(Equal("mp3"))
+ Expect(normalizeProbeCodec("aac")).To(Equal("aac"))
+ Expect(normalizeProbeCodec("flac")).To(Equal("flac"))
+ Expect(normalizeProbeCodec("opus")).To(Equal("opus"))
+ Expect(normalizeProbeCodec("vorbis")).To(Equal("vorbis"))
+ Expect(normalizeProbeCodec("alac")).To(Equal("alac"))
+ Expect(normalizeProbeCodec("wmav2")).To(Equal("wmav2"))
+ })
+
+ It("normalizes DSD variants to dsd", func() {
+ Expect(normalizeProbeCodec("dsd_lsbf_planar")).To(Equal("dsd"))
+ Expect(normalizeProbeCodec("dsd_msbf_planar")).To(Equal("dsd"))
+ Expect(normalizeProbeCodec("dsd_lsbf")).To(Equal("dsd"))
+ Expect(normalizeProbeCodec("dsd_msbf")).To(Equal("dsd"))
+ })
+
+ It("normalizes PCM variants to pcm", func() {
+ Expect(normalizeProbeCodec("pcm_s16le")).To(Equal("pcm"))
+ Expect(normalizeProbeCodec("pcm_s24le")).To(Equal("pcm"))
+ Expect(normalizeProbeCodec("pcm_s32be")).To(Equal("pcm"))
+ Expect(normalizeProbeCodec("pcm_f32le")).To(Equal("pcm"))
+ })
+
+ It("lowercases input", func() {
+ Expect(normalizeProbeCodec("MP3")).To(Equal("mp3"))
+ Expect(normalizeProbeCodec("AAC")).To(Equal("aac"))
+ Expect(normalizeProbeCodec("DSD_LSBF_PLANAR")).To(Equal("dsd"))
+ })
+ })
+})
diff --git a/core/stream/decider.go b/core/stream/decider.go
new file mode 100644
index 000000000..5cca0cb0f
--- /dev/null
+++ b/core/stream/decider.go
@@ -0,0 +1,449 @@
+package stream
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+)
+
+const fallbackBitrate = 256 // kbps
+
+// TranscodeDecider is the core service interface for making transcoding decisions
+type TranscodeDecider interface {
+ MakeDecision(ctx context.Context, mf *model.MediaFile, clientInfo *ClientInfo, opts TranscodeOptions) (*TranscodeDecision, error)
+ CreateTranscodeParams(decision *TranscodeDecision) (string, error)
+ ResolveRequestFromToken(ctx context.Context, token string, mf *model.MediaFile, offset int) (Request, error)
+ ResolveRequest(ctx context.Context, mf *model.MediaFile, reqFormat string, reqBitRate int, offset int) Request
+}
+
+func NewTranscodeDecider(ds model.DataStore, ff ffmpeg.FFmpeg) TranscodeDecider {
+ return &deciderService{
+ ds: ds,
+ ff: ff,
+ }
+}
+
+type deciderService struct {
+ ds model.DataStore
+ ff ffmpeg.FFmpeg
+}
+
+func (s *deciderService) MakeDecision(ctx context.Context, mf *model.MediaFile, clientInfo *ClientInfo, opts TranscodeOptions) (*TranscodeDecision, error) {
+ decision := &TranscodeDecision{
+ MediaID: mf.ID,
+ SourceUpdatedAt: mf.UpdatedAt,
+ }
+
+ var probe *ffmpeg.AudioProbeResult
+ if !opts.SkipProbe {
+ var err error
+ probe, err = s.ensureProbed(ctx, mf)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ // Build source stream details (uses probe data if available)
+ decision.SourceStream = buildSourceStream(mf, probe)
+ src := &decision.SourceStream
+
+ // Check for server-side player transcoding override
+ if trc, ok := request.TranscodingFrom(ctx); ok && trc.TargetFormat != "" {
+ clientInfo = applyServerOverride(ctx, clientInfo, &trc)
+ } else if player, ok := request.PlayerFrom(ctx); ok && player.MaxBitRate > 0 {
+ if clientInfo.MaxAudioBitrate == 0 || player.MaxBitRate < clientInfo.MaxAudioBitrate {
+ modified := *clientInfo
+ modified.MaxAudioBitrate = player.MaxBitRate
+ clientInfo = &modified
+ log.Debug(ctx, "Applied player MaxBitRate cap", "playerMaxBitRate", player.MaxBitRate, "client", clientInfo.Name)
+ }
+ }
+
+ log.Trace(ctx, "Making transcode decision", "mediaID", mf.ID, "container", src.Container,
+ "codec", src.Codec, "bitrate", src.Bitrate, "channels", src.Channels,
+ "sampleRate", src.SampleRate, "lossless", src.IsLossless, "client", clientInfo.Name)
+
+ // Check global bitrate constraint first.
+ if clientInfo.MaxAudioBitrate > 0 && src.Bitrate > clientInfo.MaxAudioBitrate {
+ log.Trace(ctx, "Global bitrate constraint exceeded, skipping direct play",
+ "sourceBitrate", src.Bitrate, "maxAudioBitrate", clientInfo.MaxAudioBitrate)
+ decision.TranscodeReasons = append(decision.TranscodeReasons, "audio bitrate not supported")
+ // Skip direct play profiles entirely — global constraint fails
+ } else {
+ // Try direct play profiles, collecting reasons for each failure
+ for _, profile := range clientInfo.DirectPlayProfiles {
+ if reason := s.checkDirectPlayProfile(src, &profile, clientInfo); reason == "" {
+ decision.CanDirectPlay = true
+ decision.TranscodeReasons = nil // Clear any previously collected reasons
+ break
+ } else {
+ decision.TranscodeReasons = append(decision.TranscodeReasons, reason)
+ }
+ }
+ }
+
+ // If direct play is possible, we're done
+ if decision.CanDirectPlay {
+ log.Debug(ctx, "Transcode decision: direct play", "mediaID", mf.ID, "container", src.Container, "codec", src.Codec)
+ return decision, nil
+ }
+
+ // Try transcoding profiles (in order of preference)
+ for _, profile := range clientInfo.TranscodingProfiles {
+ if ts, transcodeFormat := s.computeTranscodedStream(ctx, src, &profile, clientInfo); ts != nil {
+ decision.CanTranscode = true
+ decision.TargetFormat = transcodeFormat
+ decision.TargetBitrate = ts.Bitrate
+ decision.TargetChannels = ts.Channels
+ decision.TargetSampleRate = ts.SampleRate
+ decision.TargetBitDepth = ts.BitDepth
+ decision.TranscodeStream = ts
+ break
+ }
+ }
+
+ if decision.CanTranscode {
+ log.Debug(ctx, "Transcode decision: transcode", "mediaID", mf.ID,
+ "targetFormat", decision.TargetFormat, "targetBitrate", decision.TargetBitrate,
+ "targetChannels", decision.TargetChannels, "reasons", decision.TranscodeReasons)
+ }
+
+ // If neither direct play nor transcode is possible
+ if !decision.CanDirectPlay && !decision.CanTranscode {
+ decision.ErrorReason = "no compatible playback profile found"
+ log.Warn(ctx, "Transcode decision: no compatible profile", "mediaID", mf.ID,
+ "container", src.Container, "codec", src.Codec, "reasons", decision.TranscodeReasons)
+ }
+
+ return decision, nil
+}
+
+func buildSourceStream(mf *model.MediaFile, probe *ffmpeg.AudioProbeResult) Details {
+ sd := Details{
+ Container: mf.Suffix,
+ Duration: mf.Duration,
+ Size: mf.Size,
+ }
+
+ // Use pre-parsed probe result, or fall back to parsing stored probe data
+ if probe == nil {
+ probe, _ = parseProbeData(mf.ProbeData)
+ }
+
+ // Use probe data if available for authoritative values
+ if probe != nil {
+ sd.Codec = normalizeProbeCodec(probe.Codec)
+ sd.Profile = probe.Profile
+ sd.Bitrate = probe.BitRate
+ sd.SampleRate = probe.SampleRate
+ sd.BitDepth = probe.BitDepth
+ sd.Channels = probe.Channels
+ } else {
+ sd.Codec = mf.AudioCodec()
+ sd.Bitrate = mf.BitRate
+ sd.SampleRate = mf.SampleRate
+ sd.BitDepth = mf.BitDepth
+ sd.Channels = mf.Channels
+ }
+ sd.IsLossless = isLosslessFormat(sd.Codec)
+
+ return sd
+}
+
+// applyServerOverride replaces the client-provided profiles with synthetic ones
+// matching the server-forced transcoding format and bitrate.
+func applyServerOverride(ctx context.Context, original *ClientInfo, trc *model.Transcoding) *ClientInfo {
+ maxBitRate := trc.DefaultBitRate
+ if player, ok := request.PlayerFrom(ctx); ok && player.MaxBitRate > 0 {
+ maxBitRate = player.MaxBitRate
+ }
+
+ log.Debug(ctx, "Applying server-side transcoding override",
+ "targetFormat", trc.TargetFormat, "maxBitRate", maxBitRate,
+ "client", original.Name)
+
+ return &ClientInfo{
+ Name: original.Name,
+ Platform: original.Platform,
+ MaxAudioBitrate: maxBitRate,
+ MaxTranscodingAudioBitrate: maxBitRate,
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{trc.TargetFormat}, AudioCodecs: []string{trc.TargetFormat}, Protocols: []string{ProtocolHTTP}},
+ },
+ TranscodingProfiles: []Profile{
+ {Container: trc.TargetFormat, AudioCodec: trc.TargetFormat, Protocol: ProtocolHTTP},
+ },
+ }
+}
+
+func parseProbeData(data string) (*ffmpeg.AudioProbeResult, error) {
+ if data == "" {
+ return nil, nil
+ }
+ var result ffmpeg.AudioProbeResult
+ if err := json.Unmarshal([]byte(data), &result); err != nil {
+ return nil, err
+ }
+ return &result, nil
+}
+
+// checkDirectPlayProfile returns "" if the profile matches (direct play OK),
+// or a typed reason string if it doesn't match.
+func (s *deciderService) checkDirectPlayProfile(src *Details, profile *DirectPlayProfile, clientInfo *ClientInfo) string {
+ // Check protocol (only http for now)
+ if len(profile.Protocols) > 0 && !containsIgnoreCase(profile.Protocols, ProtocolHTTP) {
+ return "protocol not supported"
+ }
+
+ // Check container
+ if len(profile.Containers) > 0 && !matchesContainer(src.Container, profile.Containers) {
+ return "container not supported"
+ }
+
+ // Check codec
+ if len(profile.AudioCodecs) > 0 && !matchesCodec(src.Codec, profile.AudioCodecs) {
+ return "audio codec not supported"
+ }
+
+ // Check channels
+ if profile.MaxAudioChannels > 0 && src.Channels > profile.MaxAudioChannels {
+ return "audio channels not supported"
+ }
+
+ // Check codec-specific limitations
+ for _, codecProfile := range clientInfo.CodecProfiles {
+ if strings.EqualFold(codecProfile.Type, CodecProfileTypeAudio) && matchesCodec(src.Codec, []string{codecProfile.Name}) {
+ if reason := checkLimitations(src, codecProfile.Limitations); reason != "" {
+ return reason
+ }
+ }
+ }
+
+ return ""
+}
+
+// computeTranscodedStream attempts to build a valid transcoded stream for the given profile.
+// Returns the stream details and the internal transcoding format (which may differ from the
+// response container when a codec fallback occurs, e.g., "mp4"→"aac").
+// Returns nil, "" if the profile cannot produce a valid output.
+func (s *deciderService) computeTranscodedStream(ctx context.Context, src *Details, profile *Profile, clientInfo *ClientInfo) (*Details, string) {
+ // Check protocol (only http for now)
+ if profile.Protocol != "" && !strings.EqualFold(profile.Protocol, ProtocolHTTP) {
+ log.Trace(ctx, "Skipping transcoding profile: unsupported protocol", "protocol", profile.Protocol)
+ return nil, ""
+ }
+
+ responseContainer, targetFormat := resolveTargetFormat(profile)
+ if targetFormat == "" {
+ return nil, ""
+ }
+
+ // Verify we have a transcoding command available (DB custom or built-in default)
+ if LookupTranscodeCommand(ctx, s.ds, targetFormat) == "" {
+ log.Trace(ctx, "Skipping transcoding profile: no transcoding command available", "targetFormat", targetFormat)
+ return nil, ""
+ }
+
+ targetIsLossless := isLosslessFormat(targetFormat)
+
+ // Reject lossy to lossless conversion
+ if !src.IsLossless && targetIsLossless {
+ log.Trace(ctx, "Skipping transcoding profile: lossy to lossless not allowed", "targetFormat", targetFormat)
+ return nil, ""
+ }
+
+ ts := &Details{
+ Container: responseContainer,
+ Codec: strings.ToLower(profile.AudioCodec),
+ SampleRate: normalizeSourceSampleRate(src.SampleRate, src.Codec),
+ Channels: src.Channels,
+ BitDepth: normalizeSourceBitDepth(src.BitDepth, src.Codec),
+ IsLossless: targetIsLossless,
+ }
+ if ts.Codec == "" {
+ ts.Codec = targetFormat
+ }
+
+ // Apply codec-intrinsic sample rate adjustments before codec profile limitations
+ if fixedRate := codecFixedOutputSampleRate(ts.Codec); fixedRate > 0 {
+ ts.SampleRate = fixedRate
+ }
+ if maxRate := codecMaxSampleRate(ts.Codec); maxRate > 0 && ts.SampleRate > maxRate {
+ ts.SampleRate = maxRate
+ }
+
+ // Determine target bitrate (all in kbps)
+ if ok := s.computeBitrate(ctx, src, targetFormat, targetIsLossless, clientInfo, ts); !ok {
+ return nil, ""
+ }
+
+ // Apply MaxAudioChannels from the transcoding profile
+ if profile.MaxAudioChannels > 0 && src.Channels > profile.MaxAudioChannels {
+ ts.Channels = profile.MaxAudioChannels
+ }
+
+ // Apply codec profile limitations to the TARGET codec
+ if ok := s.applyCodecLimitations(ctx, src.Bitrate, targetFormat, targetIsLossless, clientInfo, ts); !ok {
+ return nil, ""
+ }
+
+ return ts, targetFormat
+}
+
+// lookupDefaultBitrate returns the default bitrate for the given format.
+// It checks the DB first (for user-customized values), then falls back to
+// the built-in defaults, and finally to fallbackBitrate.
+func lookupDefaultBitrate(ctx context.Context, ds model.DataStore, format string) int {
+ if t, err := ds.Transcoding(ctx).FindByFormat(format); err == nil && t.DefaultBitRate > 0 {
+ return t.DefaultBitRate
+ }
+ for _, dt := range consts.DefaultTranscodings {
+ if dt.TargetFormat == format && dt.DefaultBitRate > 0 {
+ return dt.DefaultBitRate
+ }
+ }
+ return fallbackBitrate
+}
+
+// LookupTranscodeCommand returns the ffmpeg command for the given format.
+// It checks the DB first (for user-customized commands), then falls back to
+// the built-in default command. Returns "" if the format is unknown.
+func LookupTranscodeCommand(ctx context.Context, ds model.DataStore, format string) string {
+ t, err := ds.Transcoding(ctx).FindByFormat(format)
+ if err == nil && t.Command != "" {
+ return t.Command
+ }
+ // Fall back to built-in defaults
+ for _, dt := range consts.DefaultTranscodings {
+ if dt.TargetFormat == format {
+ return dt.Command
+ }
+ }
+ return ""
+}
+
+// resolveTargetFormat determines the response container and internal target format
+// from the profile's Container and AudioCodec fields. When an AudioCodec is specified
+// it is preferred as targetFormat (e.g. container "mp4" with audioCodec "aac" → targetFormat "aac").
+func resolveTargetFormat(profile *Profile) (responseContainer, targetFormat string) {
+ responseContainer = strings.ToLower(profile.Container)
+ targetFormat = responseContainer
+
+ // Prefer the audioCodec as targetFormat when provided (handles container-to-codec
+ // mapping like "mp4" → "aac", "ogg" → "opus").
+ if profile.AudioCodec != "" {
+ targetFormat = strings.ToLower(profile.AudioCodec)
+ }
+
+ // If neither container nor audioCodec is set, we can't resolve a format.
+ if targetFormat == "" {
+ return "", ""
+ }
+
+ // When no container was specified, use the targetFormat as container too.
+ if responseContainer == "" {
+ responseContainer = targetFormat
+ }
+
+ return responseContainer, targetFormat
+}
+
+// computeBitrate determines the target bitrate for the transcoded stream.
+// Returns false if the profile should be rejected.
+func (s *deciderService) computeBitrate(ctx context.Context, src *Details, targetFormat string, targetIsLossless bool, clientInfo *ClientInfo, ts *Details) bool {
+ if src.IsLossless {
+ if !targetIsLossless {
+ if clientInfo.MaxTranscodingAudioBitrate > 0 {
+ ts.Bitrate = clientInfo.MaxTranscodingAudioBitrate
+ } else if clientInfo.MaxAudioBitrate > 0 {
+ ts.Bitrate = clientInfo.MaxAudioBitrate
+ } else {
+ ts.Bitrate = lookupDefaultBitrate(ctx, s.ds, targetFormat)
+ }
+ } else {
+ if clientInfo.MaxAudioBitrate > 0 && src.Bitrate > clientInfo.MaxAudioBitrate {
+ log.Trace(ctx, "Skipping transcoding profile: lossless target exceeds bitrate limit",
+ "targetFormat", targetFormat, "sourceBitrate", src.Bitrate, "maxAudioBitrate", clientInfo.MaxAudioBitrate)
+ return false
+ }
+ }
+ } else {
+ ts.Bitrate = src.Bitrate
+ }
+
+ // Apply maxAudioBitrate as final cap
+ if clientInfo.MaxAudioBitrate > 0 && ts.Bitrate > 0 && ts.Bitrate > clientInfo.MaxAudioBitrate {
+ ts.Bitrate = clientInfo.MaxAudioBitrate
+ }
+ return true
+}
+
+// applyCodecLimitations applies codec profile limitations to the transcoded stream.
+// Returns false if the profile should be rejected.
+func (s *deciderService) applyCodecLimitations(ctx context.Context, sourceBitrate int, targetFormat string, targetIsLossless bool, clientInfo *ClientInfo, ts *Details) bool {
+ targetCodec := ts.Codec
+ for _, codecProfile := range clientInfo.CodecProfiles {
+ if !strings.EqualFold(codecProfile.Type, CodecProfileTypeAudio) {
+ continue
+ }
+ if !matchesCodec(targetCodec, []string{codecProfile.Name}) {
+ continue
+ }
+ for _, lim := range codecProfile.Limitations {
+ result := applyLimitation(sourceBitrate, &lim, ts)
+ if strings.EqualFold(lim.Name, LimitationAudioBitrate) && targetIsLossless && result == adjustAdjusted {
+ log.Trace(ctx, "Skipping transcoding profile: cannot adjust bitrate for lossless target",
+ "targetFormat", targetFormat, "codec", targetCodec, "limitation", lim.Name)
+ return false
+ }
+ if result == adjustCannotFit {
+ log.Trace(ctx, "Skipping transcoding profile: codec limitation cannot be satisfied",
+ "targetFormat", targetFormat, "codec", targetCodec, "limitation", lim.Name,
+ "comparison", lim.Comparison, "values", lim.Values)
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// ensureProbed runs ffprobe if probe data is missing, persists it, and returns
+// the parsed result. Returns (nil, nil) when probing is skipped or data already exists
+// (in which case the caller should parse mf.ProbeData).
+func (s *deciderService) ensureProbed(ctx context.Context, mf *model.MediaFile) (*ffmpeg.AudioProbeResult, error) {
+ if mf.ProbeData != "" {
+ return nil, nil
+ }
+ if !conf.Server.DevEnableMediaFileProbe {
+ return nil, nil
+ }
+
+ result, err := s.ff.ProbeAudioStream(ctx, mf.AbsolutePath())
+ if err != nil {
+ return nil, fmt.Errorf("probing media file %s: %w", mf.ID, err)
+ }
+
+ data, err := json.Marshal(result)
+ if err != nil {
+ return nil, fmt.Errorf("marshaling probe result for %s: %w", mf.ID, err)
+ }
+ mf.ProbeData = string(data)
+
+ if err := s.ds.MediaFile(ctx).UpdateProbeData(mf.ID, mf.ProbeData); err != nil {
+ log.Error(ctx, "Failed to persist probe data", "mediaID", mf.ID, err)
+ // Don't fail the decision — we have the data in memory
+ }
+
+ log.Debug(ctx, "Probed media file", "mediaID", mf.ID, "codec", result.Codec,
+ "profile", result.Profile, "bitRate", result.BitRate,
+ "sampleRate", result.SampleRate, "bitDepth", result.BitDepth, "channels", result.Channels)
+ return result, nil
+}
diff --git a/core/stream/decider_test.go b/core/stream/decider_test.go
new file mode 100644
index 000000000..42ebd84f1
--- /dev/null
+++ b/core/stream/decider_test.go
@@ -0,0 +1,1190 @@
+package stream
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/core/auth"
+ "github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+// withProbe pre-populates ProbeData on a MediaFile from its own fields,
+// so ensureProbed short-circuits and tests don't need mock ffprobe results.
+func withProbe(mf *model.MediaFile) *model.MediaFile {
+ probe := ffmpeg.AudioProbeResult{
+ Codec: mf.AudioCodec(),
+ BitRate: mf.BitRate,
+ SampleRate: mf.SampleRate,
+ BitDepth: mf.BitDepth,
+ Channels: mf.Channels,
+ }
+ data, _ := json.Marshal(probe)
+ mf.ProbeData = string(data)
+ return mf
+}
+
+var _ = Describe("Decider", func() {
+ var (
+ ds *tests.MockDataStore
+ ff *tests.MockFFmpeg
+ svc TranscodeDecider
+ ctx context.Context
+ )
+
+ BeforeEach(func() {
+ ctx = GinkgoT().Context()
+ ds = &tests.MockDataStore{
+ MockedProperty: &tests.MockedPropertyRepo{},
+ MockedTranscoding: &tests.MockTranscodingRepo{},
+ }
+ ff = tests.NewMockFFmpeg("")
+ auth.Init(ds)
+ svc = NewTranscodeDecider(ds, ff)
+ })
+
+ Describe("MakeDecision", func() {
+ Context("Direct Play", func() {
+ It("allows direct play when profile matches", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp3"}, AudioCodecs: []string{"mp3"}, Protocols: []string{ProtocolHTTP}, MaxAudioChannels: 2},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ Expect(decision.CanTranscode).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(BeEmpty())
+ })
+
+ It("rejects direct play when container doesn't match", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp3"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(ContainElement("container not supported"))
+ })
+
+ It("rejects direct play when codec doesn't match", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "m4a", Codec: "ALAC", BitRate: 1000, Channels: 2})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"m4a"}, AudioCodecs: []string{"aac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(ContainElement("audio codec not supported"))
+ })
+
+ It("rejects direct play when channels exceed limit", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 6})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}, MaxAudioChannels: 2},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(ContainElement("audio channels not supported"))
+ })
+
+ It("handles container aliases (aac -> m4a)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "m4a", Codec: "AAC", BitRate: 256, Channels: 2})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"aac"}, AudioCodecs: []string{"aac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("handles container aliases (mp4 -> m4a)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "m4a", Codec: "AAC", BitRate: 256, Channels: 2})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp4"}, AudioCodecs: []string{"aac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("handles container aliases (opus -> ogg)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "opus", Codec: "Opus", BitRate: 165, Channels: 2, SampleRate: 48000})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"ogg"}, AudioCodecs: []string{"opus"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("handles codec aliases (adts -> aac)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "m4a", Codec: "AAC", BitRate: 256, Channels: 2})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"m4a"}, AudioCodecs: []string{"adts"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("allows when protocol list is empty (any protocol)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, AudioCodecs: []string{"flac"}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("allows when both container and codec lists are empty (wildcard)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 128, Channels: 2})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{}, AudioCodecs: []string{}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+ })
+
+ Context("MaxAudioBitrate constraint", func() {
+ It("revokes direct play when bitrate exceeds maxAudioBitrate", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1500, Channels: 2})
+ ci := &ClientInfo{
+ MaxAudioBitrate: 500, // kbps
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeReasons).To(ContainElement("audio bitrate not supported"))
+ })
+ })
+
+ Context("Transcoding", func() {
+ It("selects transcoding when direct play isn't possible", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 256, // kbps
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp3"}, Protocols: []string{ProtocolHTTP}},
+ },
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP, MaxAudioChannels: 2},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ Expect(decision.TargetBitrate).To(Equal(256)) // kbps
+ Expect(decision.TranscodeReasons).To(ContainElement("container not supported"))
+ })
+
+ It("rejects lossy to lossless transcoding", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "flac", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeFalse())
+ })
+
+ It("uses default bitrate when client doesn't specify", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, BitDepth: 16})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetBitrate).To(Equal(160)) // mp3 default from mock transcoding repo
+ })
+
+ It("preserves lossy bitrate when under max", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "ogg", BitRate: 192, Channels: 2})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 256, // kbps
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetBitrate).To(Equal(192)) // source bitrate in kbps
+ })
+
+ It("rejects format with no transcoding command available", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "wav", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeFalse())
+ })
+
+ It("applies maxAudioBitrate as final cap on transcoded stream", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2})
+ ci := &ClientInfo{
+ MaxAudioBitrate: 96, // kbps
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetBitrate).To(Equal(96)) // capped by maxAudioBitrate
+ })
+
+ It("selects first valid transcoding profile in order", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 48000, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp3"}, Protocols: []string{ProtocolHTTP}},
+ },
+ TranscodingProfiles: []Profile{
+ {Container: "opus", AudioCodec: "opus", Protocol: ProtocolHTTP},
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP, MaxAudioChannels: 2},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("opus"))
+ })
+ })
+
+ Context("Lossless to lossless transcoding", func() {
+ It("allows lossless to lossless when samplerate needs downsampling", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 176400, BitDepth: 1})
+ ci := &ClientInfo{
+ MaxAudioBitrate: 1000,
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ })
+
+ It("sets IsLossless=true on transcoded stream when target is lossless", func() {
+ // Transcoding to mp3 (lossy) should result in IsLossless=false.
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 96000, BitDepth: 24})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.IsLossless).To(BeFalse()) // mp3 is lossy
+ })
+ })
+
+ Context("No compatible profile", func() {
+ It("returns error when nothing matches", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 6})
+ ci := &ClientInfo{}
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.CanTranscode).To(BeFalse())
+ Expect(decision.ErrorReason).To(Equal("no compatible playback profile found"))
+ })
+ })
+
+ Context("Codec limitations on direct play", func() {
+ It("rejects direct play when codec limitation fails (required)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 512, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp3"}, AudioCodecs: []string{"mp3"}, Protocols: []string{ProtocolHTTP}},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "mp3",
+ Limitations: []Limitation{
+ {Name: LimitationAudioBitrate, Comparison: ComparisonLessThanEqual, Values: []string{"320"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(ContainElement("audio bitrate not supported"))
+ })
+
+ It("allows direct play when optional limitation fails", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 512, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp3"}, AudioCodecs: []string{"mp3"}, Protocols: []string{ProtocolHTTP}},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "mp3",
+ Limitations: []Limitation{
+ {Name: LimitationAudioBitrate, Comparison: ComparisonLessThanEqual, Values: []string{"320"}, Required: false},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("handles Equals comparison with multiple values", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "flac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioChannels, Comparison: ComparisonEquals, Values: []string{"1", "2"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("rejects when Equals comparison doesn't match any value", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 6, SampleRate: 44100})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "flac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioChannels, Comparison: ComparisonEquals, Values: []string{"1", "2"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ })
+
+ It("rejects direct play when audioProfile limitation fails (required)", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "m4a", Codec: "AAC", BitRate: 256, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"m4a"}, AudioCodecs: []string{"aac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "aac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioProfile, Comparison: ComparisonEquals, Values: []string{"LC"}, Required: true},
+ },
+ },
+ },
+ }
+ // Source profile is empty (not yet populated from scanner), so Equals("LC") fails
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(ContainElement("audio profile not supported"))
+ })
+
+ It("allows direct play when audioProfile limitation is optional", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "m4a", Codec: "AAC", BitRate: 256, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"m4a"}, AudioCodecs: []string{"aac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "aac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioProfile, Comparison: ComparisonEquals, Values: []string{"LC"}, Required: false},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ It("rejects direct play due to samplerate limitation", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 96000, BitDepth: 24})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "flac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioSamplerate, Comparison: ComparisonLessThanEqual, Values: []string{"48000"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(ContainElement("audio samplerate not supported"))
+ })
+ })
+
+ Context("Codec limitations on transcoded output", func() {
+ It("applies bitrate limitation to transcoded stream", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 192, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ MaxAudioBitrate: 96, // force transcode
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "mp3",
+ Limitations: []Limitation{
+ {Name: LimitationAudioBitrate, Comparison: ComparisonLessThanEqual, Values: []string{"96"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.Bitrate).To(Equal(96))
+ })
+
+ It("applies channel limitation to transcoded stream", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 6, SampleRate: 48000, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "mp3",
+ Limitations: []Limitation{
+ {Name: LimitationAudioChannels, Comparison: ComparisonLessThanEqual, Values: []string{"2"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.Channels).To(Equal(2))
+ })
+
+ It("applies samplerate limitation to transcoded stream", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 96000, BitDepth: 24})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "mp3",
+ Limitations: []Limitation{
+ {Name: LimitationAudioSamplerate, Comparison: ComparisonLessThanEqual, Values: []string{"48000"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(48000))
+ })
+
+ It("applies bitdepth limitation to transcoded stream", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 96000, BitDepth: 24})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "flac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioBitdepth, Comparison: ComparisonLessThanEqual, Values: []string{"16"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.BitDepth).To(Equal(16))
+ Expect(decision.TargetBitDepth).To(Equal(16))
+ })
+
+ It("preserves source bit depth when no limitation applies", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 24})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.BitDepth).To(Equal(24))
+ Expect(decision.TargetBitDepth).To(Equal(24))
+ })
+
+ It("rejects transcoding profile when GreaterThanEqual cannot be satisfied", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "mp3",
+ Limitations: []Limitation{
+ {Name: LimitationAudioSamplerate, Comparison: ComparisonGreaterThanEqual, Values: []string{"96000"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeFalse())
+ })
+ })
+
+ Context("DSD sample rate conversion", func() {
+ It("converts DSD sample rate to PCM-equivalent in decision", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: 1})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ // DSD64 2822400 / 8 = 352800, capped by MP3 max of 48000
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(48000))
+ Expect(decision.TargetSampleRate).To(Equal(48000))
+ // DSD 1-bit → 24-bit PCM
+ Expect(decision.TranscodeStream.BitDepth).To(Equal(24))
+ Expect(decision.TargetBitDepth).To(Equal(24))
+ })
+
+ It("converts DSD sample rate for FLAC target without codec limit", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: 1})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("flac"))
+ // DSD64 2822400 / 8 = 352800, FLAC has no hard max
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(352800))
+ Expect(decision.TargetSampleRate).To(Equal(352800))
+ // DSD 1-bit → 24-bit PCM
+ Expect(decision.TranscodeStream.BitDepth).To(Equal(24))
+ Expect(decision.TargetBitDepth).To(Equal(24))
+ })
+
+ It("applies codec profile limit to DSD-converted FLAC sample rate", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: 1})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "flac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioSamplerate, Comparison: ComparisonLessThanEqual, Values: []string{"48000"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ // DSD64 2822400 / 8 = 352800, capped by codec profile limit of 48000
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(48000))
+ Expect(decision.TargetSampleRate).To(Equal(48000))
+ // DSD 1-bit → 24-bit PCM
+ Expect(decision.TranscodeStream.BitDepth).To(Equal(24))
+ Expect(decision.TargetBitDepth).To(Equal(24))
+ })
+
+ It("applies audioBitdepth limitation to DSD-converted bit depth", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: 1})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP},
+ },
+ CodecProfiles: []CodecProfile{
+ {
+ Type: CodecProfileTypeAudio,
+ Name: "flac",
+ Limitations: []Limitation{
+ {Name: LimitationAudioBitdepth, Comparison: ComparisonLessThanEqual, Values: []string{"16"}, Required: true},
+ },
+ },
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ // DSD 1-bit → 24-bit PCM, then capped by codec profile limit to 16-bit
+ Expect(decision.TranscodeStream.BitDepth).To(Equal(16))
+ Expect(decision.TargetBitDepth).To(Equal(16))
+ })
+ })
+
+ Context("Probe-based lossless detection", func() {
+ It("uses probe codec name for lossless detection", func() {
+ // WavPack files: ffprobe reports codec as "wavpack", suffix is ".wv"
+ mf := &model.MediaFile{ID: "1", Suffix: "wv", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16}
+ probe := ffmpeg.AudioProbeResult{
+ Codec: "wavpack", BitRate: 1000, SampleRate: 44100, BitDepth: 16, Channels: 2,
+ }
+ data, _ := json.Marshal(probe)
+ mf.ProbeData = string(data)
+
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ MaxTranscodingAudioBitrate: 256,
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.SourceStream.IsLossless).To(BeTrue())
+ Expect(decision.SourceStream.Codec).To(Equal("wavpack"))
+ // Lossless source transcoding to MP3 should use MaxTranscodingAudioBitrate
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.Bitrate).To(Equal(256))
+ })
+
+ It("detects lossy from probe codec name", func() {
+ mf := &model.MediaFile{ID: "1", Suffix: "ogg", BitRate: 192, Channels: 2, SampleRate: 48000}
+ probe := ffmpeg.AudioProbeResult{
+ Codec: "vorbis", BitRate: 192, SampleRate: 48000, BitDepth: 0, Channels: 2,
+ }
+ data, _ := json.Marshal(probe)
+ mf.ProbeData = string(data)
+
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"ogg"}, AudioCodecs: []string{"vorbis"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.SourceStream.IsLossless).To(BeFalse())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+ })
+
+ Context("Opus fixed sample rate", func() {
+ It("sets Opus output to 48000Hz regardless of input", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 128,
+ TranscodingProfiles: []Profile{
+ {Container: "opus", AudioCodec: "opus", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("opus"))
+ // Opus always outputs 48000Hz
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(48000))
+ Expect(decision.TargetSampleRate).To(Equal(48000))
+ })
+
+ It("sets Opus output to 48000Hz even for 96kHz input", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1500, Channels: 2, SampleRate: 96000, BitDepth: 24})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 128,
+ TranscodingProfiles: []Profile{
+ {Container: "opus", AudioCodec: "opus", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(48000))
+ })
+ })
+
+ Context("Container vs format separation", func() {
+ It("preserves mp4 container when falling back to aac format", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 256,
+ TranscodingProfiles: []Profile{
+ {Container: "mp4", AudioCodec: "aac", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ // TargetFormat is the internal format used for transcoding ("aac")
+ Expect(decision.TargetFormat).To(Equal("aac"))
+ // Container in the response preserves what the client asked ("mp4")
+ Expect(decision.TranscodeStream.Container).To(Equal("mp4"))
+ Expect(decision.TranscodeStream.Codec).To(Equal("aac"))
+ })
+
+ It("uses container as format when container matches transcoding config", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 256,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ Expect(decision.TranscodeStream.Container).To(Equal("mp3"))
+ })
+ })
+
+ Context("MP3 max sample rate", func() {
+ It("caps sample rate at 48000 for MP3", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1500, Channels: 2, SampleRate: 96000, BitDepth: 24})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(48000))
+ })
+
+ It("preserves sample rate at 44100 for MP3", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(44100))
+ })
+ })
+
+ Context("AAC max sample rate", func() {
+ It("caps sample rate at 96000 for AAC", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: 1})
+ ci := &ClientInfo{
+ MaxTranscodingAudioBitrate: 320,
+ TranscodingProfiles: []Profile{
+ {Container: "aac", AudioCodec: "aac", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ // DSD64 2822400 / 8 = 352800, capped by AAC max of 96000
+ Expect(decision.TranscodeStream.SampleRate).To(Equal(96000))
+ })
+ })
+
+ Context("Typed transcode reasons from multiple profiles", func() {
+ It("collects reasons from each failed direct play profile", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "ogg", Codec: "Vorbis", BitRate: 128, Channels: 2, SampleRate: 48000})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ {Containers: []string{"mp3"}, AudioCodecs: []string{"mp3"}, Protocols: []string{ProtocolHTTP}},
+ {Containers: []string{"m4a", "mp4"}, AudioCodecs: []string{"aac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.TranscodeReasons).To(HaveLen(3))
+ Expect(decision.TranscodeReasons[0]).To(Equal("container not supported"))
+ Expect(decision.TranscodeReasons[1]).To(Equal("container not supported"))
+ Expect(decision.TranscodeReasons[2]).To(Equal("container not supported"))
+ })
+ })
+
+ Context("Source stream details", func() {
+ It("populates source stream correctly with kbps bitrate", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 96000, BitDepth: 24, Duration: 300.5, Size: 50000000})
+ ci := &ClientInfo{
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.SourceStream.Container).To(Equal("flac"))
+ Expect(decision.SourceStream.Codec).To(Equal("flac"))
+ Expect(decision.SourceStream.Bitrate).To(Equal(1000)) // kbps
+ Expect(decision.SourceStream.SampleRate).To(Equal(96000))
+ Expect(decision.SourceStream.BitDepth).To(Equal(24))
+ Expect(decision.SourceStream.Channels).To(Equal(2))
+ })
+ })
+
+ Context("Server-side player transcoding override", func() {
+ It("forces transcoding when override targets a different format", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ // Set server override in context
+ overrideCtx := request.WithTranscoding(ctx, model.Transcoding{TargetFormat: "mp3", DefaultBitRate: 192})
+ overrideCtx = request.WithPlayer(overrideCtx, model.Player{MaxBitRate: 0})
+
+ decision, err := svc.MakeDecision(overrideCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ Expect(decision.TargetBitrate).To(Equal(192))
+ })
+
+ It("allows direct play when source matches forced format and bitrate is within cap", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 128, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ overrideCtx := request.WithTranscoding(ctx, model.Transcoding{TargetFormat: "mp3", DefaultBitRate: 256})
+
+ decision, err := svc.MakeDecision(overrideCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ Expect(decision.CanTranscode).To(BeFalse())
+ })
+
+ It("transcodes when source bitrate exceeds the forced cap", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ }
+ overrideCtx := request.WithTranscoding(ctx, model.Transcoding{TargetFormat: "mp3", DefaultBitRate: 192})
+
+ decision, err := svc.MakeDecision(overrideCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ Expect(decision.TargetBitrate).To(Equal(192))
+ })
+
+ It("uses player MaxBitRate over transcoding DefaultBitRate", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ }
+ overrideCtx := request.WithTranscoding(ctx, model.Transcoding{TargetFormat: "mp3", DefaultBitRate: 192})
+ overrideCtx = request.WithPlayer(overrideCtx, model.Player{MaxBitRate: 320})
+
+ decision, err := svc.MakeDecision(overrideCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ Expect(decision.TargetBitrate).To(Equal(320))
+ })
+
+ It("applies no bitrate cap when both MaxBitRate and DefaultBitRate are 0", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ }
+ overrideCtx := request.WithTranscoding(ctx, model.Transcoding{TargetFormat: "mp3", DefaultBitRate: 0})
+ overrideCtx = request.WithPlayer(overrideCtx, model.Player{MaxBitRate: 0})
+
+ decision, err := svc.MakeDecision(overrideCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetFormat).To(Equal("mp3"))
+ // With no cap, lossless→lossy uses format default bitrate (160 for mp3 from mock)
+ Expect(decision.TargetBitrate).To(Equal(160))
+ })
+
+ It("does not apply override when no transcoding is in context", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ // No override in context — client profiles used as-is
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+
+ })
+
+ Context("Player MaxBitRate cap", func() {
+ It("applies player MaxBitRate cap when client has no limit", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"flac", "mp3"}, AudioCodecs: []string{"flac", "mp3"}, Protocols: []string{ProtocolHTTP}},
+ },
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ playerCtx := request.WithPlayer(ctx, model.Player{MaxBitRate: 320})
+
+ decision, err := svc.MakeDecision(playerCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ // Source bitrate 1000 > player cap 320, so direct play is not possible
+ Expect(decision.CanDirectPlay).To(BeFalse())
+ Expect(decision.CanTranscode).To(BeTrue())
+ // Lossless→lossy should use MaxAudioBitrate (320) as target, not format default
+ Expect(decision.TargetBitrate).To(Equal(320))
+ })
+
+ It("uses client limit when it is more restrictive than player MaxBitRate", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ MaxAudioBitrate: 256,
+ MaxTranscodingAudioBitrate: 256,
+ TranscodingProfiles: []Profile{
+ {Container: "mp3", AudioCodec: "mp3", Protocol: ProtocolHTTP},
+ },
+ }
+ playerCtx := request.WithPlayer(ctx, model.Player{MaxBitRate: 500})
+
+ decision, err := svc.MakeDecision(playerCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ // Client limit 256 < player cap 500, so player cap doesn't apply; client limit wins
+ Expect(decision.TargetBitrate).To(Equal(256))
+ })
+
+ It("does not cap when player MaxBitRate is 0", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+ ci := &ClientInfo{
+ Name: "TestClient",
+ DirectPlayProfiles: []DirectPlayProfile{
+ {Containers: []string{"mp3"}, AudioCodecs: []string{"mp3"}, Protocols: []string{ProtocolHTTP}},
+ },
+ }
+ playerCtx := request.WithPlayer(ctx, model.Player{MaxBitRate: 0})
+
+ decision, err := svc.MakeDecision(playerCtx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanDirectPlay).To(BeTrue())
+ })
+ })
+
+ Context("Format-aware default bitrate", func() {
+ It("uses opus default bitrate from DB", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 48000, BitDepth: 16})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "opus", AudioCodec: "opus", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetBitrate).To(Equal(96)) // opus default from mock
+ })
+
+ It("uses aac default bitrate from DB", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+ ci := &ClientInfo{
+ TranscodingProfiles: []Profile{
+ {Container: "aac", AudioCodec: "aac", Protocol: ProtocolHTTP},
+ },
+ }
+ decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(decision.CanTranscode).To(BeTrue())
+ Expect(decision.TargetBitrate).To(Equal(256)) // aac default from mock
+ })
+
+ It("falls back to 256 for unknown format", func() {
+ bitrate := lookupDefaultBitrate(ctx, ds, "xyz")
+ Expect(bitrate).To(Equal(fallbackBitrate))
+ })
+ })
+ })
+
+ Describe("ensureProbed", func() {
+ var mockMFRepo *tests.MockMediaFileRepo
+
+ BeforeEach(func() {
+ mockMFRepo = tests.CreateMockMediaFileRepo()
+ ds.MockedMediaFile = mockMFRepo
+ })
+
+ It("calls ffprobe and populates ProbeData when empty", func() {
+ mf := &model.MediaFile{ID: "probe-1", Suffix: "mp3", BitRate: 320, Channels: 2}
+ mockMFRepo.SetData(model.MediaFiles{*mf})
+
+ ff.ProbeAudioResult = &ffmpeg.AudioProbeResult{
+ Codec: "mp3", BitRate: 320, SampleRate: 44100, Channels: 2,
+ }
+
+ svc := NewTranscodeDecider(ds, ff).(*deciderService)
+ probe, err := svc.ensureProbed(ctx, mf)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mf.ProbeData).ToNot(BeEmpty())
+ Expect(probe).ToNot(BeNil())
+ Expect(probe.Codec).To(Equal("mp3"))
+ Expect(probe.BitRate).To(Equal(320))
+ Expect(probe.SampleRate).To(Equal(44100))
+ Expect(probe.Channels).To(Equal(2))
+
+ // Verify persisted to DB
+ stored := mockMFRepo.Data["probe-1"]
+ Expect(stored.ProbeData).To(Equal(mf.ProbeData))
+ })
+
+ It("skips ffprobe when ProbeData is already set", func() {
+ mf := withProbe(&model.MediaFile{ID: "probe-2", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2})
+
+ // Set error on mock — if ffprobe were called, this would fail
+ ff.Error = fmt.Errorf("should not be called")
+
+ svc := NewTranscodeDecider(ds, ff).(*deciderService)
+ probe, err := svc.ensureProbed(ctx, mf)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(probe).To(BeNil())
+ })
+
+ It("returns error when ffprobe fails", func() {
+ mf := &model.MediaFile{ID: "probe-3", Suffix: "mp3"}
+ ff.Error = fmt.Errorf("ffprobe not found")
+
+ svc := NewTranscodeDecider(ds, ff).(*deciderService)
+ _, err := svc.ensureProbed(ctx, mf)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("probing media file"))
+ Expect(mf.ProbeData).To(BeEmpty())
+ })
+
+ It("skips ffprobe when DevEnableMediaFileProbe is false", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DevEnableMediaFileProbe = false
+
+ mf := &model.MediaFile{ID: "probe-4", Suffix: "mp3"}
+ // Set a result — if ffprobe were called, ProbeData would be populated
+ ff.ProbeAudioResult = &ffmpeg.AudioProbeResult{Codec: "mp3"}
+
+ svc := NewTranscodeDecider(ds, ff).(*deciderService)
+ probe, err := svc.ensureProbed(ctx, mf)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(probe).To(BeNil())
+ Expect(mf.ProbeData).To(BeEmpty())
+ })
+ })
+
+})
diff --git a/core/stream/legacy_client.go b/core/stream/legacy_client.go
new file mode 100644
index 000000000..d6e929ec8
--- /dev/null
+++ b/core/stream/legacy_client.go
@@ -0,0 +1,101 @@
+package stream
+
+import (
+ "context"
+ "strings"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+)
+
+// buildLegacyClientInfo translates legacy Subsonic stream/download parameters
+// into a ClientInfo for use with MakeDecision.
+// It does NOT read request.TranscodingFrom(ctx) — that is handled by
+// MakeDecision's applyServerOverride.
+func buildLegacyClientInfo(mf *model.MediaFile, reqFormat string, reqBitRate int) *ClientInfo {
+ ci := &ClientInfo{Name: "legacy"}
+
+ // Determine target format for transcoding
+ var targetFormat string
+ switch {
+ case reqFormat != "":
+ targetFormat = reqFormat
+ case reqBitRate > 0 && reqBitRate < mf.BitRate && conf.Server.DefaultDownsamplingFormat != "":
+ targetFormat = conf.Server.DefaultDownsamplingFormat
+ }
+
+ if targetFormat != "" {
+ // Add a direct play profile for the source format when no explicit
+ // format was requested (bitrate-only downsampling) or when the
+ // requested format matches the source. When the client explicitly
+ // requests a different format, direct play must not match the
+ // source — otherwise the source is returned untranscoded.
+ if reqFormat == "" || strings.EqualFold(reqFormat, mf.Suffix) {
+ ci.DirectPlayProfiles = []DirectPlayProfile{
+ {Containers: []string{mf.Suffix}, AudioCodecs: []string{mf.AudioCodec()}, Protocols: []string{ProtocolHTTP}},
+ }
+ }
+ ci.TranscodingProfiles = []Profile{
+ {Container: targetFormat, AudioCodec: targetFormat, Protocol: ProtocolHTTP},
+ }
+ if reqBitRate > 0 {
+ ci.MaxAudioBitrate = reqBitRate
+ ci.MaxTranscodingAudioBitrate = reqBitRate
+ }
+ } else {
+ // No transcoding requested — direct play everything
+ ci.DirectPlayProfiles = []DirectPlayProfile{
+ {Protocols: []string{ProtocolHTTP}},
+ }
+ }
+
+ return ci
+}
+
+// ResolveRequest uses MakeDecision to resolve legacy Subsonic stream parameters
+// into a fully specified Request.
+func (s *deciderService) ResolveRequest(ctx context.Context, mf *model.MediaFile, reqFormat string, reqBitRate int, offset int) Request {
+ var req Request
+ req.Offset = offset
+
+ if reqFormat == "raw" {
+ req.Format = "raw"
+ return req
+ }
+
+ clientInfo := buildLegacyClientInfo(mf, reqFormat, reqBitRate)
+ decision, err := s.MakeDecision(ctx, mf, clientInfo, TranscodeOptions{SkipProbe: true})
+ if err != nil {
+ log.Error(ctx, "Error making transcode decision, falling back to raw", "id", mf.ID, err)
+ req.Format = "raw"
+ return req
+ }
+
+ if decision.CanDirectPlay {
+ req.Format = "raw"
+ return req
+ }
+
+ if decision.CanTranscode {
+ req.Format = decision.TargetFormat
+ req.BitRate = decision.TargetBitrate
+ req.SampleRate = decision.TargetSampleRate
+ req.BitDepth = decision.TargetBitDepth
+ req.Channels = decision.TargetChannels
+ return req
+ }
+
+ // No compatible profile for the requested format — retry with DefaultDownsamplingFormat
+ // TODO: validate DefaultDownsamplingFormat at startup to warn about unsupported values
+ fallbackFormat := conf.Server.DefaultDownsamplingFormat
+ if reqFormat != "" && fallbackFormat != "" && !strings.EqualFold(reqFormat, fallbackFormat) {
+ log.Warn(ctx, "Requested format not available, falling back to default downsampling format",
+ "requestedFormat", reqFormat, "fallbackFormat", fallbackFormat, "id", mf.ID)
+ return s.ResolveRequest(ctx, mf, fallbackFormat, reqBitRate, offset)
+ }
+
+ // Ultimate fallback — raw
+ req.Format = "raw"
+ return req
+}
diff --git a/core/stream/legacy_client_test.go b/core/stream/legacy_client_test.go
new file mode 100644
index 000000000..de1eb1339
--- /dev/null
+++ b/core/stream/legacy_client_test.go
@@ -0,0 +1,240 @@
+package stream
+
+import (
+ "context"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/core/auth"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("buildLegacyClientInfo", func() {
+ var mf *model.MediaFile
+
+ BeforeEach(func() {
+ mf = &model.MediaFile{Suffix: "flac", BitRate: 960}
+ })
+
+ It("sets transcoding profile for explicit format without bitrate", func() {
+ ci := buildLegacyClientInfo(mf, "mp3", 0)
+
+ Expect(ci.Name).To(Equal("legacy"))
+ Expect(ci.TranscodingProfiles).To(HaveLen(1))
+ Expect(ci.TranscodingProfiles[0].Container).To(Equal("mp3"))
+ Expect(ci.TranscodingProfiles[0].AudioCodec).To(Equal("mp3"))
+ Expect(ci.TranscodingProfiles[0].Protocol).To(Equal(ProtocolHTTP))
+ Expect(ci.MaxAudioBitrate).To(BeZero())
+ Expect(ci.MaxTranscodingAudioBitrate).To(BeZero())
+ Expect(ci.DirectPlayProfiles).To(BeEmpty())
+ })
+
+ It("does not add direct play profile when explicit format differs from source (no bitrate)", func() {
+ ci := buildLegacyClientInfo(mf, "opus", 0)
+
+ Expect(ci.TranscodingProfiles).To(HaveLen(1))
+ Expect(ci.TranscodingProfiles[0].Container).To(Equal("opus"))
+ Expect(ci.DirectPlayProfiles).To(BeEmpty())
+ })
+
+ It("adds direct play profile when explicit format matches source format", func() {
+ ci := buildLegacyClientInfo(mf, "flac", 0)
+
+ Expect(ci.TranscodingProfiles).To(HaveLen(1))
+ Expect(ci.TranscodingProfiles[0].Container).To(Equal("flac"))
+ Expect(ci.DirectPlayProfiles).To(HaveLen(1))
+ Expect(ci.DirectPlayProfiles[0].Containers).To(Equal([]string{"flac"}))
+ Expect(ci.DirectPlayProfiles[0].AudioCodecs).To(Equal([]string{mf.AudioCodec()}))
+ })
+
+ It("sets transcoding profile and bitrate for explicit format with bitrate", func() {
+ ci := buildLegacyClientInfo(mf, "mp3", 192)
+
+ Expect(ci.TranscodingProfiles).To(HaveLen(1))
+ Expect(ci.TranscodingProfiles[0].Container).To(Equal("mp3"))
+ Expect(ci.TranscodingProfiles[0].AudioCodec).To(Equal("mp3"))
+ Expect(ci.MaxAudioBitrate).To(Equal(192))
+ Expect(ci.MaxTranscodingAudioBitrate).To(Equal(192))
+ Expect(ci.DirectPlayProfiles).To(BeEmpty())
+ })
+
+ It("returns direct play profile when no format and no bitrate", func() {
+ ci := buildLegacyClientInfo(mf, "", 0)
+
+ Expect(ci.DirectPlayProfiles).To(HaveLen(1))
+ Expect(ci.DirectPlayProfiles[0].Containers).To(BeEmpty())
+ Expect(ci.DirectPlayProfiles[0].AudioCodecs).To(BeEmpty())
+ Expect(ci.DirectPlayProfiles[0].Protocols).To(Equal([]string{ProtocolHTTP}))
+ Expect(ci.TranscodingProfiles).To(BeEmpty())
+ Expect(ci.MaxAudioBitrate).To(BeZero())
+ })
+
+ It("uses default downsampling format for bitrate-only downsampling", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultDownsamplingFormat = "opus"
+
+ ci := buildLegacyClientInfo(mf, "", 128)
+
+ Expect(ci.TranscodingProfiles).To(HaveLen(1))
+ Expect(ci.TranscodingProfiles[0].Container).To(Equal("opus"))
+ Expect(ci.TranscodingProfiles[0].AudioCodec).To(Equal("opus"))
+ Expect(ci.TranscodingProfiles[0].Protocol).To(Equal(ProtocolHTTP))
+ Expect(ci.MaxAudioBitrate).To(Equal(128))
+ Expect(ci.MaxTranscodingAudioBitrate).To(Equal(128))
+ Expect(ci.DirectPlayProfiles).To(HaveLen(1))
+ Expect(ci.DirectPlayProfiles[0].Containers).To(Equal([]string{"flac"}))
+ Expect(ci.DirectPlayProfiles[0].AudioCodecs).To(Equal([]string{mf.AudioCodec()}))
+ })
+
+ It("returns direct play when bitrate >= source bitrate", func() {
+ ci := buildLegacyClientInfo(mf, "", 960)
+
+ Expect(ci.DirectPlayProfiles).To(HaveLen(1))
+ Expect(ci.DirectPlayProfiles[0].Containers).To(BeEmpty())
+ Expect(ci.DirectPlayProfiles[0].AudioCodecs).To(BeEmpty())
+ Expect(ci.DirectPlayProfiles[0].Protocols).To(Equal([]string{ProtocolHTTP}))
+ Expect(ci.TranscodingProfiles).To(BeEmpty())
+ Expect(ci.MaxAudioBitrate).To(BeZero())
+ })
+})
+
+var _ = Describe("ResolveRequest", func() {
+ var (
+ svc TranscodeDecider
+ ctx context.Context
+ )
+
+ BeforeEach(func() {
+ ctx = GinkgoT().Context()
+ ds := &tests.MockDataStore{
+ MockedProperty: &tests.MockedPropertyRepo{},
+ MockedTranscoding: &tests.MockTranscodingRepo{},
+ }
+ ff := tests.NewMockFFmpeg("")
+ auth.Init(ds)
+ svc = NewTranscodeDecider(ds, ff)
+ })
+
+ It("returns raw when format is 'raw'", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "raw", 0, 0)
+
+ Expect(req.Format).To(Equal("raw"))
+ })
+
+ It("returns raw (direct play) when no format or bitrate specified", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "", 0, 0)
+
+ Expect(req.Format).To(Equal("raw"))
+ })
+
+ It("transcodes to requested format", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "opus", 0, 0)
+
+ Expect(req.Format).To(Equal("opus"))
+ })
+
+ It("transcodes to requested format with bitrate limit", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "mp3", 128, 0)
+
+ Expect(req.Format).To(Equal("mp3"))
+ Expect(req.BitRate).To(Equal(128))
+ })
+
+ It("returns raw when requested format matches source and no bitrate reduction", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "mp3", 320, 0)
+
+ Expect(req.Format).To(Equal("raw"))
+ })
+
+ It("downsamples when only bitrate is specified below source", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultDownsamplingFormat = "opus"
+
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "", 128, 0)
+
+ Expect(req.Format).To(Equal("opus"))
+ Expect(req.BitRate).To(Equal(128))
+ })
+
+ It("passes offset through", func() {
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "opus", 128, 30)
+
+ Expect(req.Format).To(Equal("opus"))
+ Expect(req.Offset).To(Equal(30))
+ })
+
+ Context("fallback for unknown format", func() {
+ It("falls back to DefaultDownsamplingFormat", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultDownsamplingFormat = "opus"
+
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "xyz", 0, 0)
+
+ Expect(req.Format).To(Equal("opus"))
+ })
+
+ It("falls back to raw when DefaultDownsamplingFormat is empty", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultDownsamplingFormat = ""
+
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "xyz", 0, 0)
+
+ Expect(req.Format).To(Equal("raw"))
+ })
+
+ It("falls back to raw when DefaultDownsamplingFormat is also invalid", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultDownsamplingFormat = "xyz"
+
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "xyz", 0, 0)
+
+ Expect(req.Format).To(Equal("raw"))
+ })
+
+ It("preserves bitrate when falling back to DefaultDownsamplingFormat", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DefaultDownsamplingFormat = "opus"
+
+ mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: 16})
+
+ decider := svc.(*deciderService)
+ req := decider.ResolveRequest(ctx, mf, "xyz", 128, 0)
+
+ Expect(req.Format).To(Equal("opus"))
+ Expect(req.BitRate).To(Equal(128))
+ })
+ })
+})
diff --git a/core/stream/limitations.go b/core/stream/limitations.go
new file mode 100644
index 000000000..ab70d6c07
--- /dev/null
+++ b/core/stream/limitations.go
@@ -0,0 +1,171 @@
+package stream
+
+import (
+ "strconv"
+ "strings"
+)
+
+// adjustResult represents the outcome of applying a limitation to a transcoded stream value
+type adjustResult int
+
+const (
+ adjustNone adjustResult = iota // Value already satisfies the limitation
+ adjustAdjusted // Value was changed to fit the limitation
+ adjustCannotFit // Cannot satisfy the limitation (reject this profile)
+)
+
+// checkLimitations checks codec profile limitations against source stream details.
+// Returns "" if all limitations pass, or a typed reason string for the first failure.
+func checkLimitations(src *Details, limitations []Limitation) string {
+ for _, lim := range limitations {
+ var ok bool
+ var reason string
+
+ switch lim.Name {
+ case LimitationAudioChannels:
+ ok = checkIntLimitation(src.Channels, lim.Comparison, lim.Values)
+ reason = "audio channels not supported"
+ case LimitationAudioSamplerate:
+ ok = checkIntLimitation(src.SampleRate, lim.Comparison, lim.Values)
+ reason = "audio samplerate not supported"
+ case LimitationAudioBitrate:
+ ok = checkIntLimitation(src.Bitrate, lim.Comparison, lim.Values)
+ reason = "audio bitrate not supported"
+ case LimitationAudioBitdepth:
+ ok = checkIntLimitation(src.BitDepth, lim.Comparison, lim.Values)
+ reason = "audio bitdepth not supported"
+ case LimitationAudioProfile:
+ ok = checkStringLimitation(src.Profile, lim.Comparison, lim.Values)
+ reason = "audio profile not supported"
+ default:
+ continue
+ }
+
+ if !ok && lim.Required {
+ return reason
+ }
+ }
+ return ""
+}
+
+// applyLimitation adjusts a transcoded stream parameter to satisfy the limitation.
+// Returns the adjustment result.
+func applyLimitation(sourceBitrate int, lim *Limitation, ts *Details) adjustResult {
+ switch lim.Name {
+ case LimitationAudioChannels:
+ return applyIntLimitation(lim.Comparison, lim.Values, ts.Channels, func(v int) { ts.Channels = v })
+ case LimitationAudioBitrate:
+ current := ts.Bitrate
+ if current == 0 {
+ current = sourceBitrate
+ }
+ return applyIntLimitation(lim.Comparison, lim.Values, current, func(v int) { ts.Bitrate = v })
+ case LimitationAudioSamplerate:
+ return applyIntLimitation(lim.Comparison, lim.Values, ts.SampleRate, func(v int) { ts.SampleRate = v })
+ case LimitationAudioBitdepth:
+ if ts.BitDepth > 0 {
+ return applyIntLimitation(lim.Comparison, lim.Values, ts.BitDepth, func(v int) { ts.BitDepth = v })
+ }
+ case LimitationAudioProfile:
+ // TODO: implement when audio profile data is available
+ }
+ return adjustNone
+}
+
+// applyIntLimitation applies a limitation comparison to a value.
+// If the value needs adjusting, calls the setter and returns the result.
+func applyIntLimitation(comparison string, values []string, current int, setter func(int)) adjustResult {
+ if len(values) == 0 {
+ return adjustNone
+ }
+
+ switch comparison {
+ case ComparisonLessThanEqual:
+ limit, ok := parseInt(values[0])
+ if !ok {
+ return adjustNone
+ }
+ if current <= limit {
+ return adjustNone
+ }
+ setter(limit)
+ return adjustAdjusted
+ case ComparisonGreaterThanEqual:
+ limit, ok := parseInt(values[0])
+ if !ok {
+ return adjustNone
+ }
+ if current >= limit {
+ return adjustNone
+ }
+ // Cannot upscale
+ return adjustCannotFit
+ case ComparisonEquals:
+ // Check if current value matches any allowed value
+ for _, v := range values {
+ if limit, ok := parseInt(v); ok && current == limit {
+ return adjustNone
+ }
+ }
+ // Find the closest allowed value below current (don't upscale)
+ var closest int
+ found := false
+ for _, v := range values {
+ if limit, ok := parseInt(v); ok && limit < current {
+ if !found || limit > closest {
+ closest = limit
+ found = true
+ }
+ }
+ }
+ if found {
+ setter(closest)
+ return adjustAdjusted
+ }
+ return adjustCannotFit
+ case ComparisonNotEquals:
+ for _, v := range values {
+ if limit, ok := parseInt(v); ok && current == limit {
+ return adjustCannotFit
+ }
+ }
+ return adjustNone
+ }
+
+ return adjustNone
+}
+
+func checkIntLimitation(value int, comparison string, values []string) bool {
+ return applyIntLimitation(comparison, values, value, func(int) {}) == adjustNone
+}
+
+// checkStringLimitation checks a string value against a limitation.
+// Only Equals and NotEquals comparisons are meaningful for strings.
+// LessThanEqual/GreaterThanEqual are not applicable and always pass.
+func checkStringLimitation(value string, comparison string, values []string) bool {
+ switch comparison {
+ case ComparisonEquals:
+ for _, v := range values {
+ if strings.EqualFold(value, v) {
+ return true
+ }
+ }
+ return false
+ case ComparisonNotEquals:
+ for _, v := range values {
+ if strings.EqualFold(value, v) {
+ return false
+ }
+ }
+ return true
+ }
+ return true
+}
+
+func parseInt(s string) (int, bool) {
+ v, err := strconv.Atoi(s)
+ if err != nil || v < 0 {
+ return 0, false
+ }
+ return v, true
+}
diff --git a/core/stream/media_streamer.go b/core/stream/media_streamer.go
new file mode 100644
index 000000000..de03b4d2f
--- /dev/null
+++ b/core/stream/media_streamer.go
@@ -0,0 +1,257 @@
+package stream
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "mime"
+ "net/http"
+ "os"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ "github.com/navidrome/navidrome/utils/cache"
+ "github.com/navidrome/navidrome/utils/req"
+)
+
+type MediaStreamer interface {
+ NewStream(ctx context.Context, mf *model.MediaFile, req Request) (*Stream, error)
+}
+
+type TranscodingCache cache.FileCache
+
+func NewMediaStreamer(ds model.DataStore, t ffmpeg.FFmpeg, cache TranscodingCache) MediaStreamer {
+ return &mediaStreamer{ds: ds, transcoder: t, cache: cache}
+}
+
+type mediaStreamer struct {
+ ds model.DataStore
+ transcoder ffmpeg.FFmpeg
+ cache cache.FileCache
+}
+
+type streamJob struct {
+ ms *mediaStreamer
+ mf *model.MediaFile
+ filePath string
+ format string
+ bitRate int
+ sampleRate int
+ bitDepth int
+ channels int
+ offset int
+}
+
+func (j *streamJob) Key() string {
+ return fmt.Sprintf("%s.%s.%d.%d.%d.%d.%s.%d", j.mf.ID, j.mf.UpdatedAt.Format(time.RFC3339Nano), j.bitRate, j.sampleRate, j.bitDepth, j.channels, j.format, j.offset)
+}
+
+// NewStream creates a Stream for the given MediaFile and Request. It handles both raw streaming (no transcoding)
+// and transcoded streaming based on the requested format and bitrate. It also logs detailed information about
+// the streaming request and whether the transcoding result was served from cache or not.
+func (ms *mediaStreamer) NewStream(ctx context.Context, mf *model.MediaFile, req Request) (*Stream, error) {
+ var format string
+ var bitRate int
+ var cached bool
+ defer func() {
+ log.Info(ctx, "Streaming file", "title", mf.Title, "artist", mf.Artist, "format", format, "cached", cached,
+ "bitRate", bitRate, "sampleRate", req.SampleRate, "bitDepth", req.BitDepth, "channels", req.Channels,
+ "user", userName(ctx), "transcoding", format != "raw",
+ "originalFormat", mf.Suffix, "originalBitRate", mf.BitRate)
+ }()
+
+ format = req.Format
+ bitRate = req.BitRate
+ if format == "" || format == "raw" {
+ format = "raw"
+ bitRate = 0
+ }
+ s := &Stream{ctx: ctx, mf: mf, format: format, bitRate: bitRate}
+ filePath := mf.AbsolutePath()
+
+ if format == "raw" {
+ log.Debug(ctx, "Streaming RAW file", "id", mf.ID, "path", filePath,
+ "requestBitrate", req.BitRate, "requestFormat", req.Format, "requestOffset", req.Offset,
+ "originalBitrate", mf.BitRate, "originalFormat", mf.Suffix,
+ "selectedBitrate", bitRate, "selectedFormat", format)
+ f, err := os.Open(filePath)
+ if err != nil {
+ return nil, err
+ }
+ s.ReadCloser = f
+ s.Seeker = f
+ s.format = mf.Suffix
+ return s, nil
+ }
+
+ job := &streamJob{
+ ms: ms,
+ mf: mf,
+ filePath: filePath,
+ format: format,
+ bitRate: bitRate,
+ sampleRate: req.SampleRate,
+ bitDepth: req.BitDepth,
+ channels: req.Channels,
+ offset: req.Offset,
+ }
+ r, err := ms.cache.Get(ctx, job)
+ if err != nil {
+ log.Error(ctx, "Error accessing transcoding cache", "id", mf.ID, err)
+ return nil, err
+ }
+ cached = r.Cached
+
+ s.ReadCloser = r
+ s.Seeker = r.Seeker
+
+ log.Debug(ctx, "Streaming TRANSCODED file", "id", mf.ID, "path", filePath,
+ "requestBitrate", req.BitRate, "requestFormat", req.Format, "requestOffset", req.Offset,
+ "originalBitrate", mf.BitRate, "originalFormat", mf.Suffix,
+ "selectedBitrate", bitRate, "selectedFormat", format, "cached", cached, "seekable", s.Seekable())
+
+ return s, nil
+}
+
+type Stream struct {
+ ctx context.Context
+ mf *model.MediaFile
+ bitRate int
+ format string
+ io.ReadCloser
+ io.Seeker
+}
+
+func (s *Stream) Seekable() bool { return s.Seeker != nil }
+func (s *Stream) Duration() float32 { return s.mf.Duration }
+func (s *Stream) ContentType() string { return mime.TypeByExtension("." + s.format) }
+func (s *Stream) Name() string { return s.mf.Title + "." + s.format }
+func (s *Stream) ModTime() time.Time { return s.mf.UpdatedAt }
+func (s *Stream) EstimatedContentLength() int {
+ return int(s.mf.Duration * float32(s.bitRate) / 8 * 1024)
+}
+
+// Serve writes the stream to the HTTP response. For seekable streams it uses http.ServeContent
+// (supporting range requests). For non-seekable streams it writes directly and logs any errors.
+// Returns the number of bytes written and an error only when io.Copy fails with 0 bytes written
+// (meaning the HTTP 200 status has not been flushed yet and the caller can still send an error response).
+// Empty output (0 bytes, no error) is logged but not treated as an error.
+func (s *Stream) Serve(ctx context.Context, w http.ResponseWriter, r *http.Request) (int64, error) {
+ if s.Seekable() {
+ http.ServeContent(w, r, s.Name(), s.ModTime(), s)
+ return -1, nil
+ }
+
+ w.Header().Set("Accept-Ranges", "none")
+ w.Header().Set("Content-Type", s.ContentType())
+
+ if req.Params(r).BoolOr("estimateContentLength", false) {
+ length := strconv.Itoa(s.EstimatedContentLength())
+ log.Trace(ctx, "Estimated content-length", "contentLength", length)
+ w.Header().Set("Content-Length", length)
+ }
+
+ if r.Method == http.MethodHead {
+ go func() { _, _ = io.Copy(io.Discard, s) }()
+ return 0, nil
+ }
+
+ id := s.mf.ID
+ c, err := io.Copy(w, s)
+ if err != nil {
+ log.Error(ctx, "Error sending transcoded file", "id", id, err)
+ if c == 0 {
+ w.Header().Del("Content-Length")
+ return 0, fmt.Errorf("sending transcoded file: %w", err)
+ }
+ return c, nil
+ }
+ if c == 0 {
+ log.Error(ctx, "Transcoding returned empty output, ffmpeg may have failed. "+
+ "Check that ffmpeg supports the requested codec. Enable Trace logging for ffmpeg stderr details",
+ "id", id, "format", s.ContentType())
+ } else {
+ log.Trace(ctx, "Success sending transcoded file", "id", id, "size", c)
+ }
+ return c, nil
+}
+
+// NewStream creates a non-seekable Stream from the given components.
+func NewStream(mf *model.MediaFile, format string, bitRate int, r io.ReadCloser) *Stream {
+ return &Stream{
+ ctx: context.Background(),
+ mf: mf,
+ format: format,
+ bitRate: bitRate,
+ ReadCloser: r,
+ }
+}
+
+var (
+ onceTranscodingCache sync.Once
+ instanceTranscodingCache TranscodingCache
+)
+
+func GetTranscodingCache() TranscodingCache {
+ onceTranscodingCache.Do(func() {
+ instanceTranscodingCache = NewTranscodingCache()
+ })
+ return instanceTranscodingCache
+}
+
+func NewTranscodingCache() TranscodingCache {
+ return cache.NewFileCache("Transcoding", conf.Server.TranscodingCacheSize,
+ consts.TranscodingCacheDir, consts.DefaultTranscodingCacheMaxItems,
+ func(ctx context.Context, arg cache.Item) (io.Reader, error) {
+ job := arg.(*streamJob)
+ command := LookupTranscodeCommand(ctx, job.ms.ds, job.format)
+ if command == "" {
+ log.Error(ctx, "No transcoding command available", "format", job.format)
+ return nil, os.ErrInvalid
+ }
+
+ // Choose the appropriate context based on EnableTranscodingCancellation configuration.
+ // This is where we decide whether transcoding processes should be cancellable or not.
+ var transcodingCtx context.Context
+ if conf.Server.EnableTranscodingCancellation {
+ // Use the request context directly, allowing cancellation when client disconnects
+ transcodingCtx = ctx
+ } else {
+ // Use background context with request values preserved.
+ // This prevents cancellation but maintains request metadata (user, client, etc.)
+ transcodingCtx = request.AddValues(context.Background(), ctx)
+ }
+
+ out, err := job.ms.transcoder.Transcode(transcodingCtx, ffmpeg.TranscodeOptions{
+ Command: command,
+ Format: job.format,
+ FilePath: job.filePath,
+ BitRate: job.bitRate,
+ SampleRate: job.sampleRate,
+ BitDepth: job.bitDepth,
+ Channels: job.channels,
+ Offset: job.offset,
+ })
+ if err != nil {
+ log.Error(ctx, "Error starting transcoder", "id", job.mf.ID, err)
+ return nil, os.ErrInvalid
+ }
+ return out, nil
+ })
+}
+
+// userName extracts the username from the context for logging purposes.
+func userName(ctx context.Context) string {
+ if user, ok := request.UserFrom(ctx); !ok {
+ return "UNKNOWN"
+ } else {
+ return user.UserName
+ }
+}
diff --git a/core/media_streamer_test.go b/core/stream/media_streamer_test.go
similarity index 70%
rename from core/media_streamer_test.go
rename to core/stream/media_streamer_test.go
index f5175495b..1bc21e239 100644
--- a/core/media_streamer_test.go
+++ b/core/stream/media_streamer_test.go
@@ -1,4 +1,4 @@
-package core_test
+package stream_test
import (
"context"
@@ -7,7 +7,7 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
- "github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
@@ -16,7 +16,7 @@ import (
)
var _ = Describe("MediaStreamer", func() {
- var streamer core.MediaStreamer
+ var streamer stream.MediaStreamer
var ds model.DataStore
ffmpeg := tests.NewMockFFmpeg("fake data")
ctx := log.NewContext(context.TODO())
@@ -29,44 +29,45 @@ var _ = Describe("MediaStreamer", func() {
ds.MediaFile(ctx).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: "123", Path: "tests/fixtures/test.mp3", Suffix: "mp3", BitRate: 128, Duration: 257.0},
})
- testCache := core.NewTranscodingCache()
+ testCache := stream.NewTranscodingCache()
Eventually(func() bool { return testCache.Available(context.TODO()) }).Should(BeTrue())
- streamer = core.NewMediaStreamer(ds, ffmpeg, testCache)
+ streamer = stream.NewMediaStreamer(ds, ffmpeg, testCache)
})
AfterEach(func() {
_ = os.RemoveAll(conf.Server.CacheFolder)
})
Context("NewStream", func() {
+ var mf *model.MediaFile
+ BeforeEach(func() {
+ var err error
+ mf, err = ds.MediaFile(ctx).Get("123")
+ Expect(err).ToNot(HaveOccurred())
+ })
It("returns a seekable stream if format is 'raw'", func() {
- s, err := streamer.NewStream(ctx, "123", "raw", 0, 0)
+ s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "raw"})
Expect(err).ToNot(HaveOccurred())
Expect(s.Seekable()).To(BeTrue())
})
- It("returns a seekable stream if maxBitRate is 0", func() {
- s, err := streamer.NewStream(ctx, "123", "mp3", 0, 0)
- Expect(err).ToNot(HaveOccurred())
- Expect(s.Seekable()).To(BeTrue())
- })
- It("returns a seekable stream if maxBitRate is higher than file bitRate", func() {
- s, err := streamer.NewStream(ctx, "123", "mp3", 320, 0)
+ It("returns a seekable stream if no format is specified (direct play)", func() {
+ s, err := streamer.NewStream(ctx, mf, stream.Request{})
Expect(err).ToNot(HaveOccurred())
Expect(s.Seekable()).To(BeTrue())
})
It("returns a NON seekable stream if transcode is required", func() {
- s, err := streamer.NewStream(ctx, "123", "mp3", 64, 0)
+ s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 64})
Expect(err).To(BeNil())
Expect(s.Seekable()).To(BeFalse())
Expect(s.Duration()).To(Equal(float32(257.0)))
})
It("returns a seekable stream if the file is complete in the cache", func() {
- s, err := streamer.NewStream(ctx, "123", "mp3", 32, 0)
+ s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 32})
Expect(err).To(BeNil())
_, _ = io.ReadAll(s)
_ = s.Close()
Eventually(func() bool { return ffmpeg.IsClosed() }, "3s").Should(BeTrue())
- s, err = streamer.NewStream(ctx, "123", "mp3", 32, 0)
+ s, err = streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 32})
Expect(err).To(BeNil())
Expect(s.Seekable()).To(BeTrue())
})
diff --git a/core/agents/spotify/spotify_suite_test.go b/core/stream/stream_suite_test.go
similarity index 74%
rename from core/agents/spotify/spotify_suite_test.go
rename to core/stream/stream_suite_test.go
index 275b05e73..36e9e7f43 100644
--- a/core/agents/spotify/spotify_suite_test.go
+++ b/core/stream/stream_suite_test.go
@@ -1,4 +1,4 @@
-package spotify
+package stream
import (
"testing"
@@ -9,9 +9,9 @@ import (
. "github.com/onsi/gomega"
)
-func TestSpotify(t *testing.T) {
+func TestStream(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
RegisterFailHandler(Fail)
- RunSpecs(t, "Spotify Test Suite")
+ RunSpecs(t, "Stream Suite")
}
diff --git a/core/stream/token.go b/core/stream/token.go
new file mode 100644
index 000000000..24a154b54
--- /dev/null
+++ b/core/stream/token.go
@@ -0,0 +1,148 @@
+package stream
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/lestrrat-go/jwx/v3/jwt"
+ "github.com/navidrome/navidrome/core/auth"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+)
+
+const tokenTTL = 48 * time.Hour
+
+// params contains the parameters extracted from a transcode token.
+// TargetBitrate is in kilobits per second (kbps).
+type params struct {
+ MediaID string
+ DirectPlay bool
+ TargetFormat string
+ TargetBitrate int
+ TargetChannels int
+ TargetSampleRate int
+ TargetBitDepth int
+ SourceUpdatedAt time.Time
+}
+
+// toClaimsMap converts a Decision into a JWT claims map for token encoding.
+// Only non-zero transcode fields are included.
+func (d *TranscodeDecision) toClaimsMap() map[string]any {
+ m := map[string]any{
+ "mid": d.MediaID,
+ "ua": d.SourceUpdatedAt.Truncate(time.Second).Unix(),
+ jwt.ExpirationKey: time.Now().Add(tokenTTL).UTC().Unix(),
+ }
+ if d.CanDirectPlay {
+ m["dp"] = true
+ }
+ if d.CanTranscode && d.TargetFormat != "" {
+ m["f"] = d.TargetFormat
+ if d.TargetBitrate != 0 {
+ m["b"] = d.TargetBitrate
+ }
+ if d.TargetChannels != 0 {
+ m["ch"] = d.TargetChannels
+ }
+ if d.TargetSampleRate != 0 {
+ m["sr"] = d.TargetSampleRate
+ }
+ if d.TargetBitDepth != 0 {
+ m["bd"] = d.TargetBitDepth
+ }
+ }
+ return m
+}
+
+// paramsFromToken extracts and validates Params from a parsed JWT token.
+// Returns an error if required claims (media ID, source timestamp) are missing.
+func paramsFromToken(token jwt.Token) (*params, error) {
+ var p params
+ var mid string
+ if err := token.Get("mid", &mid); err == nil {
+ p.MediaID = mid
+ }
+ if p.MediaID == "" {
+ return nil, fmt.Errorf("%w: missing media ID", ErrTokenInvalid)
+ }
+
+ var dp bool
+ if err := token.Get("dp", &dp); err == nil {
+ p.DirectPlay = dp
+ }
+
+ ua := getIntClaim(token, "ua")
+ if ua != 0 {
+ p.SourceUpdatedAt = time.Unix(int64(ua), 0)
+ }
+ if p.SourceUpdatedAt.IsZero() {
+ return nil, fmt.Errorf("%w: missing source timestamp", ErrTokenInvalid)
+ }
+
+ var f string
+ if err := token.Get("f", &f); err == nil {
+ p.TargetFormat = f
+ }
+ p.TargetBitrate = getIntClaim(token, "b")
+ p.TargetChannels = getIntClaim(token, "ch")
+ p.TargetSampleRate = getIntClaim(token, "sr")
+ p.TargetBitDepth = getIntClaim(token, "bd")
+ return &p, nil
+}
+
+// getIntClaim extracts an int claim from a JWT token, handling the case where
+// the value may be stored as int64 or float64 (common in JSON-based JWT libraries).
+func getIntClaim(token jwt.Token, key string) int {
+ var v int
+ if err := token.Get(key, &v); err == nil {
+ return v
+ }
+ var v64 int64
+ if err := token.Get(key, &v64); err == nil {
+ return int(v64)
+ }
+ var f float64
+ if err := token.Get(key, &f); err == nil {
+ return int(f)
+ }
+ return 0
+}
+
+func (s *deciderService) CreateTranscodeParams(decision *TranscodeDecision) (string, error) {
+ return auth.EncodeToken(decision.toClaimsMap())
+}
+
+func (s *deciderService) parseTranscodeParams(tokenStr string) (*params, error) {
+ token, err := auth.DecodeAndVerifyToken(tokenStr)
+ if err != nil {
+ return nil, err
+ }
+ return paramsFromToken(token)
+}
+
+func (s *deciderService) ResolveRequestFromToken(ctx context.Context, token string, mf *model.MediaFile, offset int) (Request, error) {
+ p, err := s.parseTranscodeParams(token)
+ if err != nil {
+ return Request{}, errors.Join(ErrTokenInvalid, err)
+ }
+ if p.MediaID != mf.ID {
+ return Request{}, fmt.Errorf("%w: token mediaID %q does not match %q", ErrTokenInvalid, p.MediaID, mf.ID)
+ }
+ if !mf.UpdatedAt.Truncate(time.Second).Equal(p.SourceUpdatedAt) {
+ log.Info(ctx, "Transcode token is stale", "mediaID", mf.ID,
+ "tokenUpdatedAt", p.SourceUpdatedAt, "fileUpdatedAt", mf.UpdatedAt)
+ return Request{}, ErrTokenStale
+ }
+
+ req := Request{Offset: offset}
+ if !p.DirectPlay && p.TargetFormat != "" {
+ req.Format = p.TargetFormat
+ req.BitRate = p.TargetBitrate
+ req.SampleRate = p.TargetSampleRate
+ req.BitDepth = p.TargetBitDepth
+ req.Channels = p.TargetChannels
+ }
+ return req, nil
+}
diff --git a/core/stream/token_test.go b/core/stream/token_test.go
new file mode 100644
index 000000000..7409a7532
--- /dev/null
+++ b/core/stream/token_test.go
@@ -0,0 +1,256 @@
+package stream
+
+import (
+ "context"
+ "time"
+
+ "github.com/go-chi/jwtauth/v5"
+ "github.com/navidrome/navidrome/core/auth"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Token", func() {
+ var (
+ ds *tests.MockDataStore
+ ff *tests.MockFFmpeg
+ svc TranscodeDecider
+ ctx context.Context
+ )
+
+ BeforeEach(func() {
+ ctx = GinkgoT().Context()
+ ds = &tests.MockDataStore{
+ MockedProperty: &tests.MockedPropertyRepo{},
+ MockedTranscoding: &tests.MockTranscodingRepo{},
+ }
+ ff = tests.NewMockFFmpeg("")
+ auth.Init(ds)
+ svc = NewTranscodeDecider(ds, ff)
+ })
+
+ Describe("Token round-trip", func() {
+ var (
+ sourceTime time.Time
+ impl *deciderService
+ )
+
+ BeforeEach(func() {
+ sourceTime = time.Date(2025, 6, 15, 10, 30, 0, 0, time.UTC)
+ impl = svc.(*deciderService)
+ })
+
+ It("creates and parses a direct play token", func() {
+ decision := &TranscodeDecision{
+ MediaID: "media-123",
+ CanDirectPlay: true,
+ SourceUpdatedAt: sourceTime,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(token).ToNot(BeEmpty())
+
+ params, err := impl.parseTranscodeParams(token)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(params.MediaID).To(Equal("media-123"))
+ Expect(params.DirectPlay).To(BeTrue())
+ Expect(params.TargetFormat).To(BeEmpty())
+ Expect(params.SourceUpdatedAt.Unix()).To(Equal(sourceTime.Unix()))
+ })
+
+ It("creates and parses a transcode token with kbps bitrate", func() {
+ decision := &TranscodeDecision{
+ MediaID: "media-456",
+ CanDirectPlay: false,
+ CanTranscode: true,
+ TargetFormat: "mp3",
+ TargetBitrate: 256, // kbps
+ TargetChannels: 2,
+ SourceUpdatedAt: sourceTime,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+
+ params, err := impl.parseTranscodeParams(token)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(params.MediaID).To(Equal("media-456"))
+ Expect(params.DirectPlay).To(BeFalse())
+ Expect(params.TargetFormat).To(Equal("mp3"))
+ Expect(params.TargetBitrate).To(Equal(256)) // kbps
+ Expect(params.TargetChannels).To(Equal(2))
+ Expect(params.SourceUpdatedAt.Unix()).To(Equal(sourceTime.Unix()))
+ })
+
+ It("creates and parses a transcode token with sample rate", func() {
+ decision := &TranscodeDecision{
+ MediaID: "media-789",
+ CanDirectPlay: false,
+ CanTranscode: true,
+ TargetFormat: "flac",
+ TargetBitrate: 0,
+ TargetChannels: 2,
+ TargetSampleRate: 48000,
+ SourceUpdatedAt: sourceTime,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+
+ params, err := impl.parseTranscodeParams(token)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(params.MediaID).To(Equal("media-789"))
+ Expect(params.DirectPlay).To(BeFalse())
+ Expect(params.TargetFormat).To(Equal("flac"))
+ Expect(params.TargetSampleRate).To(Equal(48000))
+ Expect(params.TargetChannels).To(Equal(2))
+ })
+
+ It("creates and parses a transcode token with bit depth", func() {
+ decision := &TranscodeDecision{
+ MediaID: "media-bd",
+ CanDirectPlay: false,
+ CanTranscode: true,
+ TargetFormat: "flac",
+ TargetBitrate: 0,
+ TargetChannels: 2,
+ TargetBitDepth: 24,
+ SourceUpdatedAt: sourceTime,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+
+ params, err := impl.parseTranscodeParams(token)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(params.MediaID).To(Equal("media-bd"))
+ Expect(params.TargetBitDepth).To(Equal(24))
+ })
+
+ It("omits bit depth from token when 0", func() {
+ decision := &TranscodeDecision{
+ MediaID: "media-nobd",
+ CanDirectPlay: false,
+ CanTranscode: true,
+ TargetFormat: "mp3",
+ TargetBitrate: 256,
+ TargetBitDepth: 0,
+ SourceUpdatedAt: sourceTime,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+
+ params, err := impl.parseTranscodeParams(token)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(params.TargetBitDepth).To(Equal(0))
+ })
+
+ It("omits sample rate from token when 0", func() {
+ decision := &TranscodeDecision{
+ MediaID: "media-100",
+ CanDirectPlay: false,
+ CanTranscode: true,
+ TargetFormat: "mp3",
+ TargetBitrate: 256,
+ TargetSampleRate: 0,
+ SourceUpdatedAt: sourceTime,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+
+ params, err := impl.parseTranscodeParams(token)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(params.TargetSampleRate).To(Equal(0))
+ })
+
+ It("truncates SourceUpdatedAt to seconds", func() {
+ timeWithNanos := time.Date(2025, 6, 15, 10, 30, 0, 123456789, time.UTC)
+ decision := &TranscodeDecision{
+ MediaID: "media-trunc",
+ CanDirectPlay: true,
+ SourceUpdatedAt: timeWithNanos,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+
+ params, err := impl.parseTranscodeParams(token)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(params.SourceUpdatedAt.Unix()).To(Equal(timeWithNanos.Truncate(time.Second).Unix()))
+ })
+
+ It("rejects an invalid token", func() {
+ _, err := impl.parseTranscodeParams("invalid-token")
+ Expect(err).To(HaveOccurred())
+ })
+ })
+
+ Describe("ResolveRequestFromToken", func() {
+ var sourceTime time.Time
+
+ BeforeEach(func() {
+ sourceTime = time.Date(2025, 6, 15, 10, 30, 0, 0, time.UTC)
+ })
+
+ createTokenForMedia := func(mediaID string, updatedAt time.Time) string {
+ decision := &TranscodeDecision{
+ MediaID: mediaID,
+ CanDirectPlay: true,
+ SourceUpdatedAt: updatedAt,
+ }
+ token, err := svc.CreateTranscodeParams(decision)
+ Expect(err).ToNot(HaveOccurred())
+ return token
+ }
+
+ It("returns stream request for valid token", func() {
+ mf := &model.MediaFile{ID: "song-1", UpdatedAt: sourceTime}
+ token := createTokenForMedia("song-1", sourceTime)
+
+ req, err := svc.ResolveRequestFromToken(ctx, token, mf, 0)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(req.Format).To(BeEmpty()) // direct play has no target format
+ })
+
+ It("returns ErrTokenInvalid for invalid token", func() {
+ mf := &model.MediaFile{ID: "song-1", UpdatedAt: sourceTime}
+ _, err := svc.ResolveRequestFromToken(ctx, "bad-token", mf, 0)
+ Expect(err).To(MatchError(ContainSubstring(ErrTokenInvalid.Error())))
+ })
+
+ It("returns ErrTokenInvalid when mediaID does not match token", func() {
+ mf := &model.MediaFile{ID: "song-2", UpdatedAt: sourceTime}
+ token := createTokenForMedia("song-1", sourceTime)
+
+ _, err := svc.ResolveRequestFromToken(ctx, token, mf, 0)
+ Expect(err).To(MatchError(ContainSubstring(ErrTokenInvalid.Error())))
+ })
+
+ It("returns ErrTokenStale when media file has changed", func() {
+ newTime := sourceTime.Add(1 * time.Hour)
+ mf := &model.MediaFile{ID: "song-1", UpdatedAt: newTime}
+ token := createTokenForMedia("song-1", sourceTime)
+
+ _, err := svc.ResolveRequestFromToken(ctx, token, mf, 0)
+ Expect(err).To(MatchError(ErrTokenStale))
+ })
+ })
+
+ Describe("paramsFromToken", func() {
+ It("returns error when media ID is missing", func() {
+ tokenAuth := jwtauth.New("HS256", []byte("test-secret"), nil)
+ token, _, err := tokenAuth.Encode(map[string]any{"ua": int64(1700000000)})
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = paramsFromToken(token)
+ Expect(err).To(MatchError(ContainSubstring("missing media ID")))
+ })
+
+ It("returns error when source timestamp is missing", func() {
+ tokenAuth := jwtauth.New("HS256", []byte("test-secret"), nil)
+ token, _, err := tokenAuth.Encode(map[string]any{"mid": "song-5"})
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = paramsFromToken(token)
+ Expect(err).To(MatchError(ContainSubstring("missing source timestamp")))
+ })
+ })
+})
diff --git a/core/stream/types.go b/core/stream/types.go
new file mode 100644
index 000000000..0cb4ac47d
--- /dev/null
+++ b/core/stream/types.go
@@ -0,0 +1,132 @@
+package stream
+
+import (
+ "errors"
+ "time"
+)
+
+var (
+ ErrTokenInvalid = errors.New("invalid or expired transcode token")
+ ErrTokenStale = errors.New("transcode token is stale: media file has changed")
+)
+
+// TranscodeOptions controls optional behavior of MakeTranscodeDecision.
+type TranscodeOptions struct {
+ // SkipProbe prevents MakeTranscodeDecision from running ffprobe on the media file.
+ // When true, source stream details are derived from tag metadata only.
+ SkipProbe bool
+}
+
+// Request contains the resolved parameters for creating a media stream.
+type Request struct {
+ Format string
+ BitRate int // kbps
+ SampleRate int
+ BitDepth int
+ Channels int
+ Offset int // seconds
+}
+
+// ClientInfo represents client playback capabilities.
+// All bitrate values are in kilobits per second (kbps)
+type ClientInfo struct {
+ Name string
+ Platform string
+ MaxAudioBitrate int
+ MaxTranscodingAudioBitrate int
+ DirectPlayProfiles []DirectPlayProfile
+ TranscodingProfiles []Profile
+ CodecProfiles []CodecProfile
+}
+
+// DirectPlayProfile describes a format the client can play directly
+type DirectPlayProfile struct {
+ Containers []string
+ AudioCodecs []string
+ Protocols []string
+ MaxAudioChannels int
+}
+
+// Profile describes a transcoding target the client supports
+type Profile struct {
+ Container string
+ AudioCodec string
+ Protocol string
+ MaxAudioChannels int
+}
+
+// CodecProfile describes codec-specific limitations
+type CodecProfile struct {
+ Type string
+ Name string
+ Limitations []Limitation
+}
+
+// Limitation describes a specific codec limitation
+type Limitation struct {
+ Name string
+ Comparison string
+ Values []string
+ Required bool
+}
+
+// Protocol values (OpenSubsonic spec enum)
+const (
+ ProtocolHTTP = "http"
+ ProtocolHLS = "hls"
+)
+
+// Comparison operators (OpenSubsonic spec enum)
+const (
+ ComparisonEquals = "Equals"
+ ComparisonNotEquals = "NotEquals"
+ ComparisonLessThanEqual = "LessThanEqual"
+ ComparisonGreaterThanEqual = "GreaterThanEqual"
+)
+
+// Limitation names (OpenSubsonic spec enum)
+const (
+ LimitationAudioChannels = "audioChannels"
+ LimitationAudioBitrate = "audioBitrate"
+ LimitationAudioProfile = "audioProfile"
+ LimitationAudioSamplerate = "audioSamplerate"
+ LimitationAudioBitdepth = "audioBitdepth"
+)
+
+// Codec profile types (OpenSubsonic spec enum)
+const (
+ CodecProfileTypeAudio = "AudioCodec"
+)
+
+// TranscodeDecision represents the internal decision result.
+// All bitrate values are in kilobits per second (kbps).
+type TranscodeDecision struct {
+ MediaID string
+ CanDirectPlay bool
+ CanTranscode bool
+ TranscodeReasons []string
+ ErrorReason string
+ TargetFormat string
+ TargetBitrate int
+ TargetChannels int
+ TargetSampleRate int
+ TargetBitDepth int
+ SourceStream Details
+ SourceUpdatedAt time.Time
+ TranscodeStream *Details
+}
+
+// Details describes audio stream properties.
+// Bitrate is in kilobits per second (kbps).
+type Details struct {
+ Container string
+ Codec string
+ Profile string // Audio profile (e.g., "LC", "HE-AACv2"). Populated from ffprobe data.
+ Bitrate int
+ SampleRate int
+ BitDepth int
+ Channels int
+ Duration float32
+ Size int64
+ IsLossless bool
+}
diff --git a/core/user.go b/core/user.go
new file mode 100644
index 000000000..f13e90167
--- /dev/null
+++ b/core/user.go
@@ -0,0 +1,76 @@
+package core
+
+import (
+ "context"
+
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/model"
+)
+
+// PluginUnloader defines the interface for unloading disabled plugins.
+// This is satisfied by plugins.Manager but defined here to avoid import cycles.
+type PluginUnloader interface {
+ UnloadDisabledPlugins(ctx context.Context)
+}
+
+// User provides business logic for user management with plugin coordination.
+type User interface {
+ NewRepository(ctx context.Context) rest.Repository
+}
+
+type userService struct {
+ ds model.DataStore
+ pluginManager PluginUnloader
+}
+
+// NewUser creates a new User service
+func NewUser(ds model.DataStore, pluginManager PluginUnloader) User {
+ return &userService{
+ ds: ds,
+ pluginManager: pluginManager,
+ }
+}
+
+// NewRepository returns a REST repository wrapper for user operations.
+// The wrapper intercepts Delete operations to coordinate plugin unloading.
+func (s *userService) NewRepository(ctx context.Context) rest.Repository {
+ repo := s.ds.User(ctx)
+ wrapper := &userRepositoryWrapper{
+ ctx: ctx,
+ UserRepository: repo,
+ pluginManager: s.pluginManager,
+ }
+ return wrapper
+}
+
+type userRepositoryWrapper struct {
+ model.UserRepository
+ ctx context.Context
+ pluginManager PluginUnloader
+}
+
+// Save implements rest.Persistable by delegating to the underlying repository.
+func (r *userRepositoryWrapper) Save(entity any) (string, error) {
+ return r.UserRepository.(rest.Persistable).Save(entity)
+}
+
+// Update implements rest.Persistable by delegating to the underlying repository.
+func (r *userRepositoryWrapper) Update(id string, entity any, cols ...string) error {
+ return r.UserRepository.(rest.Persistable).Update(id, entity, cols...)
+}
+
+// Delete implements rest.Persistable and coordinates plugin unloading.
+func (r *userRepositoryWrapper) Delete(id string) error {
+ // The underlying repository Delete handles the database cleanup
+ // including calling cleanupPluginUserReferences
+ err := r.UserRepository.(rest.Persistable).Delete(id)
+ if err != nil {
+ return err
+ }
+
+ // After successful deletion, check if any plugins were auto-disabled
+ // and need to be unloaded from memory
+ r.pluginManager.UnloadDisabledPlugins(r.ctx)
+
+ return nil
+}
diff --git a/core/user_test.go b/core/user_test.go
new file mode 100644
index 000000000..b2d3117f8
--- /dev/null
+++ b/core/user_test.go
@@ -0,0 +1,86 @@
+package core_test
+
+import (
+ "context"
+ "errors"
+
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/core"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/tests"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("User Service", func() {
+ var service core.User
+ var ds *tests.MockDataStore
+ var userRepo *tests.MockedUserRepo
+ var pluginManager *mockPluginUnloader
+ var ctx context.Context
+
+ BeforeEach(func() {
+ ds = &tests.MockDataStore{}
+ userRepo = tests.CreateMockUserRepo()
+ ds.MockedUser = userRepo
+ pluginManager = &mockPluginUnloader{}
+ service = core.NewUser(ds, pluginManager)
+ ctx = GinkgoT().Context()
+ })
+
+ Describe("NewRepository", func() {
+ It("returns a rest.Persistable", func() {
+ repo := service.NewRepository(ctx)
+ _, ok := repo.(rest.Persistable)
+ Expect(ok).To(BeTrue())
+ })
+ })
+
+ Describe("Delete", func() {
+ var repo rest.Persistable
+
+ BeforeEach(func() {
+ r := service.NewRepository(ctx)
+ repo = r.(rest.Persistable)
+
+ // Add a test user
+ user := &model.User{
+ ID: "user-123",
+ UserName: "testuser",
+ IsAdmin: false,
+ }
+ user.NewPassword = "password"
+ Expect(userRepo.Put(user)).To(Succeed())
+ })
+
+ It("deletes the user successfully", func() {
+ err := repo.Delete("user-123")
+ Expect(err).NotTo(HaveOccurred())
+
+ // Verify user is deleted
+ _, err = userRepo.Get("user-123")
+ Expect(err).To(Equal(model.ErrNotFound))
+ })
+
+ It("calls UnloadDisabledPlugins after successful deletion", func() {
+ err := repo.Delete("user-123")
+ Expect(err).NotTo(HaveOccurred())
+ Expect(pluginManager.unloadCalls).To(Equal(1))
+ })
+
+ It("does not call UnloadDisabledPlugins when deletion fails", func() {
+ // Try to delete non-existent user
+ err := repo.Delete("non-existent")
+ Expect(err).To(HaveOccurred())
+ Expect(pluginManager.unloadCalls).To(Equal(0))
+ })
+
+ It("returns error when repository fails", func() {
+ userRepo.Error = errors.New("database error")
+ err := repo.Delete("user-123")
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("database error"))
+ Expect(pluginManager.unloadCalls).To(Equal(0))
+ })
+ })
+})
diff --git a/core/wire_providers.go b/core/wire_providers.go
index ae365156a..276d9556a 100644
--- a/core/wire_providers.go
+++ b/core/wire_providers.go
@@ -5,19 +5,27 @@ import (
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/ffmpeg"
+ "github.com/navidrome/navidrome/core/lyrics"
"github.com/navidrome/navidrome/core/metrics"
"github.com/navidrome/navidrome/core/playback"
+ "github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/core/scrobbler"
+ "github.com/navidrome/navidrome/core/stream"
)
var Set = wire.NewSet(
- NewMediaStreamer,
- GetTranscodingCache,
+ stream.NewMediaStreamer,
+ stream.GetTranscodingCache,
NewArchiver,
NewPlayers,
NewShare,
- NewPlaylists,
+ playlists.NewPlaylists,
NewLibrary,
+ NewUser,
+ NewMaintenance,
+ NewImageUploadService,
+ wire.Bind(new(playlists.ImageUploadService), new(ImageUploadService)),
+ stream.NewTranscodeDecider,
agents.GetAgents,
external.NewProvider,
wire.Bind(new(external.Agents), new(*agents.Agents)),
@@ -25,4 +33,5 @@ var Set = wire.NewSet(
scrobbler.GetPlayTracker,
playback.GetInstance,
metrics.GetInstance,
+ lyrics.NewLyrics,
)
diff --git a/db/db.go b/db/db.go
index cb1ebd9e3..0945d1a00 100644
--- a/db/db.go
+++ b/db/db.go
@@ -45,10 +45,12 @@ func Db() *sql.DB {
if err != nil {
log.Fatal("Error opening database", err)
}
- _, err = db.Exec("PRAGMA optimize=0x10002")
- if err != nil {
- log.Error("Error applying PRAGMA optimize", err)
- return nil
+ if conf.Server.DevOptimizeDB {
+ _, err = db.Exec("PRAGMA optimize=0x10002")
+ if err != nil {
+ log.Error("Error applying PRAGMA optimize", err)
+ return nil
+ }
}
return db
})
@@ -99,7 +101,7 @@ func Init(ctx context.Context) func() {
log.Fatal(ctx, "Failed to apply new migrations", err)
}
- if hasSchemaChanges {
+ if hasSchemaChanges && conf.Server.DevOptimizeDB {
log.Debug(ctx, "Applying PRAGMA optimize after schema changes")
_, err = db.ExecContext(ctx, "PRAGMA optimize")
if err != nil {
@@ -114,6 +116,9 @@ func Init(ctx context.Context) func() {
// Optimize runs PRAGMA optimize on each connection in the pool
func Optimize(ctx context.Context) {
+ if !conf.Server.DevOptimizeDB {
+ return
+ }
numConns := Db().Stats().OpenConnections
if numConns == 0 {
log.Debug(ctx, "No open connections to optimize")
@@ -121,7 +126,7 @@ func Optimize(ctx context.Context) {
}
log.Debug(ctx, "Optimizing open connections", "numConns", numConns)
var conns []*sql.Conn
- for i := 0; i < numConns; i++ {
+ for range numConns {
conn, err := Db().Conn(ctx)
conns = append(conns, conn)
if err != nil {
@@ -142,8 +147,8 @@ func Optimize(ctx context.Context) {
type statusLogger struct{ numPending int }
-func (*statusLogger) Fatalf(format string, v ...interface{}) { log.Fatal(fmt.Sprintf(format, v...)) }
-func (l *statusLogger) Printf(format string, v ...interface{}) {
+func (*statusLogger) Fatalf(format string, v ...any) { log.Fatal(fmt.Sprintf(format, v...)) }
+func (l *statusLogger) Printf(format string, v ...any) {
if len(v) < 1 {
return
}
@@ -178,27 +183,27 @@ type logAdapter struct {
silent bool
}
-func (l *logAdapter) Fatal(v ...interface{}) {
+func (l *logAdapter) Fatal(v ...any) {
log.Fatal(l.ctx, fmt.Sprint(v...))
}
-func (l *logAdapter) Fatalf(format string, v ...interface{}) {
+func (l *logAdapter) Fatalf(format string, v ...any) {
log.Fatal(l.ctx, fmt.Sprintf(format, v...))
}
-func (l *logAdapter) Print(v ...interface{}) {
+func (l *logAdapter) Print(v ...any) {
if !l.silent {
log.Info(l.ctx, fmt.Sprint(v...))
}
}
-func (l *logAdapter) Println(v ...interface{}) {
+func (l *logAdapter) Println(v ...any) {
if !l.silent {
log.Info(l.ctx, fmt.Sprintln(v...))
}
}
-func (l *logAdapter) Printf(format string, v ...interface{}) {
+func (l *logAdapter) Printf(format string, v ...any) {
if !l.silent {
log.Info(l.ctx, fmt.Sprintf(format, v...))
}
diff --git a/db/migrations/20250823142158_make_playqueue_position_int.sql b/db/migrations/20250823142158_make_playqueue_position_int.sql
new file mode 100644
index 000000000..de20f0c79
--- /dev/null
+++ b/db/migrations/20250823142158_make_playqueue_position_int.sql
@@ -0,0 +1,9 @@
+-- +goose Up
+-- +goose StatementBegin
+ALTER TABLE playqueue ADD COLUMN position_int integer;
+UPDATE playqueue SET position_int = CAST(position as INTEGER) ;
+ALTER TABLE playqueue DROP COLUMN position;
+ALTER TABLE playqueue RENAME COLUMN position_int TO position;
+-- +goose StatementEnd
+
+-- +goose Down
diff --git a/db/migrations/20251109010105_add_annotation_rating_date.sql b/db/migrations/20251109010105_add_annotation_rating_date.sql
new file mode 100644
index 000000000..9dac46a5e
--- /dev/null
+++ b/db/migrations/20251109010105_add_annotation_rating_date.sql
@@ -0,0 +1,7 @@
+-- +goose Up
+-- +goose StatementBegin
+ALTER TABLE annotation ADD COLUMN rated_at datetime;
+-- +goose StatementEnd
+
+-- +goose Down
+
\ No newline at end of file
diff --git a/db/migrations/20251206013022_create_scrobbles_table.sql b/db/migrations/20251206013022_create_scrobbles_table.sql
new file mode 100644
index 000000000..9791c48e3
--- /dev/null
+++ b/db/migrations/20251206013022_create_scrobbles_table.sql
@@ -0,0 +1,20 @@
+-- +goose Up
+-- +goose StatementBegin
+CREATE TABLE scrobbles(
+ media_file_id VARCHAR(255) NOT NULL
+ REFERENCES media_file(id)
+ ON DELETE CASCADE
+ ON UPDATE CASCADE,
+ user_id VARCHAR(255) NOT NULL
+ REFERENCES user(id)
+ ON DELETE CASCADE
+ ON UPDATE CASCADE,
+ submission_time INTEGER NOT NULL
+);
+CREATE INDEX scrobbles_date ON scrobbles (submission_time);
+-- +goose StatementEnd
+
+-- +goose Down
+-- +goose StatementBegin
+DROP TABLE scrobbles;
+-- +goose StatementEnd
diff --git a/db/migrations/20260104203627_playlist_case_insensitive_name.sql b/db/migrations/20260104203627_playlist_case_insensitive_name.sql
new file mode 100644
index 000000000..64b079cca
--- /dev/null
+++ b/db/migrations/20260104203627_playlist_case_insensitive_name.sql
@@ -0,0 +1,99 @@
+-- +goose Up
+-- Fix case-insensitive sorting for playlist names
+create table playlist_dg_tmp
+(
+ id varchar(255) not null
+ primary key,
+ name varchar(255) collate NOCASE default '' not null,
+ comment varchar(255) default '' not null,
+ duration real default 0 not null,
+ song_count integer default 0 not null,
+ public bool default FALSE not null,
+ created_at datetime,
+ updated_at datetime,
+ path string default '' not null,
+ sync bool default false not null,
+ size integer default 0 not null,
+ rules varchar,
+ evaluated_at datetime,
+ owner_id varchar(255) not null
+ constraint playlist_user_user_id_fk
+ references user
+ on update cascade on delete cascade
+);
+
+insert into playlist_dg_tmp(id, name, comment, duration, song_count, public, created_at, updated_at, path, sync, size,
+ rules, evaluated_at, owner_id)
+select id, name, comment, duration, song_count, public, created_at, updated_at, path, sync, size, rules, evaluated_at,
+ owner_id
+from playlist;
+
+drop table playlist;
+
+alter table playlist_dg_tmp
+ rename to playlist;
+
+create index playlist_name
+ on playlist (name);
+
+create index playlist_created_at
+ on playlist (created_at);
+
+create index playlist_updated_at
+ on playlist (updated_at);
+
+create index playlist_evaluated_at
+ on playlist (evaluated_at);
+
+create index playlist_size
+ on playlist (size);
+
+-- +goose Down
+-- Note: Downgrade loses the collation but preserves data
+create table playlist_dg_tmp
+(
+ id varchar(255) not null
+ primary key,
+ name varchar(255) default '' not null,
+ comment varchar(255) default '' not null,
+ duration real default 0 not null,
+ song_count integer default 0 not null,
+ public bool default FALSE not null,
+ created_at datetime,
+ updated_at datetime,
+ path string default '' not null,
+ sync bool default false not null,
+ size integer default 0 not null,
+ rules varchar,
+ evaluated_at datetime,
+ owner_id varchar(255) not null
+ constraint playlist_user_user_id_fk
+ references user
+ on update cascade on delete cascade
+);
+
+insert into playlist_dg_tmp(id, name, comment, duration, song_count, public, created_at, updated_at, path, sync, size,
+ rules, evaluated_at, owner_id)
+select id, name, comment, duration, song_count, public, created_at, updated_at, path, sync, size, rules, evaluated_at,
+ owner_id
+from playlist;
+
+drop table playlist;
+
+alter table playlist_dg_tmp
+ rename to playlist;
+
+create index playlist_name
+ on playlist (name);
+
+create index playlist_created_at
+ on playlist (created_at);
+
+create index playlist_updated_at
+ on playlist (updated_at);
+
+create index playlist_evaluated_at
+ on playlist (evaluated_at);
+
+create index playlist_size
+ on playlist (size);
diff --git a/db/migrations/20260106000620_create_plugin_table.sql b/db/migrations/20260106000620_create_plugin_table.sql
new file mode 100644
index 000000000..bcc83be0b
--- /dev/null
+++ b/db/migrations/20260106000620_create_plugin_table.sql
@@ -0,0 +1,19 @@
+-- +goose Up
+CREATE TABLE IF NOT EXISTS plugin (
+ id TEXT PRIMARY KEY,
+ path TEXT NOT NULL,
+ manifest JSONB NOT NULL,
+ config JSONB,
+ users JSONB,
+ all_users BOOL NOT NULL DEFAULT false,
+ libraries JSONB,
+ all_libraries BOOL NOT NULL DEFAULT false,
+ enabled BOOL NOT NULL DEFAULT false,
+ last_error TEXT,
+ sha256 TEXT NOT NULL,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL
+);
+
+-- +goose Down
+DROP TABLE IF EXISTS plugin;
diff --git a/db/migrations/20260117201522_add_avg_rating_column.sql b/db/migrations/20260117201522_add_avg_rating_column.sql
new file mode 100644
index 000000000..f5c8d4522
--- /dev/null
+++ b/db/migrations/20260117201522_add_avg_rating_column.sql
@@ -0,0 +1,23 @@
+-- +goose Up
+ALTER TABLE album ADD COLUMN average_rating REAL NOT NULL DEFAULT 0;
+ALTER TABLE media_file ADD COLUMN average_rating REAL NOT NULL DEFAULT 0;
+ALTER TABLE artist ADD COLUMN average_rating REAL NOT NULL DEFAULT 0;
+
+-- Populate average_rating from existing ratings
+UPDATE album SET average_rating = coalesce(
+ (SELECT round(avg(rating), 2) FROM annotation WHERE item_id = album.id AND item_type = 'album' AND rating > 0),
+ 0
+);
+UPDATE media_file SET average_rating = coalesce(
+ (SELECT round(avg(rating), 2) FROM annotation WHERE item_id = media_file.id AND item_type = 'media_file' AND rating > 0),
+ 0
+);
+UPDATE artist SET average_rating = coalesce(
+ (SELECT round(avg(rating), 2) FROM annotation WHERE item_id = artist.id AND item_type = 'artist' AND rating > 0),
+ 0
+);
+
+-- +goose Down
+ALTER TABLE artist DROP COLUMN average_rating;
+ALTER TABLE media_file DROP COLUMN average_rating;
+ALTER TABLE album DROP COLUMN average_rating;
diff --git a/db/migrations/20260220173400_add_fts5_search.go b/db/migrations/20260220173400_add_fts5_search.go
new file mode 100644
index 000000000..dc4cd647b
--- /dev/null
+++ b/db/migrations/20260220173400_add_fts5_search.go
@@ -0,0 +1,391 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upAddFts5Search, downAddFts5Search)
+}
+
+// stripPunct generates a SQL expression that strips common punctuation from a column or expression.
+// Used during migration to approximate the Go normalizeForFTS function for bulk-populating search_normalized.
+func stripPunct(col string) string {
+ return fmt.Sprintf(
+ `REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(%s, '.', ''), '/', ''), '-', ''), '''', ''), '&', ''), ',', '')`,
+ col,
+ )
+}
+
+func upAddFts5Search(ctx context.Context, tx *sql.Tx) error {
+ notice(tx, "Adding FTS5 full-text search indexes. This may take a moment on large libraries.")
+
+ // Step 1: Add search_participants and search_normalized columns to media_file, album, and artist
+ _, err := tx.ExecContext(ctx, `ALTER TABLE media_file ADD COLUMN search_participants TEXT NOT NULL DEFAULT ''`)
+ if err != nil {
+ return fmt.Errorf("adding search_participants to media_file: %w", err)
+ }
+ _, err = tx.ExecContext(ctx, `ALTER TABLE media_file ADD COLUMN search_normalized TEXT NOT NULL DEFAULT ''`)
+ if err != nil {
+ return fmt.Errorf("adding search_normalized to media_file: %w", err)
+ }
+ _, err = tx.ExecContext(ctx, `ALTER TABLE album ADD COLUMN search_participants TEXT NOT NULL DEFAULT ''`)
+ if err != nil {
+ return fmt.Errorf("adding search_participants to album: %w", err)
+ }
+ _, err = tx.ExecContext(ctx, `ALTER TABLE album ADD COLUMN search_normalized TEXT NOT NULL DEFAULT ''`)
+ if err != nil {
+ return fmt.Errorf("adding search_normalized to album: %w", err)
+ }
+ _, err = tx.ExecContext(ctx, `ALTER TABLE artist ADD COLUMN search_normalized TEXT NOT NULL DEFAULT ''`)
+ if err != nil {
+ return fmt.Errorf("adding search_normalized to artist: %w", err)
+ }
+
+ // Step 2: Populate search_participants from participants JSON.
+ // Extract all "name" values from the participants JSON structure.
+ // participants is a JSON object like: {"artist":[{"name":"...","id":"..."}],"albumartist":[...]}
+ // We use json_each + json_extract to flatten all names into a space-separated string.
+ _, err = tx.ExecContext(ctx, `
+ UPDATE media_file SET search_participants = COALESCE(
+ (SELECT group_concat(json_extract(je2.value, '$.name'), ' ')
+ FROM json_each(media_file.participants) AS je1,
+ json_each(je1.value) AS je2
+ WHERE json_extract(je2.value, '$.name') IS NOT NULL),
+ ''
+ )
+ WHERE participants IS NOT NULL AND participants != '' AND participants != '{}'
+ `)
+ if err != nil {
+ return fmt.Errorf("populating media_file search_participants: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ UPDATE album SET search_participants = COALESCE(
+ (SELECT group_concat(json_extract(je2.value, '$.name'), ' ')
+ FROM json_each(album.participants) AS je1,
+ json_each(je1.value) AS je2
+ WHERE json_extract(je2.value, '$.name') IS NOT NULL),
+ ''
+ )
+ WHERE participants IS NOT NULL AND participants != '' AND participants != '{}'
+ `)
+ if err != nil {
+ return fmt.Errorf("populating album search_participants: %w", err)
+ }
+
+ // Step 2b: Populate search_normalized using SQL REPLACE chains for common punctuation.
+ // The Go code will compute the precise value on next scan; this is a best-effort approximation.
+ _, err = tx.ExecContext(ctx, fmt.Sprintf(`
+ UPDATE artist SET search_normalized = %s
+ WHERE name != %s`,
+ stripPunct("name"), stripPunct("name")))
+ if err != nil {
+ return fmt.Errorf("populating artist search_normalized: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, fmt.Sprintf(`
+ UPDATE album SET search_normalized = TRIM(%s || ' ' || %s)
+ WHERE name != %s OR COALESCE(album_artist, '') != %s`,
+ stripPunct("name"), stripPunct("COALESCE(album_artist, '')"),
+ stripPunct("name"), stripPunct("COALESCE(album_artist, '')")))
+ if err != nil {
+ return fmt.Errorf("populating album search_normalized: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, fmt.Sprintf(`
+ UPDATE media_file SET search_normalized =
+ TRIM(%s || ' ' || %s || ' ' || %s || ' ' || %s)
+ WHERE title != %s
+ OR COALESCE(album, '') != %s
+ OR COALESCE(artist, '') != %s
+ OR COALESCE(album_artist, '') != %s`,
+ stripPunct("title"), stripPunct("COALESCE(album, '')"),
+ stripPunct("COALESCE(artist, '')"), stripPunct("COALESCE(album_artist, '')"),
+ stripPunct("title"), stripPunct("COALESCE(album, '')"),
+ stripPunct("COALESCE(artist, '')"), stripPunct("COALESCE(album_artist, '')")))
+ if err != nil {
+ return fmt.Errorf("populating media_file search_normalized: %w", err)
+ }
+
+ // Step 3: Create FTS5 virtual tables
+ _, err = tx.ExecContext(ctx, `
+ CREATE VIRTUAL TABLE IF NOT EXISTS media_file_fts USING fts5(
+ title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized,
+ content='', content_rowid='rowid',
+ tokenize='unicode61 remove_diacritics 2'
+ )
+ `)
+ if err != nil {
+ return fmt.Errorf("creating media_file_fts: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE VIRTUAL TABLE IF NOT EXISTS album_fts USING fts5(
+ name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized,
+ content='', content_rowid='rowid',
+ tokenize='unicode61 remove_diacritics 2'
+ )
+ `)
+ if err != nil {
+ return fmt.Errorf("creating album_fts: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE VIRTUAL TABLE IF NOT EXISTS artist_fts USING fts5(
+ name, sort_artist_name, search_normalized,
+ content='', content_rowid='rowid',
+ tokenize='unicode61 remove_diacritics 2'
+ )
+ `)
+ if err != nil {
+ return fmt.Errorf("creating artist_fts: %w", err)
+ }
+
+ // Step 4: Bulk-populate FTS5 indexes from existing data
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO media_file_fts(rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ SELECT rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ COALESCE(disc_subtitle, ''), COALESCE(search_participants, ''),
+ COALESCE(search_normalized, '')
+ FROM media_file
+ `)
+ if err != nil {
+ return fmt.Errorf("populating media_file_fts: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO album_fts(rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ SELECT rowid, name, COALESCE(sort_album_name, ''), COALESCE(album_artist, ''),
+ COALESCE(search_participants, ''), COALESCE(discs, ''),
+ COALESCE(catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(album.tags, '$.albumversion') AS je), ''),
+ COALESCE(search_normalized, '')
+ FROM album
+ `)
+ if err != nil {
+ return fmt.Errorf("populating album_fts: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO artist_fts(rowid, name, sort_artist_name, search_normalized)
+ SELECT rowid, name, COALESCE(sort_artist_name, ''), COALESCE(search_normalized, '')
+ FROM artist
+ `)
+ if err != nil {
+ return fmt.Errorf("populating artist_fts: %w", err)
+ }
+
+ // Step 5: Create triggers for media_file
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER media_file_fts_ai AFTER INSERT ON media_file BEGIN
+ INSERT INTO media_file_fts(rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES (NEW.rowid, NEW.title, NEW.album, NEW.artist, NEW.album_artist,
+ NEW.sort_title, NEW.sort_album_name, NEW.sort_artist_name, NEW.sort_album_artist_name,
+ COALESCE(NEW.disc_subtitle, ''), COALESCE(NEW.search_participants, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating media_file_fts insert trigger: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER media_file_fts_ad AFTER DELETE ON media_file BEGIN
+ INSERT INTO media_file_fts(media_file_fts, rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.title, OLD.album, OLD.artist, OLD.album_artist,
+ OLD.sort_title, OLD.sort_album_name, OLD.sort_artist_name, OLD.sort_album_artist_name,
+ COALESCE(OLD.disc_subtitle, ''), COALESCE(OLD.search_participants, ''),
+ COALESCE(OLD.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating media_file_fts delete trigger: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER media_file_fts_au AFTER UPDATE ON media_file
+ WHEN
+ OLD.title IS NOT NEW.title OR
+ OLD.album IS NOT NEW.album OR
+ OLD.artist IS NOT NEW.artist OR
+ OLD.album_artist IS NOT NEW.album_artist OR
+ OLD.sort_title IS NOT NEW.sort_title OR
+ OLD.sort_album_name IS NOT NEW.sort_album_name OR
+ OLD.sort_artist_name IS NOT NEW.sort_artist_name OR
+ OLD.sort_album_artist_name IS NOT NEW.sort_album_artist_name OR
+ OLD.disc_subtitle IS NOT NEW.disc_subtitle OR
+ OLD.search_participants IS NOT NEW.search_participants OR
+ OLD.search_normalized IS NOT NEW.search_normalized
+ BEGIN
+ INSERT INTO media_file_fts(media_file_fts, rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.title, OLD.album, OLD.artist, OLD.album_artist,
+ OLD.sort_title, OLD.sort_album_name, OLD.sort_artist_name, OLD.sort_album_artist_name,
+ COALESCE(OLD.disc_subtitle, ''), COALESCE(OLD.search_participants, ''),
+ COALESCE(OLD.search_normalized, ''));
+ INSERT INTO media_file_fts(rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES (NEW.rowid, NEW.title, NEW.album, NEW.artist, NEW.album_artist,
+ NEW.sort_title, NEW.sort_album_name, NEW.sort_artist_name, NEW.sort_album_artist_name,
+ COALESCE(NEW.disc_subtitle, ''), COALESCE(NEW.search_participants, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating media_file_fts update trigger: %w", err)
+ }
+
+ // Step 6: Create triggers for album
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER album_fts_ai AFTER INSERT ON album BEGIN
+ INSERT INTO album_fts(rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_album_name, ''), COALESCE(NEW.album_artist, ''),
+ COALESCE(NEW.search_participants, ''), COALESCE(NEW.discs, ''),
+ COALESCE(NEW.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(NEW.tags, '$.albumversion') AS je), ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating album_fts insert trigger: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER album_fts_ad AFTER DELETE ON album BEGIN
+ INSERT INTO album_fts(album_fts, rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_album_name, ''), COALESCE(OLD.album_artist, ''),
+ COALESCE(OLD.search_participants, ''), COALESCE(OLD.discs, ''),
+ COALESCE(OLD.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(OLD.tags, '$.albumversion') AS je), ''),
+ COALESCE(OLD.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating album_fts delete trigger: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER album_fts_au AFTER UPDATE ON album
+ WHEN
+ OLD.name IS NOT NEW.name OR
+ OLD.sort_album_name IS NOT NEW.sort_album_name OR
+ OLD.album_artist IS NOT NEW.album_artist OR
+ OLD.search_participants IS NOT NEW.search_participants OR
+ OLD.discs IS NOT NEW.discs OR
+ OLD.catalog_num IS NOT NEW.catalog_num OR
+ OLD.tags IS NOT NEW.tags OR
+ OLD.search_normalized IS NOT NEW.search_normalized
+ BEGIN
+ INSERT INTO album_fts(album_fts, rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_album_name, ''), COALESCE(OLD.album_artist, ''),
+ COALESCE(OLD.search_participants, ''), COALESCE(OLD.discs, ''),
+ COALESCE(OLD.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(OLD.tags, '$.albumversion') AS je), ''),
+ COALESCE(OLD.search_normalized, ''));
+ INSERT INTO album_fts(rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_album_name, ''), COALESCE(NEW.album_artist, ''),
+ COALESCE(NEW.search_participants, ''), COALESCE(NEW.discs, ''),
+ COALESCE(NEW.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(NEW.tags, '$.albumversion') AS je), ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating album_fts update trigger: %w", err)
+ }
+
+ // Step 7: Create triggers for artist
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER artist_fts_ai AFTER INSERT ON artist BEGIN
+ INSERT INTO artist_fts(rowid, name, sort_artist_name, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_artist_name, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating artist_fts insert trigger: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER artist_fts_ad AFTER DELETE ON artist BEGIN
+ INSERT INTO artist_fts(artist_fts, rowid, name, sort_artist_name, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_artist_name, ''),
+ COALESCE(OLD.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating artist_fts delete trigger: %w", err)
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ CREATE TRIGGER artist_fts_au AFTER UPDATE ON artist
+ WHEN
+ OLD.name IS NOT NEW.name OR
+ OLD.sort_artist_name IS NOT NEW.sort_artist_name OR
+ OLD.search_normalized IS NOT NEW.search_normalized
+ BEGIN
+ INSERT INTO artist_fts(artist_fts, rowid, name, sort_artist_name, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_artist_name, ''),
+ COALESCE(OLD.search_normalized, ''));
+ INSERT INTO artist_fts(rowid, name, sort_artist_name, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_artist_name, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `)
+ if err != nil {
+ return fmt.Errorf("creating artist_fts update trigger: %w", err)
+ }
+
+ return nil
+}
+
+func downAddFts5Search(ctx context.Context, tx *sql.Tx) error {
+ for _, trigger := range []string{
+ "media_file_fts_ai", "media_file_fts_ad", "media_file_fts_au",
+ "album_fts_ai", "album_fts_ad", "album_fts_au",
+ "artist_fts_ai", "artist_fts_ad", "artist_fts_au",
+ } {
+ _, err := tx.ExecContext(ctx, "DROP TRIGGER IF EXISTS "+trigger)
+ if err != nil {
+ return fmt.Errorf("dropping trigger %s: %w", trigger, err)
+ }
+ }
+
+ for _, table := range []string{"media_file_fts", "album_fts", "artist_fts"} {
+ _, err := tx.ExecContext(ctx, "DROP TABLE IF EXISTS "+table)
+ if err != nil {
+ return fmt.Errorf("dropping table %s: %w", table, err)
+ }
+ }
+
+ // Note: We don't drop search_participants columns because SQLite doesn't support DROP COLUMN
+ // on older versions, and the column is harmless if left in place.
+ return nil
+}
diff --git a/db/migrations/20260228020813_add_plugin_allow_write_access.sql b/db/migrations/20260228020813_add_plugin_allow_write_access.sql
new file mode 100644
index 000000000..e17d874a5
--- /dev/null
+++ b/db/migrations/20260228020813_add_plugin_allow_write_access.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE plugin ADD COLUMN allow_write_access BOOL NOT NULL DEFAULT false;
+
+-- +goose Down
+ALTER TABLE plugin DROP COLUMN allow_write_access;
diff --git a/db/migrations/20260228172956_add_playlist_image_file.go b/db/migrations/20260228172956_add_playlist_image_file.go
new file mode 100644
index 000000000..da2177aba
--- /dev/null
+++ b/db/migrations/20260228172956_add_playlist_image_file.go
@@ -0,0 +1,22 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upAddPlaylistImageFile, downAddPlaylistImageFile)
+}
+
+func upAddPlaylistImageFile(ctx context.Context, tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, `ALTER TABLE playlist ADD COLUMN image_file VARCHAR(255) DEFAULT '';`)
+ return err
+}
+
+func downAddPlaylistImageFile(ctx context.Context, tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, `ALTER TABLE playlist DROP COLUMN image_file;`)
+ return err
+}
diff --git a/db/migrations/20260302021413_rename_playlist_image_fields.go b/db/migrations/20260302021413_rename_playlist_image_fields.go
new file mode 100644
index 000000000..1e9754637
--- /dev/null
+++ b/db/migrations/20260302021413_rename_playlist_image_fields.go
@@ -0,0 +1,30 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upRenamePlaylistImageFields, downRenamePlaylistImageFields)
+}
+
+func upRenamePlaylistImageFields(ctx context.Context, tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, `ALTER TABLE playlist RENAME COLUMN image_file TO uploaded_image;`)
+ if err != nil {
+ return err
+ }
+ _, err = tx.ExecContext(ctx, `ALTER TABLE playlist ADD COLUMN external_image_url VARCHAR(255) DEFAULT '';`)
+ return err
+}
+
+func downRenamePlaylistImageFields(ctx context.Context, tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, `ALTER TABLE playlist DROP COLUMN external_image_url;`)
+ if err != nil {
+ return err
+ }
+ _, err = tx.ExecContext(ctx, `ALTER TABLE playlist RENAME COLUMN uploaded_image TO image_file;`)
+ return err
+}
diff --git a/db/migrations/20260307175815_add_codec_and_update_transcodings.go b/db/migrations/20260307175815_add_codec_and_update_transcodings.go
new file mode 100644
index 000000000..4e8b1b7f5
--- /dev/null
+++ b/db/migrations/20260307175815_add_codec_and_update_transcodings.go
@@ -0,0 +1,73 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/navidrome/navidrome/model/id"
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upAddCodecAndUpdateTranscodings, downAddCodecAndUpdateTranscodings)
+}
+
+func upAddCodecAndUpdateTranscodings(_ context.Context, tx *sql.Tx) error {
+ // Add codec column to media_file.
+ _, err := tx.Exec(`ALTER TABLE media_file ADD COLUMN codec VARCHAR(255) DEFAULT '' NOT NULL`)
+ if err != nil {
+ return err
+ }
+ _, err = tx.Exec(`CREATE INDEX IF NOT EXISTS media_file_codec ON media_file(codec)`)
+ if err != nil {
+ return err
+ }
+
+ // Update old AAC default (adts) to new default (ipod with fragmented MP4).
+ // Only affects users who still have the unmodified old default command.
+ _, err = tx.Exec(
+ `UPDATE transcoding SET command = ? WHERE target_format = 'aac' AND command = ?`,
+ "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -c:a aac -f ipod -movflags frag_keyframe+empty_moov -",
+ "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -c:a aac -f adts -",
+ )
+ if err != nil {
+ return err
+ }
+
+ // Add FLAC transcoding for existing installations that were seeded before FLAC was added.
+ var count int
+ err = tx.QueryRow("SELECT COUNT(*) FROM transcoding WHERE target_format = 'flac'").Scan(&count)
+ if err != nil {
+ return err
+ }
+ if count == 0 {
+ _, err = tx.Exec(
+ "INSERT INTO transcoding (id, name, target_format, default_bit_rate, command) VALUES (?, ?, ?, ?, ?)",
+ id.NewRandom(), "flac audio", "flac", 0,
+ "ffmpeg -i %s -ss %t -map 0:a:0 -v 0 -c:a flac -f flac -",
+ )
+ if err != nil {
+ return err
+ }
+ }
+
+ // Add probe_data column for caching ffprobe results.
+ _, err = tx.Exec(`ALTER TABLE media_file ADD COLUMN probe_data TEXT DEFAULT NULL`)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func downAddCodecAndUpdateTranscodings(_ context.Context, tx *sql.Tx) error {
+ _, err := tx.Exec(`ALTER TABLE media_file DROP COLUMN probe_data`)
+ if err != nil {
+ return err
+ }
+ _, err = tx.Exec(`DROP INDEX IF EXISTS media_file_codec`)
+ if err != nil {
+ return err
+ }
+ _, err = tx.Exec(`ALTER TABLE media_file DROP COLUMN codec`)
+ return err
+}
diff --git a/db/migrations/20260309120007_fix_probe_data_null.go b/db/migrations/20260309120007_fix_probe_data_null.go
new file mode 100644
index 000000000..a7e7366ed
--- /dev/null
+++ b/db/migrations/20260309120007_fix_probe_data_null.go
@@ -0,0 +1,28 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upFixProbeDataNull, downFixProbeDataNull)
+}
+
+func upFixProbeDataNull(_ context.Context, tx *sql.Tx) error {
+ // Recreate probe_data column as NOT NULL with empty string default.
+ // The previous migration created it with DEFAULT NULL, which causes
+ // scan errors when reading into Go string fields.
+ _, err := tx.Exec(`ALTER TABLE media_file DROP COLUMN probe_data`)
+ if err != nil {
+ return err
+ }
+ _, err = tx.Exec(`ALTER TABLE media_file ADD COLUMN probe_data TEXT DEFAULT '' NOT NULL`)
+ return err
+}
+
+func downFixProbeDataNull(_ context.Context, tx *sql.Tx) error {
+ return nil
+}
diff --git a/db/migrations/20260309203355_ensure_default_transcodings.go b/db/migrations/20260309203355_ensure_default_transcodings.go
new file mode 100644
index 000000000..ab6d24952
--- /dev/null
+++ b/db/migrations/20260309203355_ensure_default_transcodings.go
@@ -0,0 +1,44 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/model/id"
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upEnsureDefaultTranscodings, downEnsureDefaultTranscodings)
+}
+
+func upEnsureDefaultTranscodings(_ context.Context, tx *sql.Tx) error {
+ // Older installations may be missing default transcodings that were added
+ // after the initial seeding (e.g., aac was added later than mp3/opus).
+ // Insert any missing defaults without touching user-customized entries.
+ // Check both target_format and name since both have UNIQUE constraints,
+ // and older entries may have a different target_format (e.g., 'oga' vs 'opus')
+ // but the same name.
+ for _, t := range consts.DefaultTranscodings {
+ var count int
+ err := tx.QueryRow("SELECT COUNT(*) FROM transcoding WHERE target_format = ? OR name = ?", t.TargetFormat, t.Name).Scan(&count)
+ if err != nil {
+ return err
+ }
+ if count == 0 {
+ _, err = tx.Exec(
+ "INSERT INTO transcoding (id, name, target_format, default_bit_rate, command) VALUES (?, ?, ?, ?, ?)",
+ id.NewRandom(), t.Name, t.TargetFormat, t.DefaultBitRate, t.Command,
+ )
+ if err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func downEnsureDefaultTranscodings(_ context.Context, tx *sql.Tx) error {
+ return nil
+}
diff --git a/db/migrations/20260310113858_fix_aac_transcode_command.go b/db/migrations/20260310113858_fix_aac_transcode_command.go
new file mode 100644
index 000000000..588137383
--- /dev/null
+++ b/db/migrations/20260310113858_fix_aac_transcode_command.go
@@ -0,0 +1,30 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upFixAacTranscodeCommand, downFixAacTranscodeCommand)
+}
+
+func upFixAacTranscodeCommand(_ context.Context, tx *sql.Tx) error {
+ // The old AAC command used `-f ipod -movflags frag_keyframe+empty_moov` which produces
+ // corrupt/silent audio when ffmpeg pipes to stdout (confirmed in ffmpeg 8.0+).
+ // Switch to `-f adts` (raw AAC framing) which works reliably via pipe.
+ // Only update rows that still have the old default command.
+ const oldCommand = "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -c:a aac -f ipod -movflags frag_keyframe+empty_moov -"
+ const newCommand = "ffmpeg -i %s -ss %t -map 0:a:0 -b:a %bk -v 0 -c:a aac -f adts -"
+ _, err := tx.Exec(
+ "UPDATE transcoding SET command = ? WHERE target_format = 'aac' AND command = ?",
+ newCommand, oldCommand,
+ )
+ return err
+}
+
+func downFixAacTranscodeCommand(_ context.Context, tx *sql.Tx) error {
+ return nil
+}
diff --git a/db/migrations/20260315233131_add_artist_uploaded_image.go b/db/migrations/20260315233131_add_artist_uploaded_image.go
new file mode 100644
index 000000000..964e346f5
--- /dev/null
+++ b/db/migrations/20260315233131_add_artist_uploaded_image.go
@@ -0,0 +1,22 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upAddArtistUploadedImage, downAddArtistUploadedImage)
+}
+
+func upAddArtistUploadedImage(ctx context.Context, tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, `ALTER TABLE artist ADD COLUMN uploaded_image VARCHAR(255) DEFAULT ''`)
+ return err
+}
+
+func downAddArtistUploadedImage(ctx context.Context, tx *sql.Tx) error {
+ // This code is executed when the migration is rolled back.
+ return nil
+}
diff --git a/db/migrations/20260316000000_normalize_timestamps.sql b/db/migrations/20260316000000_normalize_timestamps.sql
new file mode 100644
index 000000000..a2e1183e9
--- /dev/null
+++ b/db/migrations/20260316000000_normalize_timestamps.sql
@@ -0,0 +1,74 @@
+-- +goose Up
+
+-- Normalize T-format timestamps (RFC3339Nano with 'T' separator) to SQLite-compatible format.
+-- SQLite uses string comparison for ORDER BY on TEXT columns, so 'T' (ASCII 84) > ' ' (ASCII 32)
+-- causes T-format timestamps to sort after space-format ones, breaking "Recently Added" ordering.
+
+UPDATE album SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE album SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE album SET imported_at = replace(replace(imported_at, 'T', ' '), 'Z', '+00:00') WHERE imported_at LIKE '%T%';
+UPDATE album SET external_info_updated_at = replace(replace(external_info_updated_at, 'T', ' '), 'Z', '+00:00') WHERE external_info_updated_at LIKE '%T%';
+
+UPDATE media_file SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE media_file SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE media_file SET birth_time = replace(replace(birth_time, 'T', ' '), 'Z', '+00:00') WHERE birth_time LIKE '%T%';
+
+UPDATE artist SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE artist SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE artist SET external_info_updated_at = replace(replace(external_info_updated_at, 'T', ' '), 'Z', '+00:00') WHERE external_info_updated_at LIKE '%T%';
+
+UPDATE annotation SET play_date = replace(replace(play_date, 'T', ' '), 'Z', '+00:00') WHERE play_date LIKE '%T%';
+UPDATE annotation SET starred_at = replace(replace(starred_at, 'T', ' '), 'Z', '+00:00') WHERE starred_at LIKE '%T%';
+UPDATE annotation SET rated_at = replace(replace(rated_at, 'T', ' '), 'Z', '+00:00') WHERE rated_at LIKE '%T%';
+
+UPDATE playlist SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE playlist SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE playlist SET evaluated_at = replace(replace(evaluated_at, 'T', ' '), 'Z', '+00:00') WHERE evaluated_at LIKE '%T%';
+
+UPDATE user SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE user SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE user SET last_login_at = replace(replace(last_login_at, 'T', ' '), 'Z', '+00:00') WHERE last_login_at LIKE '%T%';
+UPDATE user SET last_access_at = replace(replace(last_access_at, 'T', ' '), 'Z', '+00:00') WHERE last_access_at LIKE '%T%';
+
+UPDATE player SET last_seen = replace(replace(last_seen, 'T', ' '), 'Z', '+00:00') WHERE last_seen LIKE '%T%';
+
+UPDATE playqueue SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE playqueue SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+
+UPDATE bookmark SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE bookmark SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+
+UPDATE share SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE share SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE share SET expires_at = replace(replace(expires_at, 'T', ' '), 'Z', '+00:00') WHERE expires_at LIKE '%T%';
+UPDATE share SET last_visited_at = replace(replace(last_visited_at, 'T', ' '), 'Z', '+00:00') WHERE last_visited_at LIKE '%T%';
+
+UPDATE radio SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE radio SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+
+UPDATE folder SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE folder SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE folder SET images_updated_at = replace(replace(images_updated_at, 'T', ' '), 'Z', '+00:00') WHERE images_updated_at LIKE '%T%';
+
+UPDATE library SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE library SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+UPDATE library SET last_scan_at = replace(replace(last_scan_at, 'T', ' '), 'Z', '+00:00') WHERE last_scan_at LIKE '%T%';
+UPDATE library SET last_scan_started_at = replace(replace(last_scan_started_at, 'T', ' '), 'Z', '+00:00') WHERE last_scan_started_at LIKE '%T%';
+
+UPDATE scrobble_buffer SET play_time = replace(replace(play_time, 'T', ' '), 'Z', '+00:00') WHERE play_time LIKE '%T%';
+UPDATE scrobble_buffer SET enqueue_time = replace(replace(enqueue_time, 'T', ' '), 'Z', '+00:00') WHERE enqueue_time LIKE '%T%';
+
+UPDATE plugin SET created_at = replace(replace(created_at, 'T', ' '), 'Z', '+00:00') WHERE created_at LIKE '%T%';
+UPDATE plugin SET updated_at = replace(replace(updated_at, 'T', ' '), 'Z', '+00:00') WHERE updated_at LIKE '%T%';
+
+-- Replace plain indexes with expression indexes for datetime()-based sorting
+DROP INDEX IF EXISTS album_created_at;
+CREATE INDEX album_created_at ON album(datetime(created_at));
+DROP INDEX IF EXISTS album_updated_at;
+CREATE INDEX album_updated_at ON album(datetime(updated_at));
+
+-- +goose Down
+DROP INDEX IF EXISTS album_created_at;
+CREATE INDEX album_created_at ON album(created_at);
+DROP INDEX IF EXISTS album_updated_at;
+CREATE INDEX album_updated_at ON album(updated_at);
diff --git a/db/migrations/20260318182414_add_radio_uploaded_image.go b/db/migrations/20260318182414_add_radio_uploaded_image.go
new file mode 100644
index 000000000..e92a6d2ef
--- /dev/null
+++ b/db/migrations/20260318182414_add_radio_uploaded_image.go
@@ -0,0 +1,22 @@
+package migrations
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/pressly/goose/v3"
+)
+
+func init() {
+ goose.AddMigrationContext(upAddRadioUploadedImage, downAddRadioUploadedImage)
+}
+
+func upAddRadioUploadedImage(ctx context.Context, tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, `ALTER TABLE radio ADD COLUMN uploaded_image VARCHAR(255) NOT NULL DEFAULT ''`)
+ return err
+}
+
+func downAddRadioUploadedImage(ctx context.Context, tx *sql.Tx) error {
+ // This code is executed when the migration is rolled back.
+ return nil
+}
diff --git a/db/migrations/migration.go b/db/migrations/migration.go
index 8d8f8a91e..fde6f5817 100644
--- a/db/migrations/migration.go
+++ b/db/migrations/migration.go
@@ -7,6 +7,7 @@ import (
"strings"
"sync"
+ "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
)
@@ -21,11 +22,13 @@ func notice(tx *sql.Tx, msg string) {
// Call this in migrations that requires a full rescan
func forceFullRescan(tx *sql.Tx) error {
// If a full scan is required, most probably the query optimizer is outdated, so we run `analyze`.
- _, err := tx.Exec(`ANALYZE;`)
- if err != nil {
- return err
+ if conf.Server.DevOptimizeDB {
+ _, err := tx.Exec(`ANALYZE;`)
+ if err != nil {
+ return err
+ }
}
- _, err = tx.Exec(fmt.Sprintf(`
+ _, err := tx.Exec(fmt.Sprintf(`
INSERT OR REPLACE into property (id, value) values ('%s', '1');
`, consts.FullScanAfterMigrationFlagKey))
return err
diff --git a/go.mod b/go.mod
index e1a827f1d..487b57ef7 100644
--- a/go.mod
+++ b/go.mod
@@ -1,135 +1,145 @@
module github.com/navidrome/navidrome
-go 1.24.5
+go 1.25.0
-// Fork to fix https://github.com/navidrome/navidrome/pull/3254
-replace github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 => github.com/deluan/tag v0.0.0-20241002021117-dfe5e6ea396d
+// Fork to implement raw tags support
+replace go.senan.xyz/taglib => github.com/deluan/go-taglib v0.0.0-20260307161927-168f6e74ada7
require (
github.com/Masterminds/squirrel v1.5.4
- github.com/RaveNoX/go-jsoncommentstrip v1.0.0
github.com/andybalholm/cascadia v1.3.3
- github.com/bmatcuk/doublestar/v4 v4.9.0
+ github.com/bmatcuk/doublestar/v4 v4.10.0
github.com/bradleyjkemp/cupaloy/v2 v2.8.0
github.com/deluan/rest v0.0.0-20211102003136-6260bc399cbf
github.com/deluan/sanitize v0.0.0-20241120162836-fdfd8fdfaa55
github.com/dexterlb/mpvipc v0.0.0-20241005113212-7cdefca0e933
- github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
- github.com/disintegration/imaging v1.6.2
github.com/djherbis/atime v1.1.0
github.com/djherbis/fscache v0.10.2-0.20231127215153-442a07e326c4
github.com/djherbis/stream v1.4.0
github.com/djherbis/times v1.6.0
github.com/dustin/go-humanize v1.0.1
+ github.com/extism/go-sdk v1.7.1
github.com/fatih/structs v1.1.0
- github.com/go-chi/chi/v5 v5.2.2
+ github.com/gen2brain/webp v0.5.5
+ github.com/go-chi/chi/v5 v5.2.5
github.com/go-chi/cors v1.2.2
github.com/go-chi/httprate v0.15.0
- github.com/go-chi/jwtauth/v5 v5.3.3
+ github.com/go-chi/jwtauth/v5 v5.4.0
github.com/go-viper/encoding/ini v0.1.1
- github.com/gohugoio/hashstructure v0.5.0
+ github.com/gohugoio/hashstructure v0.6.0
github.com/google/go-pipeline v0.0.0-20230411140531-6cbedfc1d3fc
github.com/google/uuid v1.6.0
- github.com/google/wire v0.6.0
+ github.com/google/wire v0.7.0
github.com/gorilla/websocket v1.5.3
github.com/hashicorp/go-multierror v1.1.1
github.com/jellydator/ttlcache/v3 v3.4.0
github.com/kardianos/service v1.2.4
- github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
- github.com/knqyf263/go-plugin v0.9.0
github.com/kr/pretty v0.3.1
- github.com/lestrrat-go/jwx/v2 v2.1.6
- github.com/matoous/go-nanoid/v2 v2.1.0
- github.com/mattn/go-sqlite3 v1.14.29
+ github.com/lestrrat-go/jwx/v3 v3.0.13
+ github.com/mattn/go-sqlite3 v1.14.37
github.com/microcosm-cc/bluemonday v1.0.27
github.com/mileusna/useragent v1.3.5
- github.com/onsi/ginkgo/v2 v2.23.4
- github.com/onsi/gomega v1.38.0
+ github.com/onsi/ginkgo/v2 v2.28.1
+ github.com/onsi/gomega v1.39.1
github.com/pelletier/go-toml/v2 v2.2.4
- github.com/pocketbase/dbx v1.11.0
- github.com/pressly/goose/v3 v3.24.3
- github.com/prometheus/client_golang v1.22.0
+ github.com/pocketbase/dbx v1.12.0
+ github.com/pressly/goose/v3 v3.27.0
+ github.com/prometheus/client_golang v1.23.2
github.com/rjeczalik/notify v0.9.3
github.com/robfig/cron/v3 v3.0.1
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06
- github.com/sirupsen/logrus v1.9.3
- github.com/spf13/cobra v1.9.1
- github.com/spf13/viper v1.20.1
- github.com/stretchr/testify v1.10.0
- github.com/tetratelabs/wazero v1.9.0
+ github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
+ github.com/sirupsen/logrus v1.9.4
+ github.com/spf13/cobra v1.10.2
+ github.com/spf13/viper v1.21.0
+ github.com/stretchr/testify v1.11.1
+ github.com/tetratelabs/wazero v1.11.0
github.com/unrolled/secure v1.17.0
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342
+ go.senan.xyz/taglib v0.11.1
go.uber.org/goleak v1.3.0
- golang.org/x/exp v0.0.0-20250718183923-645b1fa84792
- golang.org/x/image v0.29.0
- golang.org/x/net v0.42.0
- golang.org/x/sync v0.16.0
- golang.org/x/sys v0.34.0
- golang.org/x/text v0.27.0
- golang.org/x/time v0.12.0
- google.golang.org/protobuf v1.36.6
+ golang.org/x/image v0.37.0
+ golang.org/x/net v0.52.0
+ golang.org/x/sync v0.20.0
+ golang.org/x/sys v0.42.0
+ golang.org/x/term v0.41.0
+ golang.org/x/text v0.35.0
+ golang.org/x/time v0.15.0
gopkg.in/yaml.v3 v3.0.1
)
require (
dario.cat/mergo v1.0.2 // indirect
+ github.com/Masterminds/semver/v3 v3.4.0 // indirect
github.com/atombender/go-jsonschema v0.20.0 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/reflex v0.3.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
- github.com/creack/pty v1.1.11 // indirect
+ github.com/creack/pty v1.1.24 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
- github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
+ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect
+ github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
+ github.com/ebitengine/purego v0.10.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
- github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
- github.com/goccy/go-json v0.10.5 // indirect
- github.com/goccy/go-yaml v1.17.1 // indirect
+ github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
+ github.com/gobwas/glob v0.2.3 // indirect
+ github.com/goccy/go-json v0.10.6 // indirect
+ github.com/goccy/go-yaml v1.19.2 // indirect
github.com/google/go-cmp v0.7.0 // indirect
- github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect
+ github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc // indirect
github.com/google/subcommands v1.2.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
+ github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/lestrrat-go/blackmagic v1.0.4 // indirect
+ github.com/lestrrat-go/dsig v1.0.0 // indirect
+ github.com/lestrrat-go/dsig-secp256k1 v1.0.0 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
- github.com/lestrrat-go/httprc v1.0.6 // indirect
- github.com/lestrrat-go/iter v1.0.2 // indirect
- github.com/lestrrat-go/option v1.0.1 // indirect
+ github.com/lestrrat-go/httprc/v3 v3.0.4 // indirect
+ github.com/lestrrat-go/option/v2 v2.0.0 // indirect
+ github.com/maruel/natural v1.3.0 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ogier/pflag v0.0.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
- github.com/prometheus/client_model v0.6.1 // indirect
- github.com/prometheus/common v0.62.0 // indirect
- github.com/prometheus/procfs v0.16.1 // indirect
+ github.com/prometheus/client_model v0.6.2 // indirect
+ github.com/prometheus/common v0.67.5 // indirect
+ github.com/prometheus/procfs v0.19.2 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
- github.com/sagikazarmark/locafero v0.9.0 // indirect
+ github.com/sagikazarmark/locafero v0.12.0 // indirect
github.com/sanity-io/litter v1.5.8 // indirect
- github.com/segmentio/asm v1.2.0 // indirect
+ github.com/segmentio/asm v1.2.1 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/sosodev/duration v1.3.1 // indirect
- github.com/sourcegraph/conc v0.3.0 // indirect
- github.com/spf13/afero v1.14.0 // indirect
- github.com/spf13/cast v1.9.2 // indirect
- github.com/spf13/pflag v1.0.7 // indirect
- github.com/stretchr/objx v0.5.2 // indirect
+ github.com/spf13/afero v1.15.0 // indirect
+ github.com/spf13/cast v1.10.0 // indirect
+ github.com/spf13/pflag v1.0.10 // indirect
+ github.com/stretchr/objx v0.5.3 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
- github.com/zeebo/xxh3 v1.0.2 // indirect
- go.uber.org/automaxprocs v1.6.0 // indirect
+ github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
+ github.com/valyala/fastjson v1.6.10 // indirect
+ github.com/zeebo/xxh3 v1.1.0 // indirect
+ go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
- golang.org/x/crypto v0.40.0 // indirect
- golang.org/x/mod v0.26.0 // indirect
- golang.org/x/tools v0.35.0 // indirect
- gopkg.in/ini.v1 v1.67.0 // indirect
+ go.yaml.in/yaml/v2 v2.4.3 // indirect
+ go.yaml.in/yaml/v3 v3.0.4 // indirect
+ golang.org/x/crypto v0.49.0 // indirect
+ golang.org/x/mod v0.34.0 // indirect
+ golang.org/x/telemetry v0.0.0-20260311193753-579e4da9a98c // indirect
+ golang.org/x/tools v0.43.0 // indirect
+ google.golang.org/protobuf v1.36.11 // indirect
+ gopkg.in/ini.v1 v1.67.1 // indirect
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
)
diff --git a/go.sum b/go.sum
index 36558f264..d7b16d9d3 100644
--- a/go.sum
+++ b/go.sum
@@ -1,11 +1,11 @@
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
-filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
-filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
+filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
+filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
+github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
+github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
-github.com/RaveNoX/go-jsoncommentstrip v1.0.0 h1:t527LHHE3HmiHrq74QMpNPZpGCIJzTx+apLkMKt4HC0=
-github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk=
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
github.com/atombender/go-jsonschema v0.20.0 h1:AHg0LeI0HcjQ686ALwUNqVJjNRcSXpIR6U+wC2J0aFY=
@@ -14,8 +14,8 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
-github.com/bmatcuk/doublestar/v4 v4.9.0 h1:DBvuZxjdKkRP/dr4GVV4w2fnmrk5Hxc90T51LZjv0JA=
-github.com/bmatcuk/doublestar/v4 v4.9.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
+github.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs=
+github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
github.com/bradleyjkemp/cupaloy/v2 v2.8.0 h1:any4BmKE+jGIaMpnU8YgH/I2LPiLBufr6oMMlVBbn9M=
github.com/bradleyjkemp/cupaloy/v2 v2.8.0/go.mod h1:bm7JXdkRd4BHJk9HpwqAI8BoAY1lps46Enkdqw6aRX0=
github.com/cespare/reflex v0.3.1 h1:N4Y/UmRrjwOkNT0oQQnYsdr6YBxvHqtSfPB4mqOyAKk=
@@ -24,25 +24,24 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
-github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
-github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
+github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo=
+github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
+github.com/deluan/go-taglib v0.0.0-20260307161927-168f6e74ada7 h1:RpRSTEsAdLHx3Ci0d3M5wtpjcBZiKzhnGfnNAxGXrAE=
+github.com/deluan/go-taglib v0.0.0-20260307161927-168f6e74ada7/go.mod h1:sKDN0U4qXDlq6LFK+aOAkDH4Me5nDV1V/A4B+B69xBA=
github.com/deluan/rest v0.0.0-20211102003136-6260bc399cbf h1:tb246l2Zmpt/GpF9EcHCKTtwzrd0HGfEmoODFA/qnk4=
github.com/deluan/rest v0.0.0-20211102003136-6260bc399cbf/go.mod h1:tSgDythFsl0QgS/PFWfIZqcJKnkADWneY80jaVRlqK8=
github.com/deluan/sanitize v0.0.0-20241120162836-fdfd8fdfaa55 h1:wSCnggTs2f2ji6nFwQmfwgINcmSMj0xF0oHnoyRSPe4=
github.com/deluan/sanitize v0.0.0-20241120162836-fdfd8fdfaa55/go.mod h1:ZNCLJfehvEf34B7BbLKjgpsL9lyW7q938w/GY1XgV4E=
-github.com/deluan/tag v0.0.0-20241002021117-dfe5e6ea396d h1:x/R3+oPEjnisl1zBx2f2v7Gf6f11l0N0JoD6BkwcJyA=
-github.com/deluan/tag v0.0.0-20241002021117-dfe5e6ea396d/go.mod h1:apkPC/CR3s48O2D7Y++n1XWEpgPNNCjXYga3PPbJe2E=
github.com/dexterlb/mpvipc v0.0.0-20241005113212-7cdefca0e933 h1:r4hxcT6GBIA/j8Ox4OXI5MNgMKfR+9plcAWYi1OnmOg=
github.com/dexterlb/mpvipc v0.0.0-20241005113212-7cdefca0e933/go.mod h1:RkQWLNITKkXHLP7LXxZSgEq+uFWU25M5qW7qfEhL9Wc=
-github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
-github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/djherbis/atime v1.1.0 h1:rgwVbP/5by8BvvjBNrbh64Qz33idKT3pSnMSJsxhi0g=
github.com/djherbis/atime v1.1.0/go.mod h1:28OF6Y8s3NQWwacXc5eZTsEsiMzp7LF8MbXE+XJPdBE=
github.com/djherbis/fscache v0.10.2-0.20231127215153-442a07e326c4 h1:wdZllsLrDJtYfHiAKogB4PNHSDeO+v+5S3eqSWHGDlc=
@@ -51,8 +50,16 @@ github.com/djherbis/stream v1.4.0 h1:aVD46WZUiq5kJk55yxJAyw6Kuera6kmC3i2vEQyW/AE
github.com/djherbis/stream v1.4.0/go.mod h1:cqjC1ZRq3FFwkGmUtHwcldbnW8f0Q4YuVsGW1eAFtOk=
github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
+github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
+github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
+github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
+github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
+github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
@@ -60,46 +67,55 @@ github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7z
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
-github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618=
-github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
+github.com/gen2brain/webp v0.5.5 h1:MvQR75yIPU/9nSqYT5h13k4URaJK3gf9tgz/ksRbyEg=
+github.com/gen2brain/webp v0.5.5/go.mod h1:xOSMzp4aROt2KFW++9qcK/RBTOVC2S9tJG66ip/9Oc0=
+github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs=
+github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo=
+github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M=
+github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk=
+github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE=
+github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc=
+github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
+github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-chi/httprate v0.15.0 h1:j54xcWV9KGmPf/X4H32/aTH+wBlrvxL7P+SdnRqxh5g=
github.com/go-chi/httprate v0.15.0/go.mod h1:rzGHhVrsBn3IMLYDOZQsSU4fJNWcjui4fWKJcCId1R4=
-github.com/go-chi/jwtauth/v5 v5.3.3 h1:50Uzmacu35/ZP9ER2Ht6SazwPsnLQ9LRJy6zTZJpHEo=
-github.com/go-chi/jwtauth/v5 v5.3.3/go.mod h1:O4QvPRuZLZghl9WvfVaON+ARfGzpD2PBX/QY5vUz7aQ=
+github.com/go-chi/jwtauth/v5 v5.4.0 h1:Ieh0xMJsFvqylqJ02/mQHKzbbKO9DYNBh4DPKCwTwYI=
+github.com/go-chi/jwtauth/v5 v5.4.0/go.mod h1:w6yjqUUXz1b8+oiJel64Sz1KJwduQM6qUA5QNzO5+bQ=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
-github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
-github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
+github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
+github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/go-viper/encoding/ini v0.1.1 h1:MVWY7B2XNw7lnOqHutGRc97bF3rP7omOdgjdMPAJgbs=
github.com/go-viper/encoding/ini v0.1.1/go.mod h1:Pfi4M2V1eAGJVZ5q6FrkHPhtHED2YgLlXhvgMVrB+YQ=
-github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
-github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
-github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
-github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
-github.com/goccy/go-yaml v1.17.1 h1:LI34wktB2xEE3ONG/2Ar54+/HJVBriAGJ55PHls4YuY=
-github.com/goccy/go-yaml v1.17.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
-github.com/gohugoio/hashstructure v0.5.0 h1:G2fjSBU36RdwEJBWJ+919ERvOVqAg9tfcYp47K9swqg=
-github.com/gohugoio/hashstructure v0.5.0/go.mod h1:Ser0TniXuu/eauYmrwM4o64EBvySxNzITEOLlm4igec=
+github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
+github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
+github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
+github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
+github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
+github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
+github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
+github.com/gohugoio/hashstructure v0.6.0 h1:7wMB/2CfXoThFYhdWRGv3u3rUM761Cq29CxUW+NltUg=
+github.com/gohugoio/hashstructure v0.6.0/go.mod h1:lapVLk9XidheHG1IQ4ZSbyYrXcaILU1ZEP/+vno5rBQ=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
-github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-pipeline v0.0.0-20230411140531-6cbedfc1d3fc h1:hd+uUVsB1vdxohPneMrhGH2YfQuH5hRIK9u4/XCeUtw=
github.com/google/go-pipeline v0.0.0-20230411140531-6cbedfc1d3fc/go.mod h1:SL66SJVysrh7YbDCP9tH30b8a9o/N2HeiQNUm85EKhc=
-github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 h1:xhMrHhTJ6zxu3gA4enFM9MLn9AY7613teCdFnlUVbSQ=
-github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA=
+github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc h1:VBbFa1lDYWEeV5FZKUiYKYT0VxCp9twUmmaq9eb8sXw=
+github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=
github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE=
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
-github.com/google/wire v0.6.0 h1:HBkoIh4BdSxoyo9PveV8giw7ZsaBOvzWKfcg/6MrVwI=
-github.com/google/wire v0.6.0/go.mod h1:F4QhpQ9EDIdJ1Mbop/NZBRB+5yrR6qg3BnctaoUk6NA=
+github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=
+github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
@@ -111,22 +127,24 @@ github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
+github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f h1:Fnl4pzx8SR7k7JuzyW8lEtSFH6EQ8xgcypgIn8pcGIE=
+github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jellydator/ttlcache/v3 v3.4.0 h1:YS4P125qQS0tNhtL6aeYkheEaB/m8HCqdMMP4mnWdTY=
github.com/jellydator/ttlcache/v3 v3.4.0/go.mod h1:Hw9EgjymziQD3yGsQdf1FqFdpp7YjFMd4Srg5EJlgD4=
+github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE=
+github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/kardianos/service v1.2.4 h1:XNlGtZOYNx2u91urOdg/Kfmc+gfmuIo1Dd3rEi2OgBk=
github.com/kardianos/service v1.2.4/go.mod h1:E4V9ufUuY82F7Ztlu1eN9VXWIQxg8NoLQlmFe0MtrXc=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
-github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
-github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
+github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
+github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
-github.com/knqyf263/go-plugin v0.9.0 h1:CQs2+lOPIlkZVtcb835ZYDEoyyWJWLbSTWeCs0EwTwI=
-github.com/knqyf263/go-plugin v0.9.0/go.mod h1:2z5lCO1/pez6qGo8CvCxSlBFSEat4MEp1DrnA+f7w8Q=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -143,24 +161,28 @@ github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhR
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
github.com/lestrrat-go/blackmagic v1.0.4/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
+github.com/lestrrat-go/dsig v1.0.0 h1:OE09s2r9Z81kxzJYRn07TFM9XA4akrUdoMwr0L8xj38=
+github.com/lestrrat-go/dsig v1.0.0/go.mod h1:dEgoOYYEJvW6XGbLasr8TFcAxoWrKlbQvmJgCR0qkDo=
+github.com/lestrrat-go/dsig-secp256k1 v1.0.0 h1:JpDe4Aybfl0soBvoVwjqDbp+9S1Y2OM7gcrVVMFPOzY=
+github.com/lestrrat-go/dsig-secp256k1 v1.0.0/go.mod h1:CxUgAhssb8FToqbL8NjSPoGQlnO4w3LG1P0qPWQm/NU=
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
-github.com/lestrrat-go/httprc v1.0.6 h1:qgmgIRhpvBqexMJjA/PmwSvhNk679oqD1RbovdCGW8k=
-github.com/lestrrat-go/httprc v1.0.6/go.mod h1:mwwz3JMTPBjHUkkDv/IGJ39aALInZLrhBp0X7KGUZlo=
-github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI=
-github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4=
-github.com/lestrrat-go/jwx/v2 v2.1.6 h1:hxM1gfDILk/l5ylers6BX/Eq1m/pnxe9NBwW6lVfecA=
-github.com/lestrrat-go/jwx/v2 v2.1.6/go.mod h1:Y722kU5r/8mV7fYDifjug0r8FK8mZdw0K0GpJw/l8pU=
-github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
-github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
-github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
-github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
+github.com/lestrrat-go/httprc/v3 v3.0.4 h1:pXyH2ppK8GYYggygxJ3TvxpCZnbEUWc9qSwRTTApaLA=
+github.com/lestrrat-go/httprc/v3 v3.0.4/go.mod h1:mSMtkZW92Z98M5YoNNztbRGxbXHql7tSitCvaxvo9l0=
+github.com/lestrrat-go/jwx/v3 v3.0.13 h1:AdHKiPIYeCSnOJtvdpipPg/0SuFh9rdkN+HF3O0VdSk=
+github.com/lestrrat-go/jwx/v3 v3.0.13/go.mod h1:2m0PV1A9tM4b/jVLMx8rh6rBl7F6WGb3EG2hufN9OQU=
+github.com/lestrrat-go/option/v2 v2.0.0 h1:XxrcaJESE1fokHy3FpaQ/cXW8ZsIdWcdFzzLOcID3Ss=
+github.com/lestrrat-go/option/v2 v2.0.0/go.mod h1:oSySsmzMoR0iRzCDCaUfsCzxQHUEuhOViQObyy7S6Vg=
+github.com/maruel/natural v1.3.0 h1:VsmCsBmEyrR46RomtgHs5hbKADGRVtliHTyCOLFBpsg=
+github.com/maruel/natural v1.3.0/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
-github.com/mattn/go-sqlite3 v1.14.29 h1:1O6nRLJKvsi1H2Sj0Hzdfojwt8GiGKm+LOfLaBFaouQ=
-github.com/mattn/go-sqlite3 v1.14.29/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/mattn/go-sqlite3 v1.14.37 h1:3DOZp4cXis1cUIpCfXLtmlGolNLp2VEqhiB/PARNBIg=
+github.com/mattn/go-sqlite3 v1.14.37/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
+github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE=
+github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/mileusna/useragent v1.3.5 h1:SJM5NzBmh/hO+4LGeATKpaEX9+b4vcGg2qXGLiNGDws=
@@ -169,14 +191,14 @@ github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQ
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
-github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
-github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ogier/pflag v0.0.1 h1:RW6JSWSu/RkSatfcLtogGfFgpim5p7ARQ10ECk5O750=
github.com/ogier/pflag v0.0.1/go.mod h1:zkFki7tvTa0tafRvTBIZTvzYyAu6kQhPZFnshFFPE+g=
-github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus=
-github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8=
-github.com/onsi/gomega v1.38.0 h1:c/WX+w8SLAinvuKKQFh77WEucCnPk4j2OTUr7lt7BeY=
-github.com/onsi/gomega v1.38.0/go.mod h1:OcXcwId0b9QsE7Y49u+BTrL4IdKOBOKnD6VQNTJEB6o=
+github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI=
+github.com/onsi/ginkgo/v2 v2.28.1/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE=
+github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28=
+github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
@@ -186,20 +208,18 @@ github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/pocketbase/dbx v1.11.0 h1:LpZezioMfT3K4tLrqA55wWFw1EtH1pM4tzSVa7kgszU=
-github.com/pocketbase/dbx v1.11.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
-github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
-github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U=
-github.com/pressly/goose/v3 v3.24.3 h1:DSWWNwwggVUsYZ0X2VitiAa9sKuqtBfe+Jr9zFGwWlM=
-github.com/pressly/goose/v3 v3.24.3/go.mod h1:v9zYL4xdViLHCUUJh/mhjnm6JrK7Eul8AS93IxiZM4E=
-github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
-github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
-github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
-github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
-github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=
-github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
-github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
-github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
+github.com/pocketbase/dbx v1.12.0 h1:/oLErM+A0b4xI0PWTGPqSDVjzix48PqI/bng2l0PzoA=
+github.com/pocketbase/dbx v1.12.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
+github.com/pressly/goose/v3 v3.27.0 h1:/D30gVTuQhu0WsNZYbJi4DMOsx1lNq+6SkLe+Wp59BM=
+github.com/pressly/goose/v3 v3.27.0/go.mod h1:3ZBeCXqzkgIRvrEMDkYh1guvtoJTU5oMMuDdkutoM78=
+github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
+github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
+github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
+github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
+github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
+github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
+github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
+github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rjeczalik/notify v0.9.3 h1:6rJAzHTGKXGj76sbRgDiDcYj/HniypXmSJo1SWakZeY=
@@ -212,89 +232,106 @@ github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI=
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs=
-github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k=
-github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk=
+github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
+github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
github.com/sanity-io/litter v1.5.8 h1:uM/2lKrWdGbRXDrIq08Lh9XtVYoeGtcQxk9rtQ7+rYg=
github.com/sanity-io/litter v1.5.8/go.mod h1:9gzJgR2i4ZpjZHsKvUXIRQVk7P+yM3e+jAF7bU2UI5U=
-github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
-github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
+github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
+github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
-github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
-github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/sosodev/duration v1.3.1 h1:qtHBDMQ6lvMQsL15g4aopM4HEfOaYuhWBw3NPTtlqq4=
github.com/sosodev/duration v1.3.1/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
-github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
-github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
-github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
-github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
-github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE=
-github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
-github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
-github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
-github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
-github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M=
-github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
-github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
-github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
+github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
+github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
+github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
+github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
+github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v0.0.0-20161117074351-18a02ba4a312/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
-github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
-github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
-github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
+github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
+github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
+github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
+github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
+github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
+github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
+github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
+github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
+github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
+github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
+github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
+github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/unrolled/secure v1.17.0 h1:Io7ifFgo99Bnh0J7+Q+qcMzWM6kaDPCA5FroFZEdbWU=
github.com/unrolled/secure v1.17.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
+github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
+github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 h1:FnBeRrxr7OU4VvAzt5X7s6266i6cSVkkFPS0TuXWbIg=
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
-github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
-github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
-go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
-go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
+go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
+go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
+go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
+go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
-golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
-golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
-golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
-golang.org/x/exp v0.0.0-20250718183923-645b1fa84792 h1:R9PFI6EUdfVKgwKjZef7QIwGcBKu86OEFpJ9nUEP2l4=
-golang.org/x/exp v0.0.0-20250718183923-645b1fa84792/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
-golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
-golang.org/x/image v0.29.0 h1:HcdsyR4Gsuys/Axh0rDEmlBmB68rW1U9BUdB3UVHsas=
-golang.org/x/image v0.29.0/go.mod h1:RVJROnf3SLK8d26OW91j4FrIHGbsJ8QnbEocVTOWQDA=
+golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
+golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
+golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
+golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
+golang.org/x/image v0.37.0 h1:ZiRjArKI8GwxZOoEtUfhrBtaCN+4b/7709dlT6SSnQA=
+golang.org/x/image v0.37.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
-golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
-golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
-golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
+golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
+golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@@ -303,12 +340,11 @@ 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.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
-golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
-golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
-golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
+golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
+golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
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=
@@ -316,8 +352,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
-golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
-golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180926160741-c2ed4eda69e7/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -326,27 +362,28 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/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-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
-golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
+golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
+golang.org/x/telemetry v0.0.0-20260311193753-579e4da9a98c h1:6a8FdnNk6bTXBjR4AGKFgUKuo+7GnR3FX5L7CbveeZc=
+golang.org/x/telemetry v0.0.0-20260311193753-579e4da9a98c/go.mod h1:TpUTTEp9frx7rTdLpC9gFG9kdI7zVLFTFFlqaH2Cncw=
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=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
-golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
+golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
+golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@@ -357,40 +394,39 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
-golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
-golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
-golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
-golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
+golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
+golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
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=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
-golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
-golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
-golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
+golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
+golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
-google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
-google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
-gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
-gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
+gopkg.in/ini.v1 v1.67.1 h1:tVBILHy0R6e4wkYOn3XmiITt/hEVH4TFMYvAX2Ytz6k=
+gopkg.in/ini.v1 v1.67.1/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU=
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-modernc.org/libc v1.65.0 h1:e183gLDnAp9VJh6gWKdTy0CThL9Pt7MfcR/0bgb7Y1Y=
-modernc.org/libc v1.65.0/go.mod h1:7m9VzGq7APssBTydds2zBcxGREwvIGpuUBaKTXdm2Qs=
+modernc.org/libc v1.68.0 h1:PJ5ikFOV5pwpW+VqCK1hKJuEWsonkIJhhIXyuF/91pQ=
+modernc.org/libc v1.68.0/go.mod h1:NnKCYeoYgsEqnY3PgvNgAeaJnso968ygU8Z0DxjoEc0=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
-modernc.org/memory v1.10.0 h1:fzumd51yQ1DxcOxSO+S6X7+QTuVU+n8/Aj7swYjFfC4=
-modernc.org/memory v1.10.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
-modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI=
-modernc.org/sqlite v1.37.0/go.mod h1:5YiWv+YviqGMuGw4V+PNplcyaJ5v+vQd7TQOgkACoJM=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU=
+modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
diff --git a/log/journal.go b/log/journal.go
new file mode 100644
index 000000000..f1c17d2e7
--- /dev/null
+++ b/log/journal.go
@@ -0,0 +1,41 @@
+package log
+
+import (
+ "fmt"
+
+ "github.com/sirupsen/logrus"
+)
+
+// journalFormatter wraps a logrus.Formatter and prepends a syslog priority
+// prefix () to each log line. When stderr is captured by systemd-journald,
+// this prefix tells journald the correct severity for each message.
+//
+// See https://www.freedesktop.org/software/systemd/man/sd-daemon.html
+type journalFormatter struct {
+ inner logrus.Formatter
+}
+
+// levelToPriority maps logrus levels to syslog priority values.
+// The mapping follows RFC 5424 severity levels.
+var levelToPriority = map[logrus.Level]int{
+ logrus.PanicLevel: 0, // emerg
+ logrus.FatalLevel: 2, // crit
+ logrus.ErrorLevel: 3, // err
+ logrus.WarnLevel: 4, // warning
+ logrus.InfoLevel: 6, // info
+ logrus.DebugLevel: 7, // debug
+ logrus.TraceLevel: 7, // debug
+}
+
+func (f *journalFormatter) Format(entry *logrus.Entry) ([]byte, error) {
+ formatted, err := f.inner.Format(entry)
+ if err != nil {
+ return formatted, err
+ }
+ priority, ok := levelToPriority[entry.Level]
+ if !ok {
+ priority = 6 // default to info for unknown levels
+ }
+ prefix := []byte(fmt.Sprintf("<%d>", priority))
+ return append(prefix, formatted...), nil
+}
diff --git a/log/journal_test.go b/log/journal_test.go
new file mode 100644
index 000000000..770f12b6d
--- /dev/null
+++ b/log/journal_test.go
@@ -0,0 +1,41 @@
+package log
+
+import (
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/sirupsen/logrus"
+)
+
+var _ = Describe("journalFormatter", func() {
+ var formatter *journalFormatter
+
+ BeforeEach(func() {
+ inner := &logrus.TextFormatter{
+ DisableTimestamp: true,
+ DisableColors: true,
+ }
+ formatter = &journalFormatter{inner: inner}
+ })
+
+ DescribeTable("prefixes log lines with syslog priority",
+ func(level logrus.Level, expectedPrefix string) {
+ entry := &logrus.Entry{
+ Logger: logrus.New(),
+ Level: level,
+ Message: "test message",
+ Data: logrus.Fields{},
+ }
+ out, err := formatter.Format(entry)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(out)).To(HavePrefix(expectedPrefix))
+ },
+ Entry("error", logrus.ErrorLevel, "<3>"),
+ Entry("warning", logrus.WarnLevel, "<4>"),
+ Entry("info", logrus.InfoLevel, "<6>"),
+ Entry("debug", logrus.DebugLevel, "<7>"),
+ Entry("trace", logrus.TraceLevel, "<7>"),
+ Entry("fatal", logrus.FatalLevel, "<2>"),
+ Entry("panic", logrus.PanicLevel, "<0>"),
+ Entry("unknown level defaults to info", logrus.Level(99), "<6>"),
+ )
+})
diff --git a/log/log.go b/log/log.go
index 20119ab46..2764d80e5 100644
--- a/log/log.go
+++ b/log/log.go
@@ -11,6 +11,7 @@ import (
"runtime"
"sort"
"strings"
+ "sync"
"time"
"github.com/sirupsen/logrus"
@@ -18,7 +19,7 @@ import (
type Level uint32
-type LevelFunc = func(ctx interface{}, msg interface{}, keyValuePairs ...interface{})
+type LevelFunc = func(ctx any, msg any, keyValuePairs ...any)
var redacted = &Hook{
AcceptedLevels: logrus.AllLevels,
@@ -26,10 +27,9 @@ var redacted = &Hook{
// Keys from the config
"(ApiKey:\")[\\w]*",
"(Secret:\")[\\w]*",
- "(Spotify.*ID:\")[\\w]*",
"(PasswordEncryptionKey:[\\s]*\")[^\"]*",
- "(ReverseProxyUserHeader:[\\s]*\")[^\"]*",
- "(ReverseProxyWhitelist:[\\s]*\")[^\"]*",
+ "(UserHeader:[\\s]*\")[^\"]*",
+ "(TrustedSources:[\\s]*\")[^\"]*",
"(MetricsPath:[\\s]*\")[^\"]*",
"(DevAutoCreateAdminPassword:[\\s]*\")[^\"]*",
"(DevAutoLoginUsername:[\\s]*\")[^\"]*",
@@ -70,6 +70,7 @@ type levelPath struct {
var (
currentLevel Level
+ loggerMu sync.RWMutex
defaultLogger = logrus.New()
logSourceLine = false
rootPath string
@@ -78,17 +79,19 @@ var (
// SetLevel sets the global log level used by the simple logger.
func SetLevel(l Level) {
+ loggerMu.Lock()
currentLevel = l
defaultLogger.Level = logrus.TraceLevel
+ loggerMu.Unlock()
logrus.SetLevel(logrus.Level(l))
}
func SetLevelString(l string) {
- level := levelFromString(l)
+ level := ParseLogLevel(l)
SetLevel(level)
}
-func levelFromString(l string) Level {
+func ParseLogLevel(l string) Level {
envLevel := strings.ToLower(l)
var level Level
switch envLevel {
@@ -110,9 +113,11 @@ func levelFromString(l string) Level {
// SetLogLevels sets the log levels for specific paths in the codebase.
func SetLogLevels(levels map[string]string) {
+ loggerMu.Lock()
+ defer loggerMu.Unlock()
logLevels = nil
for k, v := range levels {
- logLevels = append(logLevels, levelPath{path: k, level: levelFromString(v)})
+ logLevels = append(logLevels, levelPath{path: k, level: ParseLogLevel(v)})
}
sort.Slice(logLevels, func(i, j int) bool {
return logLevels[i].path > logLevels[j].path
@@ -125,6 +130,8 @@ func SetLogSourceLine(enabled bool) {
func SetRedacting(enabled bool) {
if enabled {
+ loggerMu.Lock()
+ defer loggerMu.Unlock()
defaultLogger.AddHook(redacted)
}
}
@@ -133,16 +140,27 @@ func SetOutput(w io.Writer) {
if runtime.GOOS == "windows" {
w = CRLFWriter(w)
}
+ loggerMu.Lock()
+ defer loggerMu.Unlock()
defaultLogger.SetOutput(w)
}
+// EnableJournalFormat wraps the current logger formatter with syslog
+// priority prefixes for systemd-journald. Only call this when output
+// goes to stderr and JOURNAL_STREAM is set.
+func EnableJournalFormat() {
+ loggerMu.Lock()
+ defer loggerMu.Unlock()
+ defaultLogger.Formatter = &journalFormatter{inner: defaultLogger.Formatter}
+}
+
// Redact applies redaction to a single string
func Redact(msg string) string {
r, _ := redacted.redact(msg)
return r
}
-func NewContext(ctx context.Context, keyValuePairs ...interface{}) context.Context {
+func NewContext(ctx context.Context, keyValuePairs ...any) context.Context {
if ctx == nil {
ctx = context.Background()
}
@@ -158,10 +176,14 @@ func NewContext(ctx context.Context, keyValuePairs ...interface{}) context.Conte
}
func SetDefaultLogger(l *logrus.Logger) {
+ loggerMu.Lock()
+ defer loggerMu.Unlock()
defaultLogger = l
}
func CurrentLevel() Level {
+ loggerMu.RLock()
+ defer loggerMu.RUnlock()
return currentLevel
}
@@ -170,32 +192,32 @@ func IsGreaterOrEqualTo(level Level) bool {
return shouldLog(level, 2)
}
-func Fatal(args ...interface{}) {
- log(LevelFatal, args...)
+func Fatal(args ...any) {
+ Log(LevelFatal, args...)
os.Exit(1)
}
-func Error(args ...interface{}) {
- log(LevelError, args...)
+func Error(args ...any) {
+ Log(LevelError, args...)
}
-func Warn(args ...interface{}) {
- log(LevelWarn, args...)
+func Warn(args ...any) {
+ Log(LevelWarn, args...)
}
-func Info(args ...interface{}) {
- log(LevelInfo, args...)
+func Info(args ...any) {
+ Log(LevelInfo, args...)
}
-func Debug(args ...interface{}) {
- log(LevelDebug, args...)
+func Debug(args ...any) {
+ Log(LevelDebug, args...)
}
-func Trace(args ...interface{}) {
- log(LevelTrace, args...)
+func Trace(args ...any) {
+ Log(LevelTrace, args...)
}
-func log(level Level, args ...interface{}) {
+func Log(level Level, args ...any) {
if !shouldLog(level, 3) {
return
}
@@ -204,14 +226,21 @@ func log(level Level, args ...interface{}) {
}
func Writer() io.Writer {
+ loggerMu.RLock()
+ defer loggerMu.RUnlock()
return defaultLogger.Writer()
}
func shouldLog(requiredLevel Level, skip int) bool {
- if currentLevel >= requiredLevel {
+ loggerMu.RLock()
+ level := currentLevel
+ levels := logLevels
+ loggerMu.RUnlock()
+
+ if level >= requiredLevel {
return true
}
- if len(logLevels) == 0 {
+ if len(levels) == 0 {
return false
}
@@ -221,7 +250,7 @@ func shouldLog(requiredLevel Level, skip int) bool {
}
file = strings.TrimPrefix(file, rootPath)
- for _, lp := range logLevels {
+ for _, lp := range levels {
if strings.HasPrefix(file, lp.path) {
return lp.level >= requiredLevel
}
@@ -229,7 +258,7 @@ func shouldLog(requiredLevel Level, skip int) bool {
return false
}
-func parseArgs(args []interface{}) (*logrus.Entry, string) {
+func parseArgs(args []any) (*logrus.Entry, string) {
var l *logrus.Entry
var err error
if args[0] == nil {
@@ -268,7 +297,7 @@ func parseArgs(args []interface{}) (*logrus.Entry, string) {
return l, ""
}
-func addFields(logger *logrus.Entry, keyValuePairs []interface{}) *logrus.Entry {
+func addFields(logger *logrus.Entry, keyValuePairs []any) *logrus.Entry {
for i := 0; i < len(keyValuePairs); i += 2 {
switch name := keyValuePairs[i].(type) {
case error:
@@ -295,7 +324,7 @@ func addFields(logger *logrus.Entry, keyValuePairs []interface{}) *logrus.Entry
return logger
}
-func extractLogger(ctx interface{}) (*logrus.Entry, error) {
+func extractLogger(ctx any) (*logrus.Entry, error) {
switch ctx := ctx.(type) {
case *logrus.Entry:
return ctx, nil
@@ -314,6 +343,8 @@ func extractLogger(ctx interface{}) (*logrus.Entry, error) {
func createNewLogger() *logrus.Entry {
//logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true, DisableTimestamp: false, FullTimestamp: true})
//l.Formatter = &logrus.TextFormatter{ForceColors: true, DisableTimestamp: false, FullTimestamp: true}
+ loggerMu.RLock()
+ defer loggerMu.RUnlock()
logger := logrus.NewEntry(defaultLogger)
return logger
}
diff --git a/main.go b/main.go
index 65db162ac..b5fb508b4 100644
--- a/main.go
+++ b/main.go
@@ -9,11 +9,12 @@ import (
//goland:noinspection GoBoolExpressions
func main() {
- // This import is used to force the inclusion of the `netgo` tag when compiling the project.
+ // These references force the inclusion of build tags when compiling the project.
// If you get compilation errors like "undefined: buildtags.NETGO", this means you forgot to specify
- // the `netgo` build tag when compiling the project.
+ // the required build tags when compiling the project.
// To avoid these kind of errors, you should use `make build` to compile the project.
_ = buildtags.NETGO
+ _ = buildtags.SQLITE_FTS5
cmd.Execute()
}
diff --git a/model/album.go b/model/album.go
index a8dcfe682..667f4695b 100644
--- a/model/album.go
+++ b/model/album.go
@@ -1,11 +1,14 @@
package model
import (
+ "fmt"
"iter"
"math"
"sync"
"time"
+ "github.com/navidrome/navidrome/conf"
+
"github.com/gohugoio/hashstructure"
)
@@ -70,6 +73,13 @@ func (a Album) CoverArtID() ArtworkID {
return artworkIDFromAlbum(a)
}
+func (a Album) FullName() string {
+ if conf.Server.Subsonic.AppendAlbumVersion && len(a.Tags[TagAlbumVersion]) > 0 {
+ return fmt.Sprintf("%s (%s)", a.Name, a.Tags[TagAlbumVersion][0])
+ }
+ return a.Name
+}
+
// Equals compares two Album structs, ignoring calculated fields
func (a Album) Equals(other Album) bool {
// Normalize float32 values to avoid false negatives
diff --git a/model/album_test.go b/model/album_test.go
index a45d16dd5..0f4c912cd 100644
--- a/model/album_test.go
+++ b/model/album_test.go
@@ -3,11 +3,30 @@ package model_test
import (
"encoding/json"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
. "github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
+var _ = Describe("Album", func() {
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ })
+ DescribeTable("FullName",
+ func(enabled bool, tags Tags, expected string) {
+ conf.Server.Subsonic.AppendAlbumVersion = enabled
+ a := Album{Name: "Album", Tags: tags}
+ Expect(a.FullName()).To(Equal(expected))
+ },
+ Entry("appends version when enabled and tag is present", true, Tags{TagAlbumVersion: []string{"Remastered"}}, "Album (Remastered)"),
+ Entry("returns just name when disabled", false, Tags{TagAlbumVersion: []string{"Remastered"}}, "Album"),
+ Entry("returns just name when tag is absent", true, Tags{}, "Album"),
+ Entry("returns just name when tag is an empty slice", true, Tags{TagAlbumVersion: []string{}}, "Album"),
+ )
+})
+
var _ = Describe("Albums", func() {
var albums Albums
diff --git a/model/annotation.go b/model/annotation.go
index 2ec72c1b7..5228028a6 100644
--- a/model/annotation.go
+++ b/model/annotation.go
@@ -3,11 +3,13 @@ package model
import "time"
type Annotations struct {
- PlayCount int64 `structs:"play_count" json:"playCount,omitempty"`
- PlayDate *time.Time `structs:"play_date" json:"playDate,omitempty" `
- Rating int `structs:"rating" json:"rating,omitempty" `
- Starred bool `structs:"starred" json:"starred,omitempty" `
- StarredAt *time.Time `structs:"starred_at" json:"starredAt,omitempty"`
+ PlayCount int64 `structs:"play_count" json:"playCount,omitempty"`
+ PlayDate *time.Time `structs:"play_date" json:"playDate,omitempty" `
+ Rating int `structs:"rating" json:"rating,omitempty" `
+ RatedAt *time.Time `structs:"rated_at" json:"ratedAt,omitempty" `
+ Starred bool `structs:"starred" json:"starred,omitempty" `
+ StarredAt *time.Time `structs:"starred_at" json:"starredAt,omitempty"`
+ AverageRating float64 `structs:"average_rating" json:"averageRating,omitempty"`
}
type AnnotatedRepository interface {
diff --git a/model/artist.go b/model/artist.go
index 309ee800f..2085f0051 100644
--- a/model/artist.go
+++ b/model/artist.go
@@ -4,6 +4,8 @@ import (
"maps"
"slices"
"time"
+
+ "github.com/navidrome/navidrome/consts"
)
type Artist struct {
@@ -34,6 +36,8 @@ type Artist struct {
Missing bool `structs:"missing" json:"missing"`
+ UploadedImage string `structs:"uploaded_image" json:"uploadedImage,omitempty"`
+
CreatedAt *time.Time `structs:"created_at" json:"createdAt,omitempty"`
UpdatedAt *time.Time `structs:"updated_at" json:"updatedAt,omitempty"`
}
@@ -58,6 +62,10 @@ func (a Artist) CoverArtID() ArtworkID {
return artworkIDFromArtist(a)
}
+func (a Artist) UploadedImagePath() string {
+ return UploadedImagePath(consts.EntityArtist, a.UploadedImage)
+}
+
// Roles returns the roles this artist has participated in., based on the Stats field
func (a Artist) Roles() []Role {
return slices.Collect(maps.Keys(a.Stats))
diff --git a/model/artist_test.go b/model/artist_test.go
new file mode 100644
index 000000000..5a24504eb
--- /dev/null
+++ b/model/artist_test.go
@@ -0,0 +1,30 @@
+package model_test
+
+import (
+ "path/filepath"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/model"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Artist", func() {
+ Describe("UploadedImagePath", func() {
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DataFolder = "/data"
+ })
+
+ It("returns empty string when no image uploaded", func() {
+ a := model.Artist{ID: "ar-1"}
+ Expect(a.UploadedImagePath()).To(BeEmpty())
+ })
+
+ It("returns full path when image is set", func() {
+ a := model.Artist{ID: "ar-1", UploadedImage: "ar-1_test.jpg"}
+ Expect(a.UploadedImagePath()).To(Equal(filepath.Join("/data", "artwork", "artist", "ar-1_test.jpg")))
+ })
+ })
+})
diff --git a/model/artwork_id.go b/model/artwork_id.go
index 36026dd03..1bd146c1f 100644
--- a/model/artwork_id.go
+++ b/model/artwork_id.go
@@ -22,6 +22,8 @@ var (
KindArtistArtwork = Kind{"ar", "artist"}
KindAlbumArtwork = Kind{"al", "album"}
KindPlaylistArtwork = Kind{"pl", "playlist"}
+ KindDiscArtwork = Kind{"dc", "disc"}
+ KindRadioArtwork = Kind{"ra", "radio"}
)
var artworkKindMap = map[string]Kind{
@@ -29,6 +31,8 @@ var artworkKindMap = map[string]Kind{
KindArtistArtwork.prefix: KindArtistArtwork,
KindAlbumArtwork.prefix: KindAlbumArtwork,
KindPlaylistArtwork.prefix: KindPlaylistArtwork,
+ KindDiscArtwork.prefix: KindDiscArtwork,
+ KindRadioArtwork.prefix: KindRadioArtwork,
}
type ArtworkID struct {
@@ -91,6 +95,22 @@ func MustParseArtworkID(id string) ArtworkID {
return artID
}
+func DiscArtworkID(albumID string, discNumber int) string {
+ return fmt.Sprintf("%s:%d", albumID, discNumber)
+}
+
+func ParseDiscArtworkID(id string) (albumID string, discNumber int, err error) {
+ parts := strings.SplitN(id, ":", 2)
+ if len(parts) != 2 || parts[1] == "" {
+ return "", 0, errors.New("invalid disc artwork id")
+ }
+ num, err := strconv.Atoi(parts[1])
+ if err != nil {
+ return "", 0, fmt.Errorf("invalid disc number in artwork id: %w", err)
+ }
+ return parts[0], num, nil
+}
+
func artworkIDFromAlbum(al Album) ArtworkID {
return ArtworkID{
Kind: KindAlbumArtwork,
@@ -121,3 +141,11 @@ func artworkIDFromArtist(ar Artist) ArtworkID {
ID: ar.ID,
}
}
+
+func artworkIDFromRadio(r Radio) ArtworkID {
+ return ArtworkID{
+ Kind: KindRadioArtwork,
+ ID: r.ID,
+ LastUpdate: r.UpdatedAt,
+ }
+}
diff --git a/model/artwork_id_test.go b/model/artwork_id_test.go
index 2f42217f9..b634e7cbc 100644
--- a/model/artwork_id_test.go
+++ b/model/artwork_id_test.go
@@ -28,6 +28,40 @@ var _ = Describe("ArtworkID", func() {
Expect(parsedId.LastUpdate.Unix()).To(Equal(id.LastUpdate.Unix()))
})
})
+ Describe("ParseArtworkID - disc kind", func() {
+ It("parses a disc artwork ID with dc prefix", func() {
+ now := time.Now()
+ id := model.NewArtworkID(model.KindDiscArtwork, "albumid123:2", &now)
+ parsedId, err := model.ParseArtworkID(id.String())
+ Expect(err).ToNot(HaveOccurred())
+ Expect(parsedId.Kind).To(Equal(model.KindDiscArtwork))
+ Expect(parsedId.ID).To(Equal("albumid123:2"))
+ Expect(parsedId.LastUpdate.Unix()).To(Equal(now.Unix()))
+ })
+ })
+
+ Describe("ParseDiscArtworkID", func() {
+ DescribeTable("parses composite disc artwork IDs",
+ func(id string, expectedAlbum string, expectedDisc int, expectErr bool) {
+ albumID, discNumber, err := model.ParseDiscArtworkID(id)
+ if expectErr {
+ Expect(err).To(HaveOccurred())
+ } else {
+ Expect(err).ToNot(HaveOccurred())
+ Expect(albumID).To(Equal(expectedAlbum))
+ Expect(discNumber).To(Equal(expectedDisc))
+ }
+ },
+ Entry("valid id", "albumid123:2", "albumid123", 2, false),
+ Entry("disc number 1", "abc:1", "abc", 1, false),
+ Entry("large disc number", "abc:10", "abc", 10, false),
+ Entry("missing colon", "albumid123", "", 0, true),
+ Entry("missing disc number", "albumid123:", "", 0, true),
+ Entry("non-numeric disc", "albumid123:abc", "", 0, true),
+ Entry("empty string", "", "", 0, true),
+ )
+ })
+
Describe("ParseArtworkID()", func() {
It("parses album artwork ids", func() {
id, err := model.ParseArtworkID("al-1234")
diff --git a/model/criteria/criteria.go b/model/criteria/criteria.go
index fa92c5aca..278acf34c 100644
--- a/model/criteria/criteria.go
+++ b/model/criteria/criteria.go
@@ -15,10 +15,38 @@ type Expression = squirrel.Sqlizer
type Criteria struct {
Expression
- Sort string
- Order string
- Limit int
- Offset int
+ Sort string
+ Order string
+ Limit int
+ LimitPercent int
+ Offset int
+}
+
+// EffectiveLimit resolves the effective limit for a query. If a fixed Limit is
+// set it takes precedence. Otherwise, if LimitPercent is set, the limit is
+// computed as a percentage of totalCount (minimum 1 when totalCount > 0).
+// Returns 0 when no limit applies.
+func (c Criteria) EffectiveLimit(totalCount int64) int {
+ if c.Limit > 0 {
+ return c.Limit
+ }
+ if c.LimitPercent > 0 && c.LimitPercent <= 100 {
+ if totalCount <= 0 {
+ return 0
+ }
+ result := int(totalCount) * c.LimitPercent / 100
+ if result < 1 {
+ return 1
+ }
+ return result
+ }
+ return 0
+}
+
+// IsPercentageLimit returns true when the criteria uses a valid percentage-based
+// limit (i.e. LimitPercent is in [1, 100] and no fixed Limit overrides it).
+func (c Criteria) IsPercentageLimit() bool {
+ return c.Limit == 0 && c.LimitPercent > 0 && c.LimitPercent <= 100
}
func (c Criteria) OrderBy() string {
@@ -61,7 +89,12 @@ func (c Criteria) OrderBy() string {
if f.order != "" {
mapped = f.order
} else if f.isTag {
- mapped = "COALESCE(json_extract(media_file.tags, '$." + sortField + "[0].value'), '')"
+ // Use the actual field name (handles aliases like albumtype -> releasetype)
+ tagName := sortField
+ if f.field != "" {
+ tagName = f.field
+ }
+ mapped = "COALESCE(json_extract(media_file.tags, '$." + tagName + "[0].value'), '')"
} else if f.isRole {
mapped = "COALESCE(json_extract(media_file.participants, '$." + sortField + "[0].name'), '')"
} else {
@@ -90,6 +123,35 @@ func (c Criteria) ToSql() (sql string, args []any, err error) {
return c.Expression.ToSql()
}
+// ExpressionJoins returns only the JOINs needed by the WHERE-clause expression,
+// excluding any JOINs required solely for sorting. This is useful for COUNT
+// queries where sort order is irrelevant.
+func (c Criteria) ExpressionJoins() JoinType {
+ if c.Expression == nil {
+ return JoinNone
+ }
+ return extractJoinTypes(c.Expression)
+}
+
+// RequiredJoins inspects the expression tree and Sort field to determine which
+// additional JOINs are needed when evaluating this criteria.
+func (c Criteria) RequiredJoins() JoinType {
+ result := JoinNone
+ if c.Expression != nil {
+ result |= extractJoinTypes(c.Expression)
+ }
+ // Also check Sort fields
+ if c.Sort != "" {
+ for _, p := range strings.Split(c.Sort, ",") {
+ p = strings.TrimSpace(p)
+ p = strings.TrimLeft(p, "+-")
+ p = strings.TrimSpace(p)
+ result |= fieldJoinType(p)
+ }
+ }
+ return result
+}
+
func (c Criteria) ChildPlaylistIds() []string {
if c.Expression == nil {
return nil
@@ -104,17 +166,19 @@ func (c Criteria) ChildPlaylistIds() []string {
func (c Criteria) MarshalJSON() ([]byte, error) {
aux := struct {
- All []Expression `json:"all,omitempty"`
- Any []Expression `json:"any,omitempty"`
- Sort string `json:"sort,omitempty"`
- Order string `json:"order,omitempty"`
- Limit int `json:"limit,omitempty"`
- Offset int `json:"offset,omitempty"`
+ All []Expression `json:"all,omitempty"`
+ Any []Expression `json:"any,omitempty"`
+ Sort string `json:"sort,omitempty"`
+ Order string `json:"order,omitempty"`
+ Limit int `json:"limit,omitempty"`
+ LimitPercent int `json:"limitPercent,omitempty"`
+ Offset int `json:"offset,omitempty"`
}{
- Sort: c.Sort,
- Order: c.Order,
- Limit: c.Limit,
- Offset: c.Offset,
+ Sort: c.Sort,
+ Order: c.Order,
+ Limit: c.Limit,
+ LimitPercent: c.LimitPercent,
+ Offset: c.Offset,
}
switch rules := c.Expression.(type) {
case Any:
@@ -129,12 +193,13 @@ func (c Criteria) MarshalJSON() ([]byte, error) {
func (c *Criteria) UnmarshalJSON(data []byte) error {
var aux struct {
- All unmarshalConjunctionType `json:"all"`
- Any unmarshalConjunctionType `json:"any"`
- Sort string `json:"sort"`
- Order string `json:"order"`
- Limit int `json:"limit"`
- Offset int `json:"offset"`
+ All unmarshalConjunctionType `json:"all"`
+ Any unmarshalConjunctionType `json:"any"`
+ Sort string `json:"sort"`
+ Order string `json:"order"`
+ Limit int `json:"limit"`
+ LimitPercent int `json:"limitPercent"`
+ Offset int `json:"offset"`
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
@@ -150,5 +215,15 @@ func (c *Criteria) UnmarshalJSON(data []byte) error {
c.Order = aux.Order
c.Limit = aux.Limit
c.Offset = aux.Offset
+
+ // Clamp LimitPercent to [0, 100]
+ if aux.LimitPercent < 0 {
+ log.Warn("limitPercent value out of range, clamping to 0", "value", aux.LimitPercent)
+ aux.LimitPercent = 0
+ } else if aux.LimitPercent > 100 {
+ log.Warn("limitPercent value out of range, clamping to 100", "value", aux.LimitPercent)
+ aux.LimitPercent = 100
+ }
+ c.LimitPercent = aux.LimitPercent
return nil
}
diff --git a/model/criteria/criteria_test.go b/model/criteria/criteria_test.go
index 3792264a5..a76b3fc1f 100644
--- a/model/criteria/criteria_test.go
+++ b/model/criteria/criteria_test.go
@@ -27,6 +27,7 @@ var _ = Describe("Criteria", func() {
StartsWith{"comment": "this"},
InTheRange{"year": []int{1980, 1990}},
IsNot{"genre": "Rock"},
+ Gt{"albumrating": 3},
},
},
Sort: "title",
@@ -48,7 +49,8 @@ var _ = Describe("Criteria", func() {
{ "all": [
{ "startsWith": {"comment": "this"} },
{ "inTheRange": {"year":[1980,1990]} },
- { "isNot": { "genre": "Rock" }}
+ { "isNot": { "genre": "Rock" }},
+ { "gt": { "albumrating": 3 } }
]
}
],
@@ -68,10 +70,10 @@ var _ = Describe("Criteria", func() {
gomega.Expect(err).ToNot(gomega.HaveOccurred())
gomega.Expect(sql).To(gomega.Equal(
`(media_file.title LIKE ? AND media_file.title NOT LIKE ? ` +
- `AND (not exists (select 1 from json_tree(participants, '$.artist') where key='name' and value = ?) ` +
+ `AND (not exists (select 1 from json_tree(media_file.participants, '$.artist') where key='name' and value = ?) ` +
`OR media_file.album = ?) AND (media_file.comment LIKE ? AND (media_file.year >= ? AND media_file.year <= ?) ` +
- `AND not exists (select 1 from json_tree(tags, '$.genre') where key='value' and value = ?)))`))
- gomega.Expect(args).To(gomega.HaveExactElements("%love%", "%hate%", "u2", "best of", "this%", 1980, 1990, "Rock"))
+ `AND not exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value = ?) AND COALESCE(album_annotation.rating, 0) > ?))`))
+ gomega.Expect(args).To(gomega.HaveExactElements("%love%", "%hate%", "u2", "best of", "this%", 1980, 1990, "Rock", 3))
})
It("marshals to JSON", func() {
j, err := json.Marshal(goObj)
@@ -118,6 +120,16 @@ var _ = Describe("Criteria", func() {
)
})
+ It("sorts by albumtype alias (resolves to releasetype)", func() {
+ AddTagNames([]string{"releasetype"})
+ goObj.Sort = "albumtype"
+ gomega.Expect(goObj.OrderBy()).To(
+ gomega.Equal(
+ "COALESCE(json_extract(media_file.tags, '$.releasetype[0].value'), '') asc",
+ ),
+ )
+ })
+
It("sorts by random", func() {
newObj := goObj
newObj.Sort = "random"
@@ -162,13 +174,237 @@ var _ = Describe("Criteria", func() {
sql, args, err := goObj.ToSql()
gomega.Expect(err).ToNot(gomega.HaveOccurred())
gomega.Expect(sql).To(gomega.Equal(
- `(exists (select 1 from json_tree(participants, '$.artist') where key='name' and value = ?) AND ` +
- `exists (select 1 from json_tree(participants, '$.composer') where key='name' and value LIKE ?))`,
+ `(exists (select 1 from json_tree(media_file.participants, '$.artist') where key='name' and value = ?) AND ` +
+ `exists (select 1 from json_tree(media_file.participants, '$.composer') where key='name' and value LIKE ?))`,
))
gomega.Expect(args).To(gomega.HaveExactElements("The Beatles", "%Lennon%"))
})
})
+ Describe("ExpressionJoins", func() {
+ It("excludes sort-only joins", func() {
+ c := Criteria{
+ Expression: All{
+ Contains{"title": "love"},
+ },
+ Sort: "albumRating",
+ }
+ gomega.Expect(c.ExpressionJoins()).To(gomega.Equal(JoinNone))
+ gomega.Expect(c.RequiredJoins().Has(JoinAlbumAnnotation)).To(gomega.BeTrue())
+ })
+
+ It("includes expression-based joins", func() {
+ c := Criteria{
+ Expression: All{
+ Gt{"albumRating": 3},
+ },
+ }
+ gomega.Expect(c.ExpressionJoins().Has(JoinAlbumAnnotation)).To(gomega.BeTrue())
+ })
+ })
+
+ Describe("RequiredJoins", func() {
+ It("returns JoinNone when no annotation fields are used", func() {
+ c := Criteria{
+ Expression: All{
+ Contains{"title": "love"},
+ },
+ }
+ gomega.Expect(c.RequiredJoins()).To(gomega.Equal(JoinNone))
+ })
+ It("returns JoinNone for media_file annotation fields", func() {
+ c := Criteria{
+ Expression: All{
+ Is{"loved": true},
+ Gt{"playCount": 5},
+ },
+ }
+ gomega.Expect(c.RequiredJoins()).To(gomega.Equal(JoinNone))
+ })
+ It("returns JoinAlbumAnnotation for album annotation fields", func() {
+ c := Criteria{
+ Expression: All{
+ Gt{"albumRating": 3},
+ },
+ }
+ gomega.Expect(c.RequiredJoins()).To(gomega.Equal(JoinAlbumAnnotation))
+ })
+ It("returns JoinArtistAnnotation for artist annotation fields", func() {
+ c := Criteria{
+ Expression: All{
+ Is{"artistLoved": true},
+ },
+ }
+ gomega.Expect(c.RequiredJoins()).To(gomega.Equal(JoinArtistAnnotation))
+ })
+ It("returns both join types when both are used", func() {
+ c := Criteria{
+ Expression: All{
+ Gt{"albumRating": 3},
+ Is{"artistLoved": true},
+ },
+ }
+ j := c.RequiredJoins()
+ gomega.Expect(j.Has(JoinAlbumAnnotation)).To(gomega.BeTrue())
+ gomega.Expect(j.Has(JoinArtistAnnotation)).To(gomega.BeTrue())
+ })
+ It("detects join types in nested expressions", func() {
+ c := Criteria{
+ Expression: All{
+ Any{
+ All{
+ Is{"albumLoved": true},
+ },
+ },
+ Any{
+ Gt{"artistPlayCount": 10},
+ },
+ },
+ }
+ j := c.RequiredJoins()
+ gomega.Expect(j.Has(JoinAlbumAnnotation)).To(gomega.BeTrue())
+ gomega.Expect(j.Has(JoinArtistAnnotation)).To(gomega.BeTrue())
+ })
+ It("detects join types from Sort field", func() {
+ c := Criteria{
+ Expression: All{
+ Contains{"title": "love"},
+ },
+ Sort: "albumRating",
+ }
+ gomega.Expect(c.RequiredJoins().Has(JoinAlbumAnnotation)).To(gomega.BeTrue())
+ })
+ It("detects join types from Sort field with direction prefix", func() {
+ c := Criteria{
+ Expression: All{
+ Contains{"title": "love"},
+ },
+ Sort: "-artistRating",
+ }
+ gomega.Expect(c.RequiredJoins().Has(JoinArtistAnnotation)).To(gomega.BeTrue())
+ })
+ })
+
+ Describe("LimitPercent", func() {
+ Describe("JSON round-trip", func() {
+ It("marshals and unmarshals limitPercent", func() {
+ goObj := Criteria{
+ Expression: All{Contains{"title": "love"}},
+ Sort: "title",
+ Order: "asc",
+ LimitPercent: 10,
+ }
+ j, err := json.Marshal(goObj)
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(string(j)).To(gomega.ContainSubstring(`"limitPercent":10`))
+ gomega.Expect(string(j)).ToNot(gomega.ContainSubstring(`"limit"`))
+
+ var newObj Criteria
+ err = json.Unmarshal(j, &newObj)
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(newObj.LimitPercent).To(gomega.Equal(10))
+ gomega.Expect(newObj.Limit).To(gomega.Equal(0))
+ })
+
+ It("does not include limitPercent when zero", func() {
+ goObj := Criteria{
+ Expression: All{Contains{"title": "love"}},
+ Limit: 50,
+ }
+ j, err := json.Marshal(goObj)
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(string(j)).To(gomega.ContainSubstring(`"limit":50`))
+ gomega.Expect(string(j)).ToNot(gomega.ContainSubstring(`limitPercent`))
+ })
+
+ It("backward compatible: JSON with only limit still works", func() {
+ jsonStr := `{"all":[{"contains":{"title":"love"}}],"limit":20}`
+ var c Criteria
+ err := json.Unmarshal([]byte(jsonStr), &c)
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(c.Limit).To(gomega.Equal(20))
+ gomega.Expect(c.LimitPercent).To(gomega.Equal(0))
+ })
+ })
+
+ Describe("UnmarshalJSON clamping", func() {
+ It("clamps values above 100 to 100", func() {
+ jsonStr := `{"all":[{"contains":{"title":"love"}}],"limitPercent":150}`
+ var c Criteria
+ err := json.Unmarshal([]byte(jsonStr), &c)
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(c.LimitPercent).To(gomega.Equal(100))
+ })
+
+ It("clamps negative values to 0", func() {
+ jsonStr := `{"all":[{"contains":{"title":"love"}}],"limitPercent":-5}`
+ var c Criteria
+ err := json.Unmarshal([]byte(jsonStr), &c)
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(c.LimitPercent).To(gomega.Equal(0))
+ })
+ })
+
+ Describe("EffectiveLimit", func() {
+ It("returns fixed limit when Limit is set", func() {
+ c := Criteria{Limit: 50, LimitPercent: 10}
+ gomega.Expect(c.EffectiveLimit(1000)).To(gomega.Equal(50))
+ })
+
+ It("returns percentage-based limit", func() {
+ c := Criteria{LimitPercent: 10}
+ gomega.Expect(c.EffectiveLimit(450)).To(gomega.Equal(45))
+ })
+
+ It("returns minimum 1 when totalCount > 0 and percentage rounds to 0", func() {
+ c := Criteria{LimitPercent: 1}
+ gomega.Expect(c.EffectiveLimit(5)).To(gomega.Equal(1))
+ })
+
+ It("returns 0 when totalCount is 0", func() {
+ c := Criteria{LimitPercent: 10}
+ gomega.Expect(c.EffectiveLimit(0)).To(gomega.Equal(0))
+ })
+
+ It("returns 0 when no limit is set", func() {
+ c := Criteria{}
+ gomega.Expect(c.EffectiveLimit(1000)).To(gomega.Equal(0))
+ })
+
+ It("returns full count for 100%", func() {
+ c := Criteria{LimitPercent: 100}
+ gomega.Expect(c.EffectiveLimit(450)).To(gomega.Equal(450))
+ })
+
+ It("returns 1 for 1% of 50 items", func() {
+ c := Criteria{LimitPercent: 1}
+ gomega.Expect(c.EffectiveLimit(50)).To(gomega.Equal(1))
+ })
+ })
+
+ Describe("IsPercentageLimit", func() {
+ It("returns true when LimitPercent is set and Limit is 0", func() {
+ c := Criteria{LimitPercent: 10}
+ gomega.Expect(c.IsPercentageLimit()).To(gomega.BeTrue())
+ })
+
+ It("returns false when Limit is set", func() {
+ c := Criteria{Limit: 50, LimitPercent: 10}
+ gomega.Expect(c.IsPercentageLimit()).To(gomega.BeFalse())
+ })
+
+ It("returns false when neither is set", func() {
+ c := Criteria{}
+ gomega.Expect(c.IsPercentageLimit()).To(gomega.BeFalse())
+ })
+
+ It("returns false when LimitPercent is out of range", func() {
+ c := Criteria{LimitPercent: 150}
+ gomega.Expect(c.IsPercentageLimit()).To(gomega.BeFalse())
+ })
+ })
+ })
+
Context("with child playlists", func() {
var (
topLevelInPlaylistID string
diff --git a/model/criteria/fields.go b/model/criteria/fields.go
index 3699eb14a..b9d91f087 100644
--- a/model/criteria/fields.go
+++ b/model/criteria/fields.go
@@ -9,44 +9,72 @@ import (
"github.com/navidrome/navidrome/log"
)
+// JoinType is a bitmask indicating which additional JOINs are needed by a smart playlist expression.
+type JoinType int
+
+const (
+ JoinNone JoinType = 0
+ JoinAlbumAnnotation JoinType = 1 << iota
+ JoinArtistAnnotation
+)
+
+// Has returns true if j contains all bits in other.
+func (j JoinType) Has(other JoinType) bool { return j&other != 0 }
+
var fieldMap = map[string]*mappedField{
- "title": {field: "media_file.title"},
- "album": {field: "media_file.album"},
- "hascoverart": {field: "media_file.has_cover_art"},
- "tracknumber": {field: "media_file.track_number"},
- "discnumber": {field: "media_file.disc_number"},
- "year": {field: "media_file.year"},
- "date": {field: "media_file.date", alias: "recordingdate"},
- "originalyear": {field: "media_file.original_year"},
- "originaldate": {field: "media_file.original_date"},
- "releaseyear": {field: "media_file.release_year"},
- "releasedate": {field: "media_file.release_date"},
- "size": {field: "media_file.size"},
- "compilation": {field: "media_file.compilation"},
- "dateadded": {field: "media_file.created_at"},
- "datemodified": {field: "media_file.updated_at"},
- "discsubtitle": {field: "media_file.disc_subtitle"},
- "comment": {field: "media_file.comment"},
- "lyrics": {field: "media_file.lyrics"},
- "sorttitle": {field: "media_file.sort_title"},
- "sortalbum": {field: "media_file.sort_album_name"},
- "sortartist": {field: "media_file.sort_artist_name"},
- "sortalbumartist": {field: "media_file.sort_album_artist_name"},
- "albumtype": {field: "media_file.mbz_album_type", alias: "releasetype"},
- "albumcomment": {field: "media_file.mbz_album_comment"},
- "catalognumber": {field: "media_file.catalog_num"},
- "filepath": {field: "media_file.path"},
- "filetype": {field: "media_file.suffix"},
- "duration": {field: "media_file.duration"},
- "bitrate": {field: "media_file.bit_rate"},
- "bitdepth": {field: "media_file.bit_depth"},
- "bpm": {field: "media_file.bpm"},
- "channels": {field: "media_file.channels"},
- "loved": {field: "COALESCE(annotation.starred, false)"},
- "dateloved": {field: "annotation.starred_at"},
- "lastplayed": {field: "annotation.play_date"},
- "playcount": {field: "COALESCE(annotation.play_count, 0)"},
- "rating": {field: "COALESCE(annotation.rating, 0)"},
+ "title": {field: "media_file.title"},
+ "album": {field: "media_file.album"},
+ "hascoverart": {field: "media_file.has_cover_art"},
+ "tracknumber": {field: "media_file.track_number"},
+ "discnumber": {field: "media_file.disc_number"},
+ "year": {field: "media_file.year"},
+ "date": {field: "media_file.date", alias: "recordingdate"},
+ "originalyear": {field: "media_file.original_year"},
+ "originaldate": {field: "media_file.original_date"},
+ "releaseyear": {field: "media_file.release_year"},
+ "releasedate": {field: "media_file.release_date"},
+ "size": {field: "media_file.size"},
+ "compilation": {field: "media_file.compilation"},
+ "explicitstatus": {field: "media_file.explicit_status"},
+ "dateadded": {field: "media_file.created_at"},
+ "datemodified": {field: "media_file.updated_at"},
+ "discsubtitle": {field: "media_file.disc_subtitle"},
+ "comment": {field: "media_file.comment"},
+ "lyrics": {field: "media_file.lyrics"},
+ "sorttitle": {field: "media_file.sort_title"},
+ "sortalbum": {field: "media_file.sort_album_name"},
+ "sortartist": {field: "media_file.sort_artist_name"},
+ "sortalbumartist": {field: "media_file.sort_album_artist_name"},
+ "albumcomment": {field: "media_file.mbz_album_comment"},
+ "catalognumber": {field: "media_file.catalog_num"},
+ "filepath": {field: "media_file.path"},
+ "filetype": {field: "media_file.suffix"},
+ "duration": {field: "media_file.duration"},
+ "bitrate": {field: "media_file.bit_rate"},
+ "bitdepth": {field: "media_file.bit_depth"},
+ "bpm": {field: "media_file.bpm"},
+ "channels": {field: "media_file.channels"},
+ "loved": {field: "COALESCE(annotation.starred, false)"},
+ "dateloved": {field: "annotation.starred_at"},
+ "lastplayed": {field: "annotation.play_date"},
+ "daterated": {field: "annotation.rated_at"},
+ "playcount": {field: "COALESCE(annotation.play_count, 0)"},
+ "rating": {field: "COALESCE(annotation.rating, 0)"},
+ "averagerating": {field: "media_file.average_rating", numeric: true},
+ "albumrating": {field: "COALESCE(album_annotation.rating, 0)", joinType: JoinAlbumAnnotation},
+ "albumloved": {field: "COALESCE(album_annotation.starred, false)", joinType: JoinAlbumAnnotation},
+ "albumplaycount": {field: "COALESCE(album_annotation.play_count, 0)", joinType: JoinAlbumAnnotation},
+ "albumlastplayed": {field: "album_annotation.play_date", joinType: JoinAlbumAnnotation},
+ "albumdateloved": {field: "album_annotation.starred_at", joinType: JoinAlbumAnnotation},
+ "albumdaterated": {field: "album_annotation.rated_at", joinType: JoinAlbumAnnotation},
+
+ "artistrating": {field: "COALESCE(artist_annotation.rating, 0)", joinType: JoinArtistAnnotation},
+ "artistloved": {field: "COALESCE(artist_annotation.starred, false)", joinType: JoinArtistAnnotation},
+ "artistplaycount": {field: "COALESCE(artist_annotation.play_count, 0)", joinType: JoinArtistAnnotation},
+ "artistlastplayed": {field: "artist_annotation.play_date", joinType: JoinArtistAnnotation},
+ "artistdateloved": {field: "artist_annotation.starred_at", joinType: JoinArtistAnnotation},
+ "artistdaterated": {field: "artist_annotation.rated_at", joinType: JoinArtistAnnotation},
+
"mbz_album_id": {field: "media_file.mbz_album_id"},
"mbz_album_artist_id": {field: "media_file.mbz_album_artist_id"},
"mbz_artist_id": {field: "media_file.mbz_artist_id"},
@@ -55,18 +83,22 @@ var fieldMap = map[string]*mappedField{
"mbz_release_group_id": {field: "media_file.mbz_release_group_id"},
"library_id": {field: "media_file.library_id", numeric: true},
+ // Backward compatibility: albumtype is an alias for releasetype tag
+ "albumtype": {field: "releasetype", isTag: true},
+
// special fields
"random": {field: "", order: "random()"}, // pseudo-field for random sorting
"value": {field: "value"}, // pseudo-field for tag and roles values
}
type mappedField struct {
- field string
- order string
- isRole bool // true if the field is a role (e.g. "artist", "composer", "conductor", etc.)
- isTag bool // true if the field is a tag imported from the file metadata
- alias string // name from `mappings.yml` that may differ from the name used in the smart playlist
- numeric bool // true if the field/tag should be treated as numeric
+ field string
+ order string
+ isRole bool // true if the field is a role (e.g. "artist", "composer", "conductor", etc.)
+ isTag bool // true if the field is a tag imported from the file metadata
+ alias string // name from `mappings.yml` that may differ from the name used in the smart playlist
+ numeric bool // true if the field/tag should be treated as numeric
+ joinType JoinType // which additional JOINs this field requires
}
func mapFields(expr map[string]any) map[string]any {
@@ -90,27 +122,24 @@ func mapExpr(expr squirrel.Sqlizer, negate bool, exprFunc func(string, squirrel.
log.Fatal(fmt.Sprintf("expr is not a map-based operator: %T", expr))
}
- // Extract into a generic map
+ // Extract the field name and value, then build a new map keyed by "value"
+ // for the inner condition. The original map is left untouched so that
+ // ToSql can be called multiple times without corruption.
var k string
- m := make(map[string]any, rv.Len())
+ var v any
for _, key := range rv.MapKeys() {
- // Save the key to build the expression, and use the provided keyName as the key
k = key.String()
- m["value"] = rv.MapIndex(key).Interface()
+ v = rv.MapIndex(key).Interface()
break // only one key is expected (and supported)
}
- // Clear the original map
- for _, key := range rv.MapKeys() {
- rv.SetMapIndex(key, reflect.Value{})
- }
+ // Create a new map-based expression with "value" as the key, matching the
+ // column name inside json_tree subqueries.
+ newMap := reflect.MakeMap(rv.Type())
+ newMap.SetMapIndex(reflect.ValueOf("value"), reflect.ValueOf(v))
+ newExpr := newMap.Interface().(squirrel.Sqlizer)
- // Write the updated map back into the original variable
- for key, val := range m {
- rv.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(val))
- }
-
- return exprFunc(k, expr, negate)
+ return exprFunc(k, newExpr, negate)
}
// mapTagExpr maps a normal field expression to a tag expression.
@@ -154,13 +183,19 @@ type tagCond struct {
func (e tagCond) ToSql() (string, []any, error) {
cond, args, err := e.cond.ToSql()
- // Check if this tag is marked as numeric in the fieldMap
- if fm, ok := fieldMap[e.tag]; ok && fm.numeric {
- cond = strings.ReplaceAll(cond, "value", "CAST(value AS REAL)")
+ // Resolve the actual tag name (handles aliases like albumtype -> releasetype)
+ tagName := e.tag
+ if fm, ok := fieldMap[e.tag]; ok {
+ if fm.field != "" {
+ tagName = fm.field
+ }
+ if fm.numeric {
+ cond = strings.ReplaceAll(cond, "value", "CAST(value AS REAL)")
+ }
}
- cond = fmt.Sprintf("exists (select 1 from json_tree(tags, '$.%s') where key='value' and %s)",
- e.tag, cond)
+ cond = fmt.Sprintf("exists (select 1 from json_tree(media_file.tags, '$.%s') where key='value' and %s)",
+ tagName, cond)
if e.not {
cond = "not " + cond
}
@@ -179,7 +214,7 @@ type roleCond struct {
func (e roleCond) ToSql() (string, []any, error) {
cond, args, err := e.cond.ToSql()
- cond = fmt.Sprintf(`exists (select 1 from json_tree(participants, '$.%s') where key='name' and %s)`,
+ cond = fmt.Sprintf(`exists (select 1 from json_tree(media_file.participants, '$.%s') where key='name' and %s)`,
e.role, cond)
if e.not {
cond = "not " + cond
@@ -187,6 +222,38 @@ func (e roleCond) ToSql() (string, []any, error) {
return cond, args, err
}
+// fieldJoinType returns the JoinType for a given field name (case-insensitive).
+func fieldJoinType(name string) JoinType {
+ if f, ok := fieldMap[strings.ToLower(name)]; ok {
+ return f.joinType
+ }
+ return JoinNone
+}
+
+// extractJoinTypes walks an expression tree and collects all required JoinType flags.
+func extractJoinTypes(expr any) JoinType {
+ result := JoinNone
+ switch e := expr.(type) {
+ case All:
+ for _, sub := range e {
+ result |= extractJoinTypes(sub)
+ }
+ case Any:
+ for _, sub := range e {
+ result |= extractJoinTypes(sub)
+ }
+ default:
+ // Leaf expression: use reflection to check if it's a map with field names
+ rv := reflect.ValueOf(expr)
+ if rv.Kind() == reflect.Map && rv.Type().Key().Kind() == reflect.String {
+ for _, key := range rv.MapKeys() {
+ result |= fieldJoinType(key.String())
+ }
+ }
+ }
+ return result
+}
+
// AddRoles adds roles to the field map. This is used to add all artist roles to the field map, so they can be used in
// smart playlists. If a role already exists in the field map, it is ignored, so calls to this function are idempotent.
func AddRoles(roles []string) {
diff --git a/model/criteria/operators_test.go b/model/criteria/operators_test.go
index ee716a9cd..5f756f97d 100644
--- a/model/criteria/operators_test.go
+++ b/model/criteria/operators_test.go
@@ -54,23 +54,43 @@ var _ = Describe("Operators", func() {
Entry("inTheLast", InTheLast{"lastPlayed": 30}, "annotation.play_date > ?", StartOfPeriod(30, time.Now())),
Entry("notInTheLast", NotInTheLast{"lastPlayed": 30}, "(annotation.play_date < ? OR annotation.play_date IS NULL)", StartOfPeriod(30, time.Now())),
+ // Album annotation fields
+ Entry("albumRating", Gt{"albumRating": 3}, "COALESCE(album_annotation.rating, 0) > ?", 3),
+ Entry("albumLoved", Is{"albumLoved": true}, "COALESCE(album_annotation.starred, false) = ?", true),
+ Entry("albumPlayCount", Gt{"albumPlayCount": 5}, "COALESCE(album_annotation.play_count, 0) > ?", 5),
+ Entry("albumLastPlayed", After{"albumLastPlayed": rangeStart}, "album_annotation.play_date > ?", rangeStart),
+ Entry("albumDateLoved", Before{"albumDateLoved": rangeStart}, "album_annotation.starred_at < ?", rangeStart),
+ Entry("albumDateRated", After{"albumDateRated": rangeStart}, "album_annotation.rated_at > ?", rangeStart),
+ Entry("albumLastPlayed inTheLast", InTheLast{"albumLastPlayed": 30}, "album_annotation.play_date > ?", StartOfPeriod(30, time.Now())),
+ Entry("albumLastPlayed notInTheLast", NotInTheLast{"albumLastPlayed": 30}, "(album_annotation.play_date < ? OR album_annotation.play_date IS NULL)", StartOfPeriod(30, time.Now())),
+
+ // Artist annotation fields
+ Entry("artistRating", Gt{"artistRating": 3}, "COALESCE(artist_annotation.rating, 0) > ?", 3),
+ Entry("artistLoved", Is{"artistLoved": true}, "COALESCE(artist_annotation.starred, false) = ?", true),
+ Entry("artistPlayCount", Gt{"artistPlayCount": 5}, "COALESCE(artist_annotation.play_count, 0) > ?", 5),
+ Entry("artistLastPlayed", After{"artistLastPlayed": rangeStart}, "artist_annotation.play_date > ?", rangeStart),
+ Entry("artistDateLoved", Before{"artistDateLoved": rangeStart}, "artist_annotation.starred_at < ?", rangeStart),
+ Entry("artistDateRated", After{"artistDateRated": rangeStart}, "artist_annotation.rated_at > ?", rangeStart),
+ Entry("artistLastPlayed inTheLast", InTheLast{"artistLastPlayed": 30}, "artist_annotation.play_date > ?", StartOfPeriod(30, time.Now())),
+ Entry("artistLastPlayed notInTheLast", NotInTheLast{"artistLastPlayed": 30}, "(artist_annotation.play_date < ? OR artist_annotation.play_date IS NULL)", StartOfPeriod(30, time.Now())),
+
// Tag tests
- Entry("tag is [string]", Is{"genre": "Rock"}, "exists (select 1 from json_tree(tags, '$.genre') where key='value' and value = ?)", "Rock"),
- Entry("tag isNot [string]", IsNot{"genre": "Rock"}, "not exists (select 1 from json_tree(tags, '$.genre') where key='value' and value = ?)", "Rock"),
- Entry("tag gt", Gt{"genre": "A"}, "exists (select 1 from json_tree(tags, '$.genre') where key='value' and value > ?)", "A"),
- Entry("tag lt", Lt{"genre": "Z"}, "exists (select 1 from json_tree(tags, '$.genre') where key='value' and value < ?)", "Z"),
- Entry("tag contains", Contains{"genre": "Rock"}, "exists (select 1 from json_tree(tags, '$.genre') where key='value' and value LIKE ?)", "%Rock%"),
- Entry("tag not contains", NotContains{"genre": "Rock"}, "not exists (select 1 from json_tree(tags, '$.genre') where key='value' and value LIKE ?)", "%Rock%"),
- Entry("tag startsWith", StartsWith{"genre": "Soft"}, "exists (select 1 from json_tree(tags, '$.genre') where key='value' and value LIKE ?)", "Soft%"),
- Entry("tag endsWith", EndsWith{"genre": "Rock"}, "exists (select 1 from json_tree(tags, '$.genre') where key='value' and value LIKE ?)", "%Rock"),
+ Entry("tag is [string]", Is{"genre": "Rock"}, "exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value = ?)", "Rock"),
+ Entry("tag isNot [string]", IsNot{"genre": "Rock"}, "not exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value = ?)", "Rock"),
+ Entry("tag gt", Gt{"genre": "A"}, "exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value > ?)", "A"),
+ Entry("tag lt", Lt{"genre": "Z"}, "exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value < ?)", "Z"),
+ Entry("tag contains", Contains{"genre": "Rock"}, "exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value LIKE ?)", "%Rock%"),
+ Entry("tag not contains", NotContains{"genre": "Rock"}, "not exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value LIKE ?)", "%Rock%"),
+ Entry("tag startsWith", StartsWith{"genre": "Soft"}, "exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value LIKE ?)", "Soft%"),
+ Entry("tag endsWith", EndsWith{"genre": "Rock"}, "exists (select 1 from json_tree(media_file.tags, '$.genre') where key='value' and value LIKE ?)", "%Rock"),
// Artist roles tests
- Entry("role is [string]", Is{"artist": "u2"}, "exists (select 1 from json_tree(participants, '$.artist') where key='name' and value = ?)", "u2"),
- Entry("role isNot [string]", IsNot{"artist": "u2"}, "not exists (select 1 from json_tree(participants, '$.artist') where key='name' and value = ?)", "u2"),
- Entry("role contains [string]", Contains{"artist": "u2"}, "exists (select 1 from json_tree(participants, '$.artist') where key='name' and value LIKE ?)", "%u2%"),
- Entry("role not contains [string]", NotContains{"artist": "u2"}, "not exists (select 1 from json_tree(participants, '$.artist') where key='name' and value LIKE ?)", "%u2%"),
- Entry("role startsWith [string]", StartsWith{"composer": "John"}, "exists (select 1 from json_tree(participants, '$.composer') where key='name' and value LIKE ?)", "John%"),
- Entry("role endsWith [string]", EndsWith{"composer": "Lennon"}, "exists (select 1 from json_tree(participants, '$.composer') where key='name' and value LIKE ?)", "%Lennon"),
+ Entry("role is [string]", Is{"artist": "u2"}, "exists (select 1 from json_tree(media_file.participants, '$.artist') where key='name' and value = ?)", "u2"),
+ Entry("role isNot [string]", IsNot{"artist": "u2"}, "not exists (select 1 from json_tree(media_file.participants, '$.artist') where key='name' and value = ?)", "u2"),
+ Entry("role contains [string]", Contains{"artist": "u2"}, "exists (select 1 from json_tree(media_file.participants, '$.artist') where key='name' and value LIKE ?)", "%u2%"),
+ Entry("role not contains [string]", NotContains{"artist": "u2"}, "not exists (select 1 from json_tree(media_file.participants, '$.artist') where key='name' and value LIKE ?)", "%u2%"),
+ Entry("role startsWith [string]", StartsWith{"composer": "John"}, "exists (select 1 from json_tree(media_file.participants, '$.composer') where key='name' and value LIKE ?)", "John%"),
+ Entry("role endsWith [string]", EndsWith{"composer": "Lennon"}, "exists (select 1 from json_tree(media_file.participants, '$.composer') where key='name' and value LIKE ?)", "%Lennon"),
)
// TODO Validate operators that are not valid for each field type.
@@ -88,7 +108,7 @@ var _ = Describe("Operators", func() {
op := EndsWith{"mood": "Soft"}
sql, args, err := op.ToSql()
gomega.Expect(err).ToNot(gomega.HaveOccurred())
- gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(tags, '$.mood') where key='value' and value LIKE ?)"))
+ gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(media_file.tags, '$.mood') where key='value' and value LIKE ?)"))
gomega.Expect(args).To(gomega.HaveExactElements("%Soft"))
})
It("casts numeric comparisons", func() {
@@ -96,7 +116,7 @@ var _ = Describe("Operators", func() {
op := Lt{"rate": 6}
sql, args, err := op.ToSql()
gomega.Expect(err).ToNot(gomega.HaveOccurred())
- gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(tags, '$.rate') where key='value' and CAST(value AS REAL) < ?)"))
+ gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(media_file.tags, '$.rate') where key='value' and CAST(value AS REAL) < ?)"))
gomega.Expect(args).To(gomega.HaveExactElements(6))
})
It("skips unknown tag names", func() {
@@ -105,6 +125,40 @@ var _ = Describe("Operators", func() {
gomega.Expect(sql).To(gomega.BeEmpty())
gomega.Expect(args).To(gomega.BeEmpty())
})
+ It("supports releasetype as multi-valued tag", func() {
+ AddTagNames([]string{"releasetype"})
+ op := Contains{"releasetype": "soundtrack"}
+ sql, args, err := op.ToSql()
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(media_file.tags, '$.releasetype') where key='value' and value LIKE ?)"))
+ gomega.Expect(args).To(gomega.HaveExactElements("%soundtrack%"))
+ })
+ It("supports albumtype as alias for releasetype", func() {
+ AddTagNames([]string{"releasetype"})
+ op := Contains{"albumtype": "live"}
+ sql, args, err := op.ToSql()
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(media_file.tags, '$.releasetype') where key='value' and value LIKE ?)"))
+ gomega.Expect(args).To(gomega.HaveExactElements("%live%"))
+ })
+ It("supports albumtype alias with Is operator", func() {
+ AddTagNames([]string{"releasetype"})
+ op := Is{"albumtype": "album"}
+ sql, args, err := op.ToSql()
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ // Should query $.releasetype, not $.albumtype
+ gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(media_file.tags, '$.releasetype') where key='value' and value = ?)"))
+ gomega.Expect(args).To(gomega.HaveExactElements("album"))
+ })
+ It("supports albumtype alias with IsNot operator", func() {
+ AddTagNames([]string{"releasetype"})
+ op := IsNot{"albumtype": "compilation"}
+ sql, args, err := op.ToSql()
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+ // Should query $.releasetype, not $.albumtype
+ gomega.Expect(sql).To(gomega.Equal("not exists (select 1 from json_tree(media_file.tags, '$.releasetype') where key='value' and value = ?)"))
+ gomega.Expect(args).To(gomega.HaveExactElements("compilation"))
+ })
})
Describe("Custom Roles", func() {
@@ -113,7 +167,7 @@ var _ = Describe("Operators", func() {
op := EndsWith{"producer": "Eno"}
sql, args, err := op.ToSql()
gomega.Expect(err).ToNot(gomega.HaveOccurred())
- gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(participants, '$.producer') where key='name' and value LIKE ?)"))
+ gomega.Expect(sql).To(gomega.Equal("exists (select 1 from json_tree(media_file.participants, '$.producer') where key='name' and value LIKE ?)"))
gomega.Expect(args).To(gomega.HaveExactElements("%Eno"))
})
It("skips unknown roles", func() {
@@ -124,6 +178,21 @@ var _ = Describe("Operators", func() {
})
})
+ DescribeTable("ToSql idempotency",
+ func(expr Expression) {
+ sql1, args1, err1 := expr.ToSql()
+ sql2, args2, err2 := expr.ToSql()
+
+ gomega.Expect(err1).ToNot(gomega.HaveOccurred())
+ gomega.Expect(err2).ToNot(gomega.HaveOccurred())
+ gomega.Expect(sql2).To(gomega.Equal(sql1))
+ gomega.Expect(args2).To(gomega.Equal(args1))
+ },
+ Entry("tag expression", Is{"genre": "Rock"}),
+ Entry("role expression", Contains{"artist": "Beatles"}),
+ Entry("nested criteria", Criteria{Expression: All{Is{"genre": "Rock"}, Contains{"artist": "Beatles"}}}),
+ )
+
DescribeTable("JSON Marshaling",
func(op Expression, jsonString string) {
obj := And{op}
diff --git a/model/datastore.go b/model/datastore.go
index 4290e2134..94c3c3622 100644
--- a/model/datastore.go
+++ b/model/datastore.go
@@ -38,10 +38,12 @@ type DataStore interface {
User(ctx context.Context) UserRepository
UserProps(ctx context.Context) UserPropsRepository
ScrobbleBuffer(ctx context.Context) ScrobbleBufferRepository
+ Scrobble(ctx context.Context) ScrobbleRepository
+ Plugin(ctx context.Context) PluginRepository
- Resource(ctx context.Context, model interface{}) ResourceRepository
+ Resource(ctx context.Context, model any) ResourceRepository
WithTx(block func(tx DataStore) error, scope ...string) error
WithTxImmediate(block func(tx DataStore) error, scope ...string) error
- GC(ctx context.Context) error
+ GC(ctx context.Context, libraryIDs ...int) error
}
diff --git a/model/folder.go b/model/folder.go
index f715f8c11..7a769735e 100644
--- a/model/folder.go
+++ b/model/folder.go
@@ -85,7 +85,7 @@ type FolderRepository interface {
GetByPath(lib Library, path string) (*Folder, error)
GetAll(...QueryOptions) ([]Folder, error)
CountAll(...QueryOptions) (int64, error)
- GetLastUpdates(lib Library) (map[string]FolderUpdateInfo, error)
+ GetFolderUpdateInfo(lib Library, targetPaths ...string) (map[string]FolderUpdateInfo, error)
Put(*Folder) error
MarkMissing(missing bool, ids ...string) error
GetTouchedWithPlaylists() (FolderCursor, error)
diff --git a/model/get_entity.go b/model/get_entity.go
index f51d8c36a..60972b2e9 100644
--- a/model/get_entity.go
+++ b/model/get_entity.go
@@ -5,7 +5,7 @@ import (
)
// TODO: Should the type be encoded in the ID?
-func GetEntityByID(ctx context.Context, ds DataStore, id string) (interface{}, error) {
+func GetEntityByID(ctx context.Context, ds DataStore, id string) (any, error) {
ar, err := ds.Artist(ctx).Get(id)
if err == nil {
return ar, nil
@@ -22,5 +22,9 @@ func GetEntityByID(ctx context.Context, ds DataStore, id string) (interface{}, e
if err == nil {
return mf, nil
}
+ r, err := ds.Radio(ctx).Get(id)
+ if err == nil {
+ return r, nil
+ }
return nil, err
}
diff --git a/model/id/id.go b/model/id/id.go
index 930875260..b54542898 100644
--- a/model/id/id.go
+++ b/model/id/id.go
@@ -6,12 +6,12 @@ import (
"math/big"
"strings"
- gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/utils/nanoid"
)
func NewRandom() string {
- id, err := gonanoid.Generate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 22)
+ id, err := nanoid.Generate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 22)
if err != nil {
log.Error("Could not generate new ID", err)
}
diff --git a/model/image.go b/model/image.go
new file mode 100644
index 000000000..68d8ae64c
--- /dev/null
+++ b/model/image.go
@@ -0,0 +1,17 @@
+package model
+
+import (
+ "path/filepath"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/consts"
+)
+
+// UploadedImagePath returns the absolute filesystem path for a manually uploaded
+// entity cover image. Returns empty string if filename is empty.
+func UploadedImagePath(entityType, filename string) string {
+ if filename == "" {
+ return ""
+ }
+ return filepath.Join(conf.Server.DataFolder, consts.ArtworkFolder, entityType, filename)
+}
diff --git a/model/mediafile.go b/model/mediafile.go
index 0ef26d746..ec83b76fd 100644
--- a/model/mediafile.go
+++ b/model/mediafile.go
@@ -38,7 +38,7 @@ type MediaFile struct {
AlbumArtistID string `structs:"album_artist_id" json:"albumArtistId"` // Deprecated: Use Participants instead
// AlbumArtist is the display name used for the album artist.
AlbumArtist string `structs:"album_artist" json:"albumArtist"`
- AlbumID string `structs:"album_id" json:"albumId"`
+ AlbumID string `structs:"album_id" json:"albumId" hash:"ignore"`
HasCoverArt bool `structs:"has_cover_art" json:"hasCoverArt"`
TrackNumber int `structs:"track_number" json:"trackNumber"`
DiscNumber int `structs:"disc_number" json:"discNumber"`
@@ -56,6 +56,8 @@ type MediaFile struct {
SampleRate int `structs:"sample_rate" json:"sampleRate"`
BitDepth int `structs:"bit_depth" json:"bitDepth"`
Channels int `structs:"channels" json:"channels"`
+ Codec string `structs:"codec" json:"codec"`
+ ProbeData string `structs:"probe_data" json:"-" hash:"ignore"`
Genre string `structs:"genre" json:"genre"`
Genres Genres `structs:"-" json:"genres,omitempty"`
SortTitle string `structs:"sort_title" json:"sortTitle,omitempty"`
@@ -95,12 +97,19 @@ type MediaFile struct {
}
func (mf MediaFile) FullTitle() string {
- if conf.Server.Subsonic.AppendSubtitle && mf.Tags[TagSubtitle] != nil {
+ if conf.Server.Subsonic.AppendSubtitle && len(mf.Tags[TagSubtitle]) > 0 {
return fmt.Sprintf("%s (%s)", mf.Title, mf.Tags[TagSubtitle][0])
}
return mf.Title
}
+func (mf MediaFile) FullAlbumName() string {
+ if conf.Server.Subsonic.AppendAlbumVersion && len(mf.Tags[TagAlbumVersion]) > 0 {
+ return fmt.Sprintf("%s (%s)", mf.Album, mf.Tags[TagAlbumVersion][0])
+ }
+ return mf.Album
+}
+
func (mf MediaFile) ContentType() string {
return mime.TypeByExtension("." + mf.Suffix)
}
@@ -110,7 +119,16 @@ func (mf MediaFile) CoverArtID() ArtworkID {
if mf.HasCoverArt && conf.Server.EnableMediaFileCoverArt {
return artworkIDFromMediaFile(mf)
}
- // if it does not have a coverArt, fallback to the album cover
+ // Otherwise fallback to disc (if available) or album cover
+ return mf.DiscCoverArtID()
+}
+
+// DiscCoverArtID returns the disc artwork ID when the media file has a disc number,
+// otherwise it returns the album artwork ID.
+func (mf MediaFile) DiscCoverArtID() ArtworkID {
+ if mf.DiscNumber > 0 {
+ return NewArtworkID(KindDiscArtwork, DiscArtworkID(mf.AlbumID, mf.DiscNumber), nil)
+ }
return mf.AlbumCoverArtID()
}
@@ -140,7 +158,7 @@ func (mf MediaFile) Hash() string {
}
hash, _ := hashstructure.Hash(mf, opts)
sum := md5.New()
- sum.Write([]byte(fmt.Sprintf("%d", hash)))
+ sum.Write(fmt.Appendf(nil, "%d", hash))
sum.Write(mf.Tags.Hash())
sum.Write(mf.Participants.Hash())
return fmt.Sprintf("%x", sum.Sum(nil))
@@ -161,6 +179,63 @@ func (mf MediaFile) AbsolutePath() string {
return filepath.Join(mf.LibraryPath, mf.Path)
}
+// AudioCodec returns the audio codec for this file.
+// Uses the stored Codec field if available, otherwise infers from Suffix and audio properties.
+func (mf MediaFile) AudioCodec() string {
+ // If we have a stored codec from scanning, normalize and return it
+ if mf.Codec != "" {
+ return strings.ToLower(mf.Codec)
+ }
+ // Fallback: infer from Suffix + BitDepth
+ return mf.inferCodecFromSuffix()
+}
+
+// inferCodecFromSuffix infers the codec from the file extension when Codec field is empty.
+func (mf MediaFile) inferCodecFromSuffix() string {
+ switch strings.ToLower(mf.Suffix) {
+ case "mp3", "mpga":
+ return "mp3"
+ case "mp2":
+ return "mp2"
+ case "ogg", "oga":
+ return "vorbis"
+ case "opus":
+ return "opus"
+ case "mpc":
+ return "mpc"
+ case "wma":
+ return "wma"
+ case "flac":
+ return "flac"
+ case "wav":
+ return "pcm"
+ case "aif", "aiff", "aifc":
+ return "pcm"
+ case "ape":
+ return "ape"
+ case "wv", "wvp":
+ return "wv"
+ case "tta":
+ return "tta"
+ case "tak":
+ return "tak"
+ case "shn":
+ return "shn"
+ case "dsf", "dff":
+ return "dsd"
+ case "m4a":
+ // AAC if BitDepth==0, ALAC if BitDepth>0
+ if mf.BitDepth > 0 {
+ return "alac"
+ }
+ return "aac"
+ case "m4b", "m4p", "m4r":
+ return "aac"
+ default:
+ return ""
+ }
+}
+
type MediaFiles []MediaFile
// ToAlbum creates an Album object based on the attributes of this MediaFiles collection.
@@ -353,11 +428,14 @@ type MediaFileCursor iter.Seq2[MediaFile, error]
type MediaFileRepository interface {
CountAll(options ...QueryOptions) (int64, error)
+ CountBySuffix(options ...QueryOptions) (map[string]int64, error)
Exists(id string) (bool, error)
Put(m *MediaFile) error
+ UpdateProbeData(id string, data string) error
Get(id string) (*MediaFile, error)
GetWithParticipants(id string) (*MediaFile, error)
GetAll(options ...QueryOptions) (MediaFiles, error)
+ GetAllByTags(tag TagName, values []string, options ...QueryOptions) (MediaFiles, error)
GetCursor(options ...QueryOptions) (MediaFileCursor, error)
Delete(id string) error
DeleteMissing(ids []string) error
diff --git a/model/mediafile_test.go b/model/mediafile_test.go
index 635a61d30..038ac93d5 100644
--- a/model/mediafile_test.go
+++ b/model/mediafile_test.go
@@ -475,20 +475,55 @@ var _ = Describe("MediaFile", func() {
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableMediaFileCoverArt = true
})
- Describe(".CoverArtId()", func() {
+ DescribeTable("FullTitle",
+ func(enabled bool, tags Tags, expected string) {
+ conf.Server.Subsonic.AppendSubtitle = enabled
+ mf := MediaFile{Title: "Song", Tags: tags}
+ Expect(mf.FullTitle()).To(Equal(expected))
+ },
+ Entry("appends subtitle when enabled and tag is present", true, Tags{TagSubtitle: []string{"Live"}}, "Song (Live)"),
+ Entry("returns just title when disabled", false, Tags{TagSubtitle: []string{"Live"}}, "Song"),
+ Entry("returns just title when tag is absent", true, Tags{}, "Song"),
+ Entry("returns just title when tag is an empty slice", true, Tags{TagSubtitle: []string{}}, "Song"),
+ )
+ DescribeTable("FullAlbumName",
+ func(enabled bool, tags Tags, expected string) {
+ conf.Server.Subsonic.AppendAlbumVersion = enabled
+ mf := MediaFile{Album: "Album", Tags: tags}
+ Expect(mf.FullAlbumName()).To(Equal(expected))
+ },
+ Entry("appends version when enabled and tag is present", true, Tags{TagAlbumVersion: []string{"Deluxe Edition"}}, "Album (Deluxe Edition)"),
+ Entry("returns just album name when disabled", false, Tags{TagAlbumVersion: []string{"Deluxe Edition"}}, "Album"),
+ Entry("returns just album name when tag is absent", true, Tags{}, "Album"),
+ Entry("returns just album name when tag is an empty slice", true, Tags{TagAlbumVersion: []string{}}, "Album"),
+ )
+ Describe("CoverArtId", func() {
It("returns its own id if it HasCoverArt", func() {
mf := MediaFile{ID: "111", AlbumID: "1", HasCoverArt: true}
id := mf.CoverArtID()
Expect(id.Kind).To(Equal(KindMediaFileArtwork))
Expect(id.ID).To(Equal(mf.ID))
})
- It("returns its album id if HasCoverArt is false", func() {
+ It("returns disc art id if HasCoverArt is false and DiscNumber > 0", func() {
+ mf := MediaFile{ID: "111", AlbumID: "1", HasCoverArt: false, DiscNumber: 2}
+ id := mf.CoverArtID()
+ Expect(id.Kind).To(Equal(KindDiscArtwork))
+ Expect(id.ID).To(Equal("1:2"))
+ })
+ It("returns its album id if HasCoverArt is false and DiscNumber is 0", func() {
mf := MediaFile{ID: "111", AlbumID: "1", HasCoverArt: false}
id := mf.CoverArtID()
Expect(id.Kind).To(Equal(KindAlbumArtwork))
Expect(id.ID).To(Equal(mf.AlbumID))
})
- It("returns its album id if EnableMediaFileCoverArt is disabled", func() {
+ It("returns disc art id if EnableMediaFileCoverArt is disabled and DiscNumber > 0", func() {
+ conf.Server.EnableMediaFileCoverArt = false
+ mf := MediaFile{ID: "111", AlbumID: "1", HasCoverArt: true, DiscNumber: 3}
+ id := mf.CoverArtID()
+ Expect(id.Kind).To(Equal(KindDiscArtwork))
+ Expect(id.ID).To(Equal("1:3"))
+ })
+ It("returns its album id if EnableMediaFileCoverArt is disabled and DiscNumber is 0", func() {
conf.Server.EnableMediaFileCoverArt = false
mf := MediaFile{ID: "111", AlbumID: "1", HasCoverArt: true}
id := mf.CoverArtID()
@@ -496,6 +531,58 @@ var _ = Describe("MediaFile", func() {
Expect(id.ID).To(Equal(mf.AlbumID))
})
})
+
+ Describe("AudioCodec", func() {
+ It("returns normalized stored codec when available", func() {
+ mf := MediaFile{Codec: "AAC", Suffix: "m4a"}
+ Expect(mf.AudioCodec()).To(Equal("aac"))
+ })
+
+ It("returns stored codec lowercased", func() {
+ mf := MediaFile{Codec: "ALAC", Suffix: "m4a"}
+ Expect(mf.AudioCodec()).To(Equal("alac"))
+ })
+
+ DescribeTable("infers codec from suffix when Codec field is empty",
+ func(suffix string, bitDepth int, expected string) {
+ mf := MediaFile{Suffix: suffix, BitDepth: bitDepth}
+ Expect(mf.AudioCodec()).To(Equal(expected))
+ },
+ Entry("mp3", "mp3", 0, "mp3"),
+ Entry("mpga", "mpga", 0, "mp3"),
+ Entry("mp2", "mp2", 0, "mp2"),
+ Entry("ogg", "ogg", 0, "vorbis"),
+ Entry("oga", "oga", 0, "vorbis"),
+ Entry("opus", "opus", 0, "opus"),
+ Entry("mpc", "mpc", 0, "mpc"),
+ Entry("wma", "wma", 0, "wma"),
+ Entry("flac", "flac", 0, "flac"),
+ Entry("wav", "wav", 0, "pcm"),
+ Entry("aif", "aif", 0, "pcm"),
+ Entry("aiff", "aiff", 0, "pcm"),
+ Entry("aifc", "aifc", 0, "pcm"),
+ Entry("ape", "ape", 0, "ape"),
+ Entry("wv", "wv", 0, "wv"),
+ Entry("wvp", "wvp", 0, "wv"),
+ Entry("tta", "tta", 0, "tta"),
+ Entry("tak", "tak", 0, "tak"),
+ Entry("shn", "shn", 0, "shn"),
+ Entry("dsf", "dsf", 0, "dsd"),
+ Entry("dff", "dff", 0, "dsd"),
+ Entry("m4a with BitDepth=0 (AAC)", "m4a", 0, "aac"),
+ Entry("m4a with BitDepth>0 (ALAC)", "m4a", 16, "alac"),
+ Entry("m4b", "m4b", 0, "aac"),
+ Entry("m4p", "m4p", 0, "aac"),
+ Entry("m4r", "m4r", 0, "aac"),
+ Entry("unknown suffix", "xyz", 0, ""),
+ )
+
+ It("prefers stored codec over suffix inference", func() {
+ mf := MediaFile{Codec: "ALAC", Suffix: "m4a", BitDepth: 0}
+ Expect(mf.AudioCodec()).To(Equal("alac"))
+ })
+ })
+
})
func t(v string) time.Time {
diff --git a/model/metadata/legacy_ids.go b/model/metadata/legacy_ids.go
index 0a3bf0bf3..18a273550 100644
--- a/model/metadata/legacy_ids.go
+++ b/model/metadata/legacy_ids.go
@@ -23,7 +23,7 @@ func legacyTrackID(mf model.MediaFile, prependLibId bool) string {
}
func legacyAlbumID(mf model.MediaFile, md Metadata, prependLibId bool) string {
- releaseDate := legacyReleaseDate(md)
+ _, _, releaseDate := md.mapDates()
albumPath := strings.ToLower(fmt.Sprintf("%s\\%s", legacyMapAlbumArtistName(md), legacyMapAlbumName(md)))
if !conf.Server.Scanner.GroupAlbumReleases {
if len(releaseDate) != 0 {
@@ -55,9 +55,3 @@ func legacyMapAlbumName(md Metadata) string {
consts.UnknownAlbum,
)
}
-
-// Keep the TaggedLikePicard logic for backwards compatibility
-func legacyReleaseDate(md Metadata) string {
- _, _, releaseDate := md.mapDates()
- return string(releaseDate)
-}
diff --git a/model/metadata/legacy_ids_test.go b/model/metadata/legacy_ids_test.go
deleted file mode 100644
index b6d096763..000000000
--- a/model/metadata/legacy_ids_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package metadata
-
-import (
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("legacyReleaseDate", func() {
-
- DescribeTable("legacyReleaseDate",
- func(recordingDate, originalDate, releaseDate, expected string) {
- md := New("", Info{
- Tags: map[string][]string{
- "DATE": {recordingDate},
- "ORIGINALDATE": {originalDate},
- "RELEASEDATE": {releaseDate},
- },
- })
-
- result := legacyReleaseDate(md)
- Expect(result).To(Equal(expected))
- },
- Entry("regular mapping", "2020-05-15", "2019-02-10", "2021-01-01", "2021-01-01"),
- Entry("legacy mapping", "2020-05-15", "2019-02-10", "", "2020-05-15"),
- Entry("legacy mapping, originalYear < year", "2018-05-15", "2019-02-10", "2021-01-01", "2021-01-01"),
- Entry("legacy mapping, originalYear empty", "2020-05-15", "", "2021-01-01", "2021-01-01"),
- Entry("legacy mapping, releaseYear", "2020-05-15", "2019-02-10", "2021-01-01", "2021-01-01"),
- Entry("legacy mapping, same dates", "2020-05-15", "2020-05-15", "", "2020-05-15"),
- )
-})
diff --git a/model/metadata/map_mediafile.go b/model/metadata/map_mediafile.go
index c64e8c724..824cad7c2 100644
--- a/model/metadata/map_mediafile.go
+++ b/model/metadata/map_mediafile.go
@@ -65,6 +65,7 @@ func (md Metadata) ToMediaFile(libID int, folderID string) model.MediaFile {
mf.SampleRate = md.AudioProperties().SampleRate
mf.BitDepth = md.AudioProperties().BitDepth
mf.Channels = md.AudioProperties().Channels
+ mf.Codec = md.AudioProperties().Codec
mf.Path = md.FilePath()
mf.Suffix = md.Suffix()
mf.Size = md.Size()
diff --git a/model/metadata/map_mediafile_test.go b/model/metadata/map_mediafile_test.go
index ddda39bc2..e3adf3fae 100644
--- a/model/metadata/map_mediafile_test.go
+++ b/model/metadata/map_mediafile_test.go
@@ -75,6 +75,23 @@ var _ = Describe("ToMediaFile", func() {
Expect(mf.OriginalYear).To(Equal(1966))
Expect(mf.ReleaseYear).To(Equal(2014))
})
+ DescribeTable("legacyReleaseDate (TaggedLikePicard old behavior)",
+ func(recordingDate, originalDate, releaseDate, expected string) {
+ mf := toMediaFile(model.RawTags{
+ "DATE": {recordingDate},
+ "ORIGINALDATE": {originalDate},
+ "RELEASEDATE": {releaseDate},
+ })
+
+ Expect(mf.ReleaseDate).To(Equal(expected))
+ },
+ Entry("regular mapping", "2020-05-15", "2019-02-10", "2021-01-01", "2021-01-01"),
+ Entry("legacy mapping", "2020-05-15", "2019-02-10", "", "2020-05-15"),
+ Entry("legacy mapping, originalYear < year", "2018-05-15", "2019-02-10", "2021-01-01", "2021-01-01"),
+ Entry("legacy mapping, originalYear empty", "2020-05-15", "", "2021-01-01", "2021-01-01"),
+ Entry("legacy mapping, releaseYear", "2020-05-15", "2019-02-10", "2021-01-01", "2021-01-01"),
+ Entry("legacy mapping, same dates", "2020-05-15", "2020-05-15", "", "2020-05-15"),
+ )
})
Describe("Lyrics", func() {
diff --git a/model/metadata/metadata.go b/model/metadata/metadata.go
index 1372d0034..48928f989 100644
--- a/model/metadata/metadata.go
+++ b/model/metadata/metadata.go
@@ -35,6 +35,7 @@ type AudioProperties struct {
BitDepth int
SampleRate int
Channels int
+ Codec string
}
type Date string
@@ -250,7 +251,15 @@ func processPairMapping(name model.TagName, mapping model.TagConf, lowered model
id3Base := parseID3Pairs(name, lowered)
if len(aliasValues) > 0 {
- id3Base = append(id3Base, parseVorbisPairs(aliasValues)...)
+ // For lyrics, don't use parseVorbisPairs as parentheses in lyrics content
+ // should not be interpreted as language keys (e.g. "(intro)" is not a language)
+ if name == model.TagLyrics {
+ for _, v := range aliasValues {
+ id3Base = append(id3Base, NewPair("xxx", v))
+ }
+ } else {
+ id3Base = append(id3Base, parseVorbisPairs(aliasValues)...)
+ }
}
return id3Base
}
@@ -260,8 +269,8 @@ func parseID3Pairs(name model.TagName, lowered model.Tags) []string {
prefix := string(name) + ":"
for tagKey, tagValues := range lowered {
keyStr := string(tagKey)
- if strings.HasPrefix(keyStr, prefix) {
- keyPart := strings.TrimPrefix(keyStr, prefix)
+ if after, ok := strings.CutPrefix(keyStr, prefix); ok {
+ keyPart := after
if keyPart == string(name) {
keyPart = ""
}
diff --git a/model/metadata/metadata_test.go b/model/metadata/metadata_test.go
index 82afd8657..663e306c4 100644
--- a/model/metadata/metadata_test.go
+++ b/model/metadata/metadata_test.go
@@ -246,6 +246,18 @@ var _ = Describe("Metadata", func() {
metadata.NewPair("eng", "Lyrics"),
))
})
+
+ It("should preserve lyrics starting with parentheses from alias tags", func() {
+ props.Tags = model.RawTags{
+ "LYRICS": {"(line one)\nline two\nline three"},
+ }
+ md = metadata.New(filePath, props)
+
+ Expect(md.All()).To(HaveKey(model.TagLyrics))
+ Expect(md.Strings(model.TagLyrics)).To(ContainElements(
+ metadata.NewPair("xxx", "(line one)\nline two\nline three"),
+ ))
+ })
})
Describe("ReplayGain", func() {
diff --git a/model/metadata/persistent_ids.go b/model/metadata/persistent_ids.go
index b45882946..70dfe0532 100644
--- a/model/metadata/persistent_ids.go
+++ b/model/metadata/persistent_ids.go
@@ -8,6 +8,7 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
+ "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/id"
"github.com/navidrome/navidrome/utils"
@@ -26,10 +27,14 @@ type getPIDFunc = func(mf model.MediaFile, md Metadata, spec string, prependLibI
func createGetPID(hash hashFunc) getPIDFunc {
var getPID getPIDFunc
- getAttr := func(mf model.MediaFile, md Metadata, attr string, prependLibId bool) string {
+ getAttr := func(mf model.MediaFile, md Metadata, attr string, prependLibId bool, spec string) string {
attr = strings.TrimSpace(strings.ToLower(attr))
switch attr {
case "albumid":
+ if spec == conf.Server.PID.Album {
+ log.Error("Recursive PID definition detected, ignoring `albumid`", "spec", spec)
+ return ""
+ }
return getPID(mf, md, conf.Server.PID.Album, prependLibId)
case "folder":
return filepath.Dir(mf.Path)
@@ -44,12 +49,12 @@ func createGetPID(hash hashFunc) getPIDFunc {
}
getPID = func(mf model.MediaFile, md Metadata, spec string, prependLibId bool) string {
pid := ""
- fields := strings.Split(spec, "|")
- for _, field := range fields {
+ fields := strings.SplitSeq(spec, "|")
+ for field := range fields {
attributes := strings.Split(field, ",")
hasValue := false
values := slice.Map(attributes, func(attr string) string {
- v := getAttr(mf, md, attr, prependLibId)
+ v := getAttr(mf, md, attr, prependLibId, spec)
if v != "" {
hasValue = true
}
diff --git a/model/metadata/persistent_ids_test.go b/model/metadata/persistent_ids_test.go
index 7ae0c91f7..9f1dacbd4 100644
--- a/model/metadata/persistent_ids_test.go
+++ b/model/metadata/persistent_ids_test.go
@@ -65,7 +65,7 @@ var _ = Describe("getPID", func() {
Context("calculated attributes", func() {
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
- conf.Server.PID.Album = "musicbrainz_albumid|albumartistid,album,version,releasedate"
+ conf.Server.PID.Album = "musicbrainz_albumid|albumartistid,album,albumversion,releasedate"
})
When("field is title", func() {
It("should return the pid", func() {
@@ -88,13 +88,13 @@ var _ = Describe("getPID", func() {
It("should return the pid", func() {
spec := "albumid|title"
md.tags = map[model.TagName][]string{
- "title": {"title"},
- "album": {"album name"},
- "version": {"version"},
- "releasedate": {"2021-01-01"},
+ "title": {"title"},
+ "album": {"album name"},
+ "albumversion": {"deluxe edition"},
+ "releasedate": {"2021-01-01"},
}
mf.AlbumArtist = "Album Artist"
- Expect(getPID(mf, md, spec, false)).To(Equal("(((album artist)\\album name\\version\\2021-01-01))"))
+ Expect(getPID(mf, md, spec, false)).To(Equal("(((album artist)\\album name\\deluxe edition\\2021-01-01))"))
})
})
When("field is albumartistid", func() {
@@ -114,6 +114,24 @@ var _ = Describe("getPID", func() {
Expect(getPID(mf, md, spec, false)).To(Equal("(album name)"))
})
})
+
+ When("albumid configuration refers to albumid recursively", func() {
+ It("should avoid infinite recursion", func() {
+ // Reproduce the issue from #4920
+ conf.Server.PID.Album = "albumid,album,albumversion,releasedate"
+ spec := conf.Server.PID.Album
+ md.tags = map[model.TagName][]string{
+ "album": {"Album Name"},
+ "albumversion": {"Version"},
+ "releasedate": {"2022"},
+ }
+ // Should not panic and return a valid PID ignoring the recursive "albumid"
+ Expect(func() {
+ pid := getPID(mf, md, spec, false)
+ Expect(pid).To(Equal("(\\album name\\Version\\2022)"))
+ }).To(Not(Panic()))
+ })
+ })
})
Context("edge cases", func() {
diff --git a/model/playlist.go b/model/playlist.go
index a87019ed5..e2f93993d 100644
--- a/model/playlist.go
+++ b/model/playlist.go
@@ -5,24 +5,27 @@ import (
"strconv"
"time"
+ "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/model/criteria"
)
type Playlist struct {
- ID string `structs:"id" json:"id"`
- Name string `structs:"name" json:"name"`
- Comment string `structs:"comment" json:"comment"`
- Duration float32 `structs:"duration" json:"duration"`
- Size int64 `structs:"size" json:"size"`
- SongCount int `structs:"song_count" json:"songCount"`
- OwnerName string `structs:"-" json:"ownerName"`
- OwnerID string `structs:"owner_id" json:"ownerId"`
- Public bool `structs:"public" json:"public"`
- Tracks PlaylistTracks `structs:"-" json:"tracks,omitempty"`
- Path string `structs:"path" json:"path"`
- Sync bool `structs:"sync" json:"sync"`
- CreatedAt time.Time `structs:"created_at" json:"createdAt"`
- UpdatedAt time.Time `structs:"updated_at" json:"updatedAt"`
+ ID string `structs:"id" json:"id"`
+ Name string `structs:"name" json:"name"`
+ Comment string `structs:"comment" json:"comment"`
+ Duration float32 `structs:"duration" json:"duration"`
+ Size int64 `structs:"size" json:"size"`
+ SongCount int `structs:"song_count" json:"songCount"`
+ OwnerName string `structs:"-" json:"ownerName"`
+ OwnerID string `structs:"owner_id" json:"ownerId"`
+ Public bool `structs:"public" json:"public"`
+ Tracks PlaylistTracks `structs:"-" json:"tracks,omitempty"`
+ Path string `structs:"path" json:"path"`
+ Sync bool `structs:"sync" json:"sync"`
+ UploadedImage string `structs:"uploaded_image" json:"uploadedImage"`
+ ExternalImageURL string `structs:"external_image_url" json:"externalImageUrl,omitempty"`
+ CreatedAt time.Time `structs:"created_at" json:"createdAt"`
+ UpdatedAt time.Time `structs:"updated_at" json:"updatedAt"`
// SmartPlaylist attributes
Rules *criteria.Criteria `structs:"rules" json:"rules"`
@@ -106,6 +109,14 @@ func (pls Playlist) CoverArtID() ArtworkID {
return artworkIDFromPlaylist(pls)
}
+// UploadedImagePath returns the absolute filesystem path for a manually uploaded
+// playlist cover image. Returns empty string if no image has been uploaded.
+// This does NOT cover sidecar images or external URLs — those are resolved
+// by the artwork reader's fallback chain.
+func (pls Playlist) UploadedImagePath() string {
+ return UploadedImagePath(consts.EntityPlaylist, pls.UploadedImage)
+}
+
type Playlists []Playlist
type PlaylistRepository interface {
diff --git a/model/plugin.go b/model/plugin.go
new file mode 100644
index 000000000..18d66e305
--- /dev/null
+++ b/model/plugin.go
@@ -0,0 +1,32 @@
+package model
+
+import "time"
+
+type Plugin struct {
+ ID string `structs:"id" json:"id"`
+ Path string `structs:"path" json:"path"`
+ Manifest string `structs:"manifest" json:"manifest"`
+ Config string `structs:"config" json:"config,omitempty"`
+ Users string `structs:"users" json:"users,omitempty"`
+ AllUsers bool `structs:"all_users" json:"allUsers,omitempty"`
+ Libraries string `structs:"libraries" json:"libraries,omitempty"`
+ AllLibraries bool `structs:"all_libraries" json:"allLibraries,omitempty"`
+ AllowWriteAccess bool `structs:"allow_write_access" json:"allowWriteAccess,omitempty"`
+ Enabled bool `structs:"enabled" json:"enabled"`
+ LastError string `structs:"last_error" json:"lastError,omitempty"`
+ SHA256 string `structs:"sha256" json:"sha256"`
+ CreatedAt time.Time `structs:"created_at" json:"createdAt"`
+ UpdatedAt time.Time `structs:"updated_at" json:"updatedAt"`
+}
+
+type Plugins []Plugin
+
+type PluginRepository interface {
+ ResourceRepository
+ ClearErrors() error
+ CountAll(options ...QueryOptions) (int64, error)
+ Delete(id string) error
+ Get(id string) (*Plugin, error)
+ GetAll(options ...QueryOptions) (Plugins, error)
+ Put(p *Plugin) error
+}
diff --git a/model/radio.go b/model/radio.go
index 567d32e44..86f27c24c 100644
--- a/model/radio.go
+++ b/model/radio.go
@@ -1,14 +1,27 @@
package model
-import "time"
+import (
+ "time"
+
+ "github.com/navidrome/navidrome/consts"
+)
type Radio struct {
- ID string `structs:"id" json:"id"`
- StreamUrl string `structs:"stream_url" json:"streamUrl"`
- Name string `structs:"name" json:"name"`
- HomePageUrl string `structs:"home_page_url" json:"homePageUrl"`
- CreatedAt time.Time `structs:"created_at" json:"createdAt"`
- UpdatedAt time.Time `structs:"updated_at" json:"updatedAt"`
+ ID string `structs:"id" json:"id"`
+ StreamUrl string `structs:"stream_url" json:"streamUrl"`
+ Name string `structs:"name" json:"name"`
+ HomePageUrl string `structs:"home_page_url" json:"homePageUrl"`
+ UploadedImage string `structs:"uploaded_image" json:"uploadedImage,omitempty"`
+ CreatedAt time.Time `structs:"created_at" json:"createdAt"`
+ UpdatedAt time.Time `structs:"updated_at" json:"updatedAt"`
+}
+
+func (r Radio) CoverArtID() ArtworkID {
+ return artworkIDFromRadio(r)
+}
+
+func (r Radio) UploadedImagePath() string {
+ return UploadedImagePath(consts.EntityRadio, r.UploadedImage)
}
type Radios []Radio
@@ -19,5 +32,5 @@ type RadioRepository interface {
Delete(id string) error
Get(id string) (*Radio, error)
GetAll(options ...QueryOptions) (Radios, error)
- Put(u *Radio) error
+ Put(u *Radio, colsToUpdate ...string) error
}
diff --git a/model/radio_test.go b/model/radio_test.go
new file mode 100644
index 000000000..dc421454e
--- /dev/null
+++ b/model/radio_test.go
@@ -0,0 +1,42 @@
+package model_test
+
+import (
+ "path/filepath"
+ "time"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/model"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Radio", func() {
+ Describe("CoverArtID", func() {
+ It("returns a radio artwork ID", func() {
+ now := time.Now()
+ r := model.Radio{ID: "rd-1", UpdatedAt: now}
+ artID := r.CoverArtID()
+ Expect(artID.Kind).To(Equal(model.KindRadioArtwork))
+ Expect(artID.ID).To(Equal("rd-1"))
+ Expect(artID.LastUpdate).To(Equal(now))
+ })
+ })
+
+ Describe("UploadedImagePath", func() {
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.DataFolder = "/data"
+ })
+
+ It("returns empty string when no image uploaded", func() {
+ r := model.Radio{ID: "rd-1"}
+ Expect(r.UploadedImagePath()).To(BeEmpty())
+ })
+
+ It("returns full path when image is set", func() {
+ r := model.Radio{ID: "rd-1", UploadedImage: "rd-1_test.jpg"}
+ Expect(r.UploadedImagePath()).To(Equal(filepath.Join("/data", "artwork", "radio", "rd-1_test.jpg")))
+ })
+ })
+})
diff --git a/model/scanner.go b/model/scanner.go
new file mode 100644
index 000000000..54f81037c
--- /dev/null
+++ b/model/scanner.go
@@ -0,0 +1,81 @@
+package model
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// ScanTarget represents a specific folder within a library to be scanned.
+// NOTE: This struct is used as a map key, so it should only contain comparable types.
+type ScanTarget struct {
+ LibraryID int
+ FolderPath string // Relative path within the library, or "" for entire library
+}
+
+func (st ScanTarget) String() string {
+ return fmt.Sprintf("%d:%s", st.LibraryID, st.FolderPath)
+}
+
+// ScannerStatus holds information about the current scan status
+type ScannerStatus struct {
+ Scanning bool
+ LastScan time.Time
+ Count uint32
+ FolderCount uint32
+ LastError string
+ ScanType string
+ ElapsedTime time.Duration
+}
+
+type Scanner interface {
+ // ScanAll starts a scan of all libraries. This is a blocking operation.
+ ScanAll(ctx context.Context, fullScan bool) (warnings []string, err error)
+ // ScanFolders scans specific library/folder pairs, recursing into subdirectories.
+ // If targets is nil, it scans all libraries. This is a blocking operation.
+ ScanFolders(ctx context.Context, fullScan bool, targets []ScanTarget) (warnings []string, err error)
+ Status(context.Context) (*ScannerStatus, error)
+}
+
+// ParseTargets parses scan targets strings into ScanTarget structs.
+// Example: []string{"1:Music/Rock", "2:Classical"}
+func ParseTargets(libFolders []string) ([]ScanTarget, error) {
+ targets := make([]ScanTarget, 0, len(libFolders))
+
+ for _, part := range libFolders {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ continue
+ }
+
+ // Split by the first colon
+ before, after, ok := strings.Cut(part, ":")
+ if !ok {
+ return nil, fmt.Errorf("invalid target format: %q (expected libraryID:folderPath)", part)
+ }
+
+ libIDStr := before
+ folderPath := after
+
+ libID, err := strconv.Atoi(libIDStr)
+ if err != nil {
+ return nil, fmt.Errorf("invalid library ID %q: %w", libIDStr, err)
+ }
+ if libID <= 0 {
+ return nil, fmt.Errorf("invalid library ID %q", libIDStr)
+ }
+
+ targets = append(targets, ScanTarget{
+ LibraryID: libID,
+ FolderPath: folderPath,
+ })
+ }
+
+ if len(targets) == 0 {
+ return nil, fmt.Errorf("no valid targets found")
+ }
+
+ return targets, nil
+}
diff --git a/model/scanner_test.go b/model/scanner_test.go
new file mode 100644
index 000000000..8ca0c53fa
--- /dev/null
+++ b/model/scanner_test.go
@@ -0,0 +1,89 @@
+package model_test
+
+import (
+ "github.com/navidrome/navidrome/model"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("ParseTargets", func() {
+ It("parses multiple entries in slice", func() {
+ targets, err := model.ParseTargets([]string{"1:Music/Rock", "1:Music/Jazz", "2:Classical"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(3))
+ Expect(targets[0].LibraryID).To(Equal(1))
+ Expect(targets[0].FolderPath).To(Equal("Music/Rock"))
+ Expect(targets[1].LibraryID).To(Equal(1))
+ Expect(targets[1].FolderPath).To(Equal("Music/Jazz"))
+ Expect(targets[2].LibraryID).To(Equal(2))
+ Expect(targets[2].FolderPath).To(Equal("Classical"))
+ })
+
+ It("handles empty folder paths", func() {
+ targets, err := model.ParseTargets([]string{"1:", "2:"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(2))
+ Expect(targets[0].FolderPath).To(Equal(""))
+ Expect(targets[1].FolderPath).To(Equal(""))
+ })
+
+ It("trims whitespace from entries", func() {
+ targets, err := model.ParseTargets([]string{" 1:Music/Rock", " 2:Classical "})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(2))
+ Expect(targets[0].LibraryID).To(Equal(1))
+ Expect(targets[0].FolderPath).To(Equal("Music/Rock"))
+ Expect(targets[1].LibraryID).To(Equal(2))
+ Expect(targets[1].FolderPath).To(Equal("Classical"))
+ })
+
+ It("skips empty strings", func() {
+ targets, err := model.ParseTargets([]string{"1:Music/Rock", "", "2:Classical"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(2))
+ })
+
+ It("handles paths with colons", func() {
+ targets, err := model.ParseTargets([]string{"1:C:/Music/Rock", "2:/path:with:colons"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(targets).To(HaveLen(2))
+ Expect(targets[0].FolderPath).To(Equal("C:/Music/Rock"))
+ Expect(targets[1].FolderPath).To(Equal("/path:with:colons"))
+ })
+
+ It("returns error for invalid format without colon", func() {
+ _, err := model.ParseTargets([]string{"1Music/Rock"})
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("invalid target format"))
+ })
+
+ It("returns error for non-numeric library ID", func() {
+ _, err := model.ParseTargets([]string{"abc:Music/Rock"})
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("invalid library ID"))
+ })
+
+ It("returns error for negative library ID", func() {
+ _, err := model.ParseTargets([]string{"-1:Music/Rock"})
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("invalid library ID"))
+ })
+
+ It("returns error for zero library ID", func() {
+ _, err := model.ParseTargets([]string{"0:Music/Rock"})
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("invalid library ID"))
+ })
+
+ It("returns error for empty input", func() {
+ _, err := model.ParseTargets([]string{})
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("no valid targets found"))
+ })
+
+ It("returns error for all empty strings", func() {
+ _, err := model.ParseTargets([]string{"", " ", ""})
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("no valid targets found"))
+ })
+})
diff --git a/model/scrobble.go b/model/scrobble.go
new file mode 100644
index 000000000..e1567abc3
--- /dev/null
+++ b/model/scrobble.go
@@ -0,0 +1,13 @@
+package model
+
+import "time"
+
+type Scrobble struct {
+ MediaFileID string
+ UserID string
+ SubmissionTime time.Time
+}
+
+type ScrobbleRepository interface {
+ RecordScrobble(mediaFileID string, submissionTime time.Time) error
+}
diff --git a/model/searchable.go b/model/searchable.go
index 631a11726..a64a0171c 100644
--- a/model/searchable.go
+++ b/model/searchable.go
@@ -1,5 +1,5 @@
package model
type SearchableRepository[T any] interface {
- Search(q string, offset, size int, options ...QueryOptions) (T, error)
+ Search(q string, options ...QueryOptions) (T, error)
}
diff --git a/model/share.go b/model/share.go
index acb5fb428..ce0846d60 100644
--- a/model/share.go
+++ b/model/share.go
@@ -22,8 +22,8 @@ type Share struct {
Format string `structs:"format" json:"format,omitempty"`
MaxBitRate int `structs:"max_bit_rate" json:"maxBitRate,omitempty"`
VisitCount int `structs:"visit_count" json:"visitCount,omitempty"`
- CreatedAt time.Time `structs:"created_at" json:"createdAt,omitempty"`
- UpdatedAt time.Time `structs:"updated_at" json:"updatedAt,omitempty"`
+ CreatedAt time.Time `structs:"created_at" json:"createdAt"`
+ UpdatedAt time.Time `structs:"updated_at" json:"updatedAt"`
Tracks MediaFiles `structs:"-" json:"tracks,omitempty"`
Albums Albums `structs:"-" json:"albums,omitempty"`
URL string `structs:"-" json:"-"`
diff --git a/model/tag.go b/model/tag.go
index 674f688ca..1f6b24d21 100644
--- a/model/tag.go
+++ b/model/tag.go
@@ -144,10 +144,8 @@ func (t Tags) Merge(tags Tags) {
}
func (t Tags) Add(name TagName, v string) {
- for _, existing := range t[name] {
- if existing == v {
- return
- }
+ if slices.Contains(t[name], v) {
+ return
}
t[name] = append(t[name], v)
}
diff --git a/model/user.go b/model/user.go
index aabedc096..1c8541ccf 100644
--- a/model/user.go
+++ b/model/user.go
@@ -22,7 +22,7 @@ type User struct {
Password string `structs:"-" json:"-"`
// This is used to set or change a password when calling Put. If it is empty, the password is not changed.
// It is received from the UI with the name "password"
- NewPassword string `structs:"password,omitempty" json:"password,omitempty"`
+ NewPassword string `structs:"password,omitempty" json:"password,omitempty"` //nolint:gosec
// If changing the password, this is also required
CurrentPassword string `structs:"current_password,omitempty" json:"currentPassword,omitempty"`
}
@@ -42,8 +42,11 @@ func (u User) HasLibraryAccess(libraryID int) bool {
type Users []User
type UserRepository interface {
+ ResourceRepository
CountAll(...QueryOptions) (int64, error)
+ Delete(id string) error
Get(id string) (*User, error)
+ GetAll(options ...QueryOptions) (Users, error)
Put(*User) error
UpdateLastLoginAt(id string) error
UpdateLastAccessAt(id string) error
diff --git a/persistence/album_repository.go b/persistence/album_repository.go
index 6f9bb3b48..c51a5beb1 100644
--- a/persistence/album_repository.go
+++ b/persistence/album_repository.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "iter"
"maps"
"slices"
"strings"
@@ -12,7 +13,6 @@ import (
. "github.com/Masterminds/squirrel"
"github.com/deluan/rest"
- "github.com/google/uuid"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
@@ -62,11 +62,14 @@ func (a *dbAlbum) PostScan() error {
func (a *dbAlbum) PostMapArgs(args map[string]any) error {
fullText := []string{a.Name, a.SortAlbumName, a.AlbumArtist}
- fullText = append(fullText, a.Album.Participants.AllNames()...)
+ participantNames := a.Album.Participants.AllNames()
+ fullText = append(fullText, participantNames...)
fullText = append(fullText, slices.Collect(maps.Values(a.Album.Discs))...)
fullText = append(fullText, a.Album.Tags[model.TagAlbumVersion]...)
fullText = append(fullText, a.Album.Tags[model.TagCatalogNumber]...)
args["full_text"] = formatFullText(fullText...)
+ args["search_participants"] = strings.Join(participantNames, " ")
+ args["search_normalized"] = normalizeForFTS(a.Name, a.AlbumArtist)
args["tags"] = marshalTags(a.Album.Tags)
args["participants"] = marshalParticipants(a.Album.Participants)
@@ -106,6 +109,7 @@ func NewAlbumRepository(ctx context.Context, db dbx.Builder) model.AlbumReposito
"random": "random",
"recently_added": recentlyAddedSort(),
"starred_at": "starred, starred_at",
+ "rated_at": "rating, rated_at",
})
return r
}
@@ -118,8 +122,8 @@ var albumFilters = sync.OnceValue(func() map[string]filterFunc {
"artist_id": artistFilter,
"year": yearFilter,
"recently_played": recentlyPlayedFilter,
- "starred": booleanFilter,
- "has_rating": hasRatingFilter,
+ "starred": annotationBoolFilter("starred"),
+ "has_rating": annotationBoolFilter("rating"),
"missing": booleanFilter,
"genre_id": tagIDFilter,
"role_total_id": allRolesFilter,
@@ -139,20 +143,16 @@ var albumFilters = sync.OnceValue(func() map[string]filterFunc {
func recentlyAddedSort() string {
if conf.Server.RecentlyAddedByModTime {
- return "updated_at"
+ return "datetime(album.updated_at)"
}
- return "created_at"
+ return "datetime(album.created_at)"
}
-func recentlyPlayedFilter(string, interface{}) Sqlizer {
+func recentlyPlayedFilter(string, any) Sqlizer {
return Gt{"play_count": 0}
}
-func hasRatingFilter(string, interface{}) Sqlizer {
- return Gt{"rating": 0}
-}
-
-func yearFilter(_ string, value interface{}) Sqlizer {
+func yearFilter(_ string, value any) Sqlizer {
return Or{
And{
Gt{"min_year": 0},
@@ -163,14 +163,14 @@ func yearFilter(_ string, value interface{}) Sqlizer {
}
}
-func artistFilter(_ string, value interface{}) Sqlizer {
+func artistFilter(_ string, value any) Sqlizer {
return Or{
Exists("json_tree(participants, '$.albumartist')", Eq{"value": value}),
Exists("json_tree(participants, '$.artist')", Eq{"value": value}),
}
}
-func artistRoleFilter(name string, value interface{}) Sqlizer {
+func artistRoleFilter(name string, value any) Sqlizer {
roleName := strings.TrimSuffix(strings.TrimPrefix(name, "role_"), "_id")
// Check if the role name is valid. If not, return an invalid filter
@@ -180,7 +180,7 @@ func artistRoleFilter(name string, value interface{}) Sqlizer {
return Exists(fmt.Sprintf("json_tree(participants, '$.%s')", roleName), Eq{"value": value})
}
-func allRolesFilter(_ string, value interface{}) Sqlizer {
+func allRolesFilter(_ string, value any) Sqlizer {
return Like{"participants": fmt.Sprintf(`%%"%s"%%`, value)}
}
@@ -203,12 +203,11 @@ func (r *albumRepository) Put(al *model.Album) error {
}
al.ID = id
if len(al.Participants) > 0 {
- err = r.updateParticipants(al.ID, al.Participants)
- if err != nil {
+ if err = r.updateParticipants(al.ID, al.Participants); err != nil {
return err
}
}
- return err
+ return nil
}
// TODO Move external metadata to a separated table
@@ -242,7 +241,7 @@ func (r *albumRepository) GetAll(options ...model.QueryOptions) (model.Albums, e
if err != nil {
return nil, err
}
- return res.toModels(), err
+ return res.toModels(), nil
}
func (r *albumRepository) CopyAttributes(fromID, toID string, columns ...string) error {
@@ -251,7 +250,7 @@ func (r *albumRepository) CopyAttributes(fromID, toID string, columns ...string)
if err != nil {
return fmt.Errorf("getting album to copy fields from: %w", err)
}
- to := make(map[string]interface{})
+ to := make(map[string]any)
for _, col := range columns {
to[col] = from[col]
}
@@ -303,17 +302,21 @@ func (r *albumRepository) GetTouchedAlbums(libID int) (model.AlbumCursor, error)
if err != nil {
return nil, err
}
+ return wrapAlbumCursor(cursor), nil
+}
+
+func wrapAlbumCursor(cursor iter.Seq2[dbAlbum, error]) model.AlbumCursor {
return func(yield func(model.Album, error) bool) {
for a, err := range cursor {
if a.Album == nil {
- yield(model.Album{}, fmt.Errorf("unexpected nil album: %v", a))
+ yield(model.Album{}, fmt.Errorf("unexpected nil album (%v): %w", a, err))
return
}
if !yield(*a.Album, err) || err != nil {
return
}
}
- }, nil
+ }
}
// RefreshPlayCounts updates the play count and last play date annotations for all albums, based
@@ -337,8 +340,12 @@ on conflict (user_id, item_id, item_type) do update
return r.executeSQL(query)
}
-func (r *albumRepository) purgeEmpty() error {
+func (r *albumRepository) purgeEmpty(libraryIDs ...int) error {
del := Delete(r.tableName).Where("id not in (select distinct(album_id) from media_file)")
+ // If libraryIDs are specified, only purge albums from those libraries
+ if len(libraryIDs) > 0 {
+ del = del.Where(Eq{"library_id": libraryIDs})
+ }
c, err := r.executeSQL(del)
if err != nil {
return fmt.Errorf("purging empty albums: %w", err)
@@ -349,18 +356,21 @@ func (r *albumRepository) purgeEmpty() error {
return nil
}
-func (r *albumRepository) Search(q string, offset int, size int, options ...model.QueryOptions) (model.Albums, error) {
+var albumSearchConfig = searchConfig{
+ NaturalOrder: "album.rowid",
+ OrderBy: []string{"name"},
+ MBIDFields: []string{"mbz_album_id", "mbz_release_group_id"},
+}
+
+func (r *albumRepository) Search(q string, options ...model.QueryOptions) (model.Albums, error) {
+ var opts model.QueryOptions
+ if len(options) > 0 {
+ opts = options[0]
+ }
var res dbAlbums
- if uuid.Validate(q) == nil {
- err := r.searchByMBID(r.selectAlbum(options...), q, []string{"mbz_album_id", "mbz_release_group_id"}, &res)
- if err != nil {
- return nil, fmt.Errorf("searching album by MBID %q: %w", q, err)
- }
- } else {
- err := r.doSearch(r.selectAlbum(options...), q, offset, size, &res, "album.rowid", "name")
- if err != nil {
- return nil, fmt.Errorf("searching album by query %q: %w", q, err)
- }
+ err := r.doSearch(r.selectAlbum(options...), q, &res, albumSearchConfig, opts)
+ if err != nil {
+ return nil, fmt.Errorf("searching album %q: %w", q, err)
}
return res.toModels(), nil
}
@@ -369,11 +379,11 @@ func (r *albumRepository) Count(options ...rest.QueryOptions) (int64, error) {
return r.CountAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *albumRepository) Read(id string) (interface{}, error) {
+func (r *albumRepository) Read(id string) (any, error) {
return r.Get(id)
}
-func (r *albumRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *albumRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
return r.GetAll(r.parseRestOptions(r.ctx, options...))
}
@@ -381,7 +391,7 @@ func (r *albumRepository) EntityName() string {
return "album"
}
-func (r *albumRepository) NewInstance() interface{} {
+func (r *albumRepository) NewInstance() any {
return &model.Album{}
}
diff --git a/persistence/album_repository_test.go b/persistence/album_repository_test.go
index 4be89bcb8..2792cec97 100644
--- a/persistence/album_repository_test.go
+++ b/persistence/album_repository_test.go
@@ -1,10 +1,12 @@
package persistence
import (
+ "errors"
"fmt"
"time"
"github.com/Masterminds/squirrel"
+ "github.com/deluan/rest"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/model"
@@ -55,15 +57,23 @@ var _ = Describe("AlbumRepository", func() {
It("returns all records sorted", func() {
Expect(GetAll(model.QueryOptions{Sort: "name"})).To(Equal(model.Albums{
albumAbbeyRoad,
+ albumWithVersion,
+ albumCJK,
+ albumMultiDisc,
albumRadioactivity,
albumSgtPeppers,
+ albumPunctuation,
}))
})
It("returns all records sorted desc", func() {
Expect(GetAll(model.QueryOptions{Sort: "name", Order: "desc"})).To(Equal(model.Albums{
+ albumPunctuation,
albumSgtPeppers,
albumRadioactivity,
+ albumMultiDisc,
+ albumCJK,
+ albumWithVersion,
albumAbbeyRoad,
}))
})
@@ -75,6 +85,129 @@ var _ = Describe("AlbumRepository", func() {
})
})
+ Describe("recently_added sort", func() {
+ It("sorts correctly regardless of timestamp format (T-format vs space-format)", func() {
+ // Both timestamps share the same date prefix "2024-01-15" so the T vs space
+ // character at position 10 determines sort order in raw string comparison.
+ // Without normalization, 'T' (ASCII 84) > ' ' (ASCII 32) makes the older
+ // T-format timestamp sort AFTER the newer space-format one.
+
+ // Older album: morning of Jan 15, stored in T-format
+ olderAlbum := &model.Album{LibraryID: 1, ID: "ts-older", Name: "Older Album"}
+ Expect(albumRepo.Put(olderAlbum)).To(Succeed())
+ _, err := albumRepo.executeSQL(squirrel.Update("album").
+ Set("created_at", "2024-01-15T08:00:00Z").
+ Where(squirrel.Eq{"id": "ts-older"}))
+ Expect(err).ToNot(HaveOccurred())
+
+ // Newer album: evening of Jan 15, stored in space-format
+ newerAlbum := &model.Album{LibraryID: 1, ID: "ts-newer", Name: "Newer Album"}
+ Expect(albumRepo.Put(newerAlbum)).To(Succeed())
+ _, err = albumRepo.executeSQL(squirrel.Update("album").
+ Set("created_at", "2024-01-15 20:00:00+00:00").
+ Where(squirrel.Eq{"id": "ts-newer"}))
+ Expect(err).ToNot(HaveOccurred())
+
+ albums, err := albumRepo.GetAll(model.QueryOptions{Sort: "recently_added", Order: "desc"})
+ Expect(err).ToNot(HaveOccurred())
+
+ // Find positions of our test albums
+ olderIdx, newerIdx := -1, -1
+ for i, a := range albums {
+ switch a.ID {
+ case "ts-older":
+ olderIdx = i
+ case "ts-newer":
+ newerIdx = i
+ }
+ }
+ Expect(olderIdx).To(BeNumerically(">=", 0), "older album not found in results")
+ Expect(newerIdx).To(BeNumerically(">=", 0), "newer album not found in results")
+ // Newer album (evening, space-format) should come before older album (morning, T-format) in desc order
+ Expect(newerIdx).To(BeNumerically("<", olderIdx),
+ "Newer album (20:00 space-format) should sort before older album (08:00 T-format) in desc order")
+
+ // Clean up
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": []string{"ts-older", "ts-newer"}}))
+ })
+ })
+
+ Context("Filters", func() {
+ var albumWithoutAnnotation model.Album
+
+ BeforeEach(func() {
+ // Create album without any annotation (no star, no rating)
+ albumWithoutAnnotation = model.Album{ID: "no-annotation-album", Name: "No Annotation", LibraryID: 1}
+ Expect(albumRepo.Put(&albumWithoutAnnotation)).To(Succeed())
+ })
+
+ AfterEach(func() {
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": albumWithoutAnnotation.ID}))
+ })
+
+ Describe("starred", func() {
+ It("false includes items without annotations", func() {
+ res, err := albumRepo.ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"starred": "false"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ albums := res.(model.Albums)
+
+ var found bool
+ for _, a := range albums {
+ if a.ID == albumWithoutAnnotation.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "Album without annotation should be included in starred=false filter")
+ })
+
+ It("true excludes items without annotations", func() {
+ res, err := albumRepo.ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"starred": "true"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ albums := res.(model.Albums)
+
+ for _, a := range albums {
+ Expect(a.ID).ToNot(Equal(albumWithoutAnnotation.ID))
+ }
+ })
+ })
+
+ Describe("has_rating", func() {
+ It("false includes items without annotations", func() {
+ res, err := albumRepo.ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"has_rating": "false"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ albums := res.(model.Albums)
+
+ var found bool
+ for _, a := range albums {
+ if a.ID == albumWithoutAnnotation.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "Album without annotation should be included in has_rating=false filter")
+ })
+
+ It("true excludes items without annotations", func() {
+ res, err := albumRepo.ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"has_rating": "true"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ albums := res.(model.Albums)
+
+ for _, a := range albums {
+ Expect(a.ID).ToNot(Equal(albumWithoutAnnotation.ID))
+ }
+ })
+ })
+ })
+
Describe("Album.PlayCount", func() {
// Implementation is in withAnnotation() method
DescribeTable("normalizes play count when AlbumPlayCountMode is absolute",
@@ -83,7 +216,7 @@ var _ = Describe("AlbumRepository", func() {
newID := id.NewRandom()
Expect(albumRepo.Put(&model.Album{LibraryID: 1, ID: newID, Name: "name", SongCount: songCount})).To(Succeed())
- for i := 0; i < playCount; i++ {
+ for range playCount {
Expect(albumRepo.IncPlayCount(newID, time.Now())).To(Succeed())
}
@@ -106,7 +239,7 @@ var _ = Describe("AlbumRepository", func() {
newID := id.NewRandom()
Expect(albumRepo.Put(&model.Album{LibraryID: 1, ID: newID, Name: "name", SongCount: songCount})).To(Succeed())
- for i := 0; i < playCount; i++ {
+ for range playCount {
Expect(albumRepo.IncPlayCount(newID, time.Now())).To(Succeed())
}
@@ -124,6 +257,89 @@ var _ = Describe("AlbumRepository", func() {
)
})
+ Describe("Album.AverageRating", func() {
+ It("returns 0 when no ratings exist", func() {
+ newID := id.NewRandom()
+ Expect(albumRepo.Put(&model.Album{LibraryID: 1, ID: newID, Name: "no ratings album"})).To(Succeed())
+
+ album, err := albumRepo.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(album.AverageRating).To(Equal(0.0))
+
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": newID}))
+ })
+
+ It("returns the user's rating as average when only one user rated", func() {
+ newID := id.NewRandom()
+ Expect(albumRepo.Put(&model.Album{LibraryID: 1, ID: newID, Name: "single rating album"})).To(Succeed())
+ Expect(albumRepo.SetRating(4, newID)).To(Succeed())
+
+ album, err := albumRepo.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(album.AverageRating).To(Equal(4.0))
+
+ _, _ = albumRepo.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": newID}))
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": newID}))
+ })
+
+ It("calculates average across multiple users", func() {
+ newID := id.NewRandom()
+ Expect(albumRepo.Put(&model.Album{LibraryID: 1, ID: newID, Name: "multi rating album"})).To(Succeed())
+
+ Expect(albumRepo.SetRating(4, newID)).To(Succeed())
+
+ user2Ctx := request.WithUser(GinkgoT().Context(), regularUser)
+ user2Repo := NewAlbumRepository(user2Ctx, GetDBXBuilder()).(*albumRepository)
+ Expect(user2Repo.SetRating(5, newID)).To(Succeed())
+
+ album, err := albumRepo.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(album.AverageRating).To(Equal(4.5))
+
+ _, _ = albumRepo.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": newID}))
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": newID}))
+ })
+
+ It("excludes zero ratings from average calculation", func() {
+ newID := id.NewRandom()
+ Expect(albumRepo.Put(&model.Album{LibraryID: 1, ID: newID, Name: "zero rating excluded album"})).To(Succeed())
+ Expect(albumRepo.SetRating(3, newID)).To(Succeed())
+
+ user2Ctx := request.WithUser(GinkgoT().Context(), regularUser)
+ user2Repo := NewAlbumRepository(user2Ctx, GetDBXBuilder()).(*albumRepository)
+ Expect(user2Repo.SetRating(0, newID)).To(Succeed())
+
+ album, err := albumRepo.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(album.AverageRating).To(Equal(3.0))
+
+ _, _ = albumRepo.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": newID}))
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": newID}))
+ })
+
+ It("rounds to 2 decimal places", func() {
+ newID := id.NewRandom()
+ Expect(albumRepo.Put(&model.Album{LibraryID: 1, ID: newID, Name: "rounding test album"})).To(Succeed())
+
+ Expect(albumRepo.SetRating(5, newID)).To(Succeed())
+
+ user2Ctx := request.WithUser(GinkgoT().Context(), regularUser)
+ user2Repo := NewAlbumRepository(user2Ctx, GetDBXBuilder()).(*albumRepository)
+ Expect(user2Repo.SetRating(4, newID)).To(Succeed())
+
+ user3Ctx := request.WithUser(GinkgoT().Context(), thirdUser)
+ user3Repo := NewAlbumRepository(user3Ctx, GetDBXBuilder()).(*albumRepository)
+ Expect(user3Repo.SetRating(4, newID)).To(Succeed())
+
+ album, err := albumRepo.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(album.AverageRating).To(Equal(4.33)) // (5 + 4 + 4) / 3 = 4.333...
+
+ _, _ = albumRepo.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": newID}))
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": newID}))
+ })
+ })
+
Describe("dbAlbum mapping", func() {
var (
a model.Album
@@ -244,7 +460,7 @@ var _ = Describe("AlbumRepository", func() {
sql, args, err := sqlizer.ToSql()
Expect(err).ToNot(HaveOccurred())
Expect(sql).To(Equal(expectedSQL))
- Expect(args).To(Equal([]interface{}{artistID}))
+ Expect(args).To(Equal([]any{artistID}))
},
Entry("artist role", "role_artist_id", "123",
"exists (select 1 from json_tree(participants, '$.artist') where value = ?)"),
@@ -266,7 +482,7 @@ var _ = Describe("AlbumRepository", func() {
sql, args, err := sqlizer.ToSql()
Expect(err).ToNot(HaveOccurred())
Expect(sql).To(Equal(fmt.Sprintf("exists (select 1 from json_tree(participants, '$.%s') where value = ?)", roleName)))
- Expect(args).To(Equal([]interface{}{"test-id"}))
+ Expect(args).To(Equal([]any{"test-id"}))
}
})
@@ -510,6 +726,110 @@ var _ = Describe("AlbumRepository", func() {
// Clean up the test album created for this test
_, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": album.ID}))
})
+
+ It("removes stale role associations when artist role changes", func() {
+ // Regression test for issue #4242: Composers displayed in albumartist list
+ // This happens when an artist's role changes (e.g., was both albumartist and composer,
+ // now only composer) and the old role association isn't properly removed.
+
+ // Create an artist that will have changing roles
+ artist := &model.Artist{
+ ID: "role-change-artist-1",
+ Name: "Role Change Artist",
+ OrderArtistName: "role change artist",
+ }
+ err := createArtistWithLibrary(artistRepo, artist, 1)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Create album with artist as both albumartist and composer
+ album := &model.Album{
+ LibraryID: 1,
+ ID: "test-album-role-change",
+ Name: "Test Album Role Change",
+ AlbumArtistID: "role-change-artist-1",
+ AlbumArtist: "Role Change Artist",
+ Participants: model.Participants{
+ model.RoleAlbumArtist: {
+ {Artist: model.Artist{ID: "role-change-artist-1", Name: "Role Change Artist"}},
+ },
+ model.RoleComposer: {
+ {Artist: model.Artist{ID: "role-change-artist-1", Name: "Role Change Artist"}},
+ },
+ },
+ }
+
+ err = albumRepo.Put(album)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Verify initial state: artist has both albumartist and composer roles
+ expected := []albumArtistRecord{
+ {ArtistID: "role-change-artist-1", Role: "albumartist", SubRole: ""},
+ {ArtistID: "role-change-artist-1", Role: "composer", SubRole: ""},
+ }
+ verifyAlbumArtists(album.ID, expected)
+
+ // Now update album so artist is ONLY a composer (remove albumartist role)
+ album.Participants = model.Participants{
+ model.RoleComposer: {
+ {Artist: model.Artist{ID: "role-change-artist-1", Name: "Role Change Artist"}},
+ },
+ }
+
+ err = albumRepo.Put(album)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Verify that the albumartist role was removed - only composer should remain
+ // This is the key test: before the fix, the albumartist role would remain
+ // causing composers to appear in the albumartist filter
+ expectedAfter := []albumArtistRecord{
+ {ArtistID: "role-change-artist-1", Role: "composer", SubRole: ""},
+ }
+ verifyAlbumArtists(album.ID, expectedAfter)
+
+ // Clean up
+ _, _ = artistRepo.executeSQL(squirrel.Delete("artist").Where(squirrel.Eq{"id": artist.ID}))
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": album.ID}))
+ })
+ })
+
+ Describe("wrapAlbumCursor", func() {
+ It("does not panic when the cursor yields a dbAlbum with nil Album", func() {
+ // Simulate what queryWithStableResults does on the rows.Err() path:
+ // it yields a zero-value dbAlbum (where Album is nil) with an error.
+ dbErr := fmt.Errorf("database is locked")
+ cursor := func(yield func(dbAlbum, error) bool) {
+ var empty dbAlbum // Album pointer is nil
+ yield(empty, dbErr)
+ }
+
+ // wrapAlbumCursor should handle the nil Album without panicking
+ wrappedCursor := wrapAlbumCursor(cursor)
+ var gotErr error
+ Expect(func() {
+ for _, err := range wrappedCursor {
+ gotErr = err
+ }
+ }).ToNot(Panic())
+ Expect(gotErr).To(HaveOccurred())
+ Expect(gotErr.Error()).To(ContainSubstring("unexpected nil album"))
+ Expect(errors.Is(gotErr, dbErr)).To(BeTrue(), "should wrap the original cursor error")
+ })
+
+ It("yields albums from a valid cursor", func() {
+ album := &model.Album{ID: "a1", Name: "Test"}
+ cursor := func(yield func(dbAlbum, error) bool) {
+ yield(dbAlbum{Album: album}, nil)
+ }
+
+ wrappedCursor := wrapAlbumCursor(cursor)
+ var albums []model.Album
+ for a, err := range wrappedCursor {
+ Expect(err).ToNot(HaveOccurred())
+ albums = append(albums, a)
+ }
+ Expect(albums).To(HaveLen(1))
+ Expect(albums[0].ID).To(Equal("a1"))
+ })
})
})
diff --git a/persistence/artist_repository.go b/persistence/artist_repository.go
index a7cf9272a..e75a0e58c 100644
--- a/persistence/artist_repository.go
+++ b/persistence/artist_repository.go
@@ -4,15 +4,17 @@ import (
"cmp"
"context"
"encoding/json"
+ "errors"
"fmt"
+ "os"
"slices"
"strings"
"time"
. "github.com/Masterminds/squirrel"
"github.com/deluan/rest"
- "github.com/google/uuid"
"github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils"
@@ -102,6 +104,7 @@ func (a *dbArtist) PostMapArgs(m map[string]any) error {
similarArtists, _ := json.Marshal(sa)
m["similar_artists"] = string(similarArtists)
m["full_text"] = formatFullText(a.Name, a.SortArtistName)
+ m["search_normalized"] = normalizeForFTS(a.Name)
// Do not override the sort_artist_name and mbz_artist_id fields if they are empty
// TODO: Better way to handle this?
@@ -133,14 +136,16 @@ func NewArtistRepository(ctx context.Context, db dbx.Builder) model.ArtistReposi
r.registerModel(&model.Artist{}, map[string]filterFunc{
"id": idFilter(r.tableName),
"name": fullTextFilter(r.tableName, "mbz_artist_id"),
- "starred": booleanFilter,
+ "starred": annotationBoolFilter("starred"),
+ "has_rating": annotationBoolFilter("rating"),
"role": roleFilter,
"missing": booleanFilter,
"library_id": artistLibraryIdFilter,
})
- r.setSortMappings(map[string]string{
+ r.setSortMappings(map[string]string{ //nolint:gosec
"name": "order_artist_name",
"starred_at": "starred, starred_at",
+ "rated_at": "rating, rated_at",
"song_count": "stats->>'total'->>'m'",
"album_count": "stats->>'total'->>'a'",
"size": "stats->>'total'->>'s'",
@@ -163,7 +168,7 @@ func roleFilter(_ string, role any) Sqlizer {
}
// artistLibraryIdFilter filters artists based on library access through the library_artist table
-func artistLibraryIdFilter(_ string, value interface{}) Sqlizer {
+func artistLibraryIdFilter(_ string, value any) Sqlizer {
return Eq{"library_artist.library_id": value}
}
@@ -313,7 +318,19 @@ func (r *artistRepository) GetIndex(includeMissing bool, libraryIds []int, roles
}
func (r *artistRepository) purgeEmpty() error {
- del := Delete(r.tableName).Where("id not in (select artist_id from album_artists)")
+ orphanFilter := "id not in (select artist_id from album_artists)"
+
+ // Collect uploaded image filenames before deleting
+ sel := Select("uploaded_image").From(r.tableName).
+ Where(orphanFilter).
+ Where("uploaded_image != ''")
+ var imageFiles []string
+ if err := r.queryAllSlice(sel, &imageFiles); err != nil && !errors.Is(err, model.ErrNotFound) {
+ return fmt.Errorf("collecting artist images for cleanup: %w", err)
+ }
+
+ // Delete orphan artists
+ del := Delete(r.tableName).Where(orphanFilter)
c, err := r.executeSQL(del)
if err != nil {
return fmt.Errorf("purging empty artists: %w", err)
@@ -321,6 +338,19 @@ func (r *artistRepository) purgeEmpty() error {
if c > 0 {
log.Debug(r.ctx, "Purged empty artists", "totalDeleted", c)
}
+
+ if len(imageFiles) == 0 {
+ return nil
+ }
+
+ // Best-effort cleanup of uploaded image files
+ log.Debug(r.ctx, "Cleaning up artist images", "totalImages", len(imageFiles))
+ for _, filename := range imageFiles {
+ path := model.UploadedImagePath(consts.EntityArtist, filename)
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ log.Warn(r.ctx, "Failed to remove artist image during GC", "path", path, err)
+ }
+ }
return nil
}
@@ -400,23 +430,16 @@ func (r *artistRepository) RefreshStats(allArtists bool) (int64, error) {
// This now calculates per-library statistics and stores them in library_artist.stats
batchUpdateStatsSQL := `
WITH artist_role_counters AS (
- SELECT jt.atom AS artist_id,
+ SELECT mfa.artist_id,
mf.library_id,
- substr(
- replace(jt.path, '$.', ''),
- 1,
- CASE WHEN instr(replace(jt.path, '$.', ''), '[') > 0
- THEN instr(replace(jt.path, '$.', ''), '[') - 1
- ELSE length(replace(jt.path, '$.', ''))
- END
- ) AS role,
+ mfa.role,
count(DISTINCT mf.album_id) AS album_count,
- count(mf.id) AS count,
+ count(DISTINCT mf.id) AS count,
sum(mf.size) AS size
- FROM media_file mf
- JOIN json_tree(mf.participants) jt ON jt.key = 'id' AND jt.atom IS NOT NULL
- WHERE jt.atom IN (ROLE_IDS_PLACEHOLDER) -- Will replace with actual placeholders
- GROUP BY jt.atom, mf.library_id, role
+ FROM media_file_artists mfa
+ JOIN media_file mf ON mfa.media_file_id = mf.id
+ WHERE mfa.artist_id IN (ROLE_IDS_PLACEHOLDER) -- Will replace with actual placeholders
+ GROUP BY mfa.artist_id, mf.library_id, mfa.role
),
artist_total_counters AS (
SELECT mfa.artist_id,
@@ -445,24 +468,24 @@ func (r *artistRepository) RefreshStats(allArtists bool) (int64, error) {
),
combined_counters AS (
SELECT artist_id, library_id, role, album_count, count, size FROM artist_role_counters
- UNION
+ UNION ALL
SELECT artist_id, library_id, role, album_count, count, size FROM artist_total_counters
- UNION
+ UNION ALL
SELECT artist_id, library_id, role, album_count, count, size FROM artist_participant_counter
),
library_artist_counters AS (
SELECT artist_id,
library_id,
json_group_object(
- replace(role, '"', ''),
+ role,
json_object('a', album_count, 'm', count, 's', size)
) AS counters
FROM combined_counters
GROUP BY artist_id, library_id
)
UPDATE library_artist
- SET stats = coalesce((SELECT counters FROM library_artist_counters lac
- WHERE lac.artist_id = library_artist.artist_id
+ SET stats = coalesce((SELECT counters FROM library_artist_counters lac
+ WHERE lac.artist_id = library_artist.artist_id
AND lac.library_id = library_artist.library_id), '{}')
WHERE library_artist.artist_id IN (ROLE_IDS_PLACEHOLDER);` // Will replace with actual placeholders
@@ -518,20 +541,25 @@ func (r *artistRepository) RefreshStats(allArtists bool) (int64, error) {
return totalRowsAffected, nil
}
-func (r *artistRepository) Search(q string, offset int, size int, options ...model.QueryOptions) (model.Artists, error) {
- var res dbArtists
- if uuid.Validate(q) == nil {
- err := r.searchByMBID(r.selectArtist(options...), q, []string{"mbz_artist_id"}, &res)
- if err != nil {
- return nil, fmt.Errorf("searching artist by MBID %q: %w", q, err)
- }
- } else {
+func (r *artistRepository) searchCfg() searchConfig {
+ return searchConfig{
// Natural order for artists is more performant by ID, due to GROUP BY clause in selectArtist
- err := r.doSearch(r.selectArtist(options...), q, offset, size, &res, "artist.id",
- "sum(json_extract(stats, '$.total.m')) desc", "name")
- if err != nil {
- return nil, fmt.Errorf("searching artist by query %q: %w", q, err)
- }
+ NaturalOrder: "artist.id",
+ OrderBy: []string{"sum(json_extract(stats, '$.total.m')) desc", "name"},
+ MBIDFields: []string{"mbz_artist_id"},
+ LibraryFilter: r.applyLibraryFilterToArtistQuery,
+ }
+}
+
+func (r *artistRepository) Search(q string, options ...model.QueryOptions) (model.Artists, error) {
+ var opts model.QueryOptions
+ if len(options) > 0 {
+ opts = options[0]
+ }
+ var res dbArtists
+ err := r.doSearch(r.selectArtist(options...), q, &res, r.searchCfg(), opts)
+ if err != nil {
+ return nil, fmt.Errorf("searching artist %q: %w", q, err)
}
return res.toModels(), nil
}
@@ -540,11 +568,11 @@ func (r *artistRepository) Count(options ...rest.QueryOptions) (int64, error) {
return r.CountAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *artistRepository) Read(id string) (interface{}, error) {
+func (r *artistRepository) Read(id string) (any, error) {
return r.Get(id)
}
-func (r *artistRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *artistRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
role := "total"
if len(options) > 0 {
if v, ok := options[0].Filters["role"].(string); ok {
@@ -561,7 +589,7 @@ func (r *artistRepository) EntityName() string {
return "artist"
}
-func (r *artistRepository) NewInstance() interface{} {
+func (r *artistRepository) NewInstance() any {
return &model.Artist{}
}
diff --git a/persistence/artist_repository_test.go b/persistence/artist_repository_test.go
index dfaf499ac..e2904466c 100644
--- a/persistence/artist_repository_test.go
+++ b/persistence/artist_repository_test.go
@@ -3,10 +3,14 @@ package persistence
import (
"context"
"encoding/json"
+ "os"
+ "path/filepath"
"github.com/Masterminds/squirrel"
+ "github.com/deluan/rest"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/utils"
@@ -192,7 +196,7 @@ var _ = Describe("ArtistRepository", func() {
Describe("Basic Operations", func() {
Describe("Count", func() {
It("returns the number of artists in the DB", func() {
- Expect(repo.CountAll()).To(Equal(int64(2)))
+ Expect(repo.CountAll()).To(Equal(int64(4)))
})
})
@@ -227,13 +231,19 @@ var _ = Describe("ArtistRepository", func() {
idx, err := repo.GetIndex(false, []int{1})
Expect(err).ToNot(HaveOccurred())
- Expect(idx).To(HaveLen(2))
+ Expect(idx).To(HaveLen(4))
Expect(idx[0].ID).To(Equal("F"))
Expect(idx[0].Artists).To(HaveLen(1))
Expect(idx[0].Artists[0].Name).To(Equal(artistBeatles.Name))
Expect(idx[1].ID).To(Equal("K"))
Expect(idx[1].Artists).To(HaveLen(1))
Expect(idx[1].Artists[0].Name).To(Equal(artistKraftwerk.Name))
+ Expect(idx[2].ID).To(Equal("R"))
+ Expect(idx[2].Artists).To(HaveLen(1))
+ Expect(idx[2].Artists[0].Name).To(Equal(artistPunctuation.Name))
+ Expect(idx[3].ID).To(Equal("S"))
+ Expect(idx[3].Artists).To(HaveLen(1))
+ Expect(idx[3].Artists[0].Name).To(Equal(artistCJK.Name))
// Restore the original value
artistBeatles.SortArtistName = ""
@@ -245,13 +255,19 @@ var _ = Describe("ArtistRepository", func() {
XIt("returns the index when PreferSortTags is true and SortArtistName is empty", func() {
idx, err := repo.GetIndex(false, []int{1})
Expect(err).ToNot(HaveOccurred())
- Expect(idx).To(HaveLen(2))
+ Expect(idx).To(HaveLen(4))
Expect(idx[0].ID).To(Equal("B"))
Expect(idx[0].Artists).To(HaveLen(1))
Expect(idx[0].Artists[0].Name).To(Equal(artistBeatles.Name))
Expect(idx[1].ID).To(Equal("K"))
Expect(idx[1].Artists).To(HaveLen(1))
Expect(idx[1].Artists[0].Name).To(Equal(artistKraftwerk.Name))
+ Expect(idx[2].ID).To(Equal("R"))
+ Expect(idx[2].Artists).To(HaveLen(1))
+ Expect(idx[2].Artists[0].Name).To(Equal(artistPunctuation.Name))
+ Expect(idx[3].ID).To(Equal("S"))
+ Expect(idx[3].Artists).To(HaveLen(1))
+ Expect(idx[3].Artists[0].Name).To(Equal(artistCJK.Name))
})
})
@@ -267,13 +283,19 @@ var _ = Describe("ArtistRepository", func() {
idx, err := repo.GetIndex(false, []int{1})
Expect(err).ToNot(HaveOccurred())
- Expect(idx).To(HaveLen(2))
+ Expect(idx).To(HaveLen(4))
Expect(idx[0].ID).To(Equal("B"))
Expect(idx[0].Artists).To(HaveLen(1))
Expect(idx[0].Artists[0].Name).To(Equal(artistBeatles.Name))
Expect(idx[1].ID).To(Equal("K"))
Expect(idx[1].Artists).To(HaveLen(1))
Expect(idx[1].Artists[0].Name).To(Equal(artistKraftwerk.Name))
+ Expect(idx[2].ID).To(Equal("R"))
+ Expect(idx[2].Artists).To(HaveLen(1))
+ Expect(idx[2].Artists[0].Name).To(Equal(artistPunctuation.Name))
+ Expect(idx[3].ID).To(Equal("S"))
+ Expect(idx[3].Artists).To(HaveLen(1))
+ Expect(idx[3].Artists[0].Name).To(Equal(artistCJK.Name))
// Restore the original value
artistBeatles.SortArtistName = ""
@@ -284,13 +306,19 @@ var _ = Describe("ArtistRepository", func() {
It("returns the index when SortArtistName is empty", func() {
idx, err := repo.GetIndex(false, []int{1})
Expect(err).ToNot(HaveOccurred())
- Expect(idx).To(HaveLen(2))
+ Expect(idx).To(HaveLen(4))
Expect(idx[0].ID).To(Equal("B"))
Expect(idx[0].Artists).To(HaveLen(1))
Expect(idx[0].Artists[0].Name).To(Equal(artistBeatles.Name))
Expect(idx[1].ID).To(Equal("K"))
Expect(idx[1].Artists).To(HaveLen(1))
Expect(idx[1].Artists[0].Name).To(Equal(artistKraftwerk.Name))
+ Expect(idx[2].ID).To(Equal("R"))
+ Expect(idx[2].Artists).To(HaveLen(1))
+ Expect(idx[2].Artists[0].Name).To(Equal(artistPunctuation.Name))
+ Expect(idx[3].ID).To(Equal("S"))
+ Expect(idx[3].Artists).To(HaveLen(1))
+ Expect(idx[3].Artists[0].Name).To(Equal(artistCJK.Name))
})
})
@@ -376,7 +404,7 @@ var _ = Describe("ArtistRepository", func() {
// Admin users can see all content when valid library IDs are provided
idx, err := repo.GetIndex(false, []int{1})
Expect(err).ToNot(HaveOccurred())
- Expect(idx).To(HaveLen(2))
+ Expect(idx).To(HaveLen(4))
// With non-existent library ID, admin users see no content because no artists are associated with that library
idx, err = repo.GetIndex(false, []int{999})
@@ -386,6 +414,54 @@ var _ = Describe("ArtistRepository", func() {
})
})
+ Describe("Filters", func() {
+ var artistWithoutAnnotation model.Artist
+
+ BeforeEach(func() {
+ // Create artist without any annotation
+ artistWithoutAnnotation = model.Artist{ID: "no-annotation-artist", Name: "No Annotation Artist"}
+ err := createArtistWithLibrary(repo, &artistWithoutAnnotation, 1)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ AfterEach(func() {
+ if raw, ok := repo.(*artistRepository); ok {
+ _, _ = raw.executeSQL(squirrel.Delete(raw.tableName).Where(squirrel.Eq{"id": artistWithoutAnnotation.ID}))
+ }
+ })
+
+ Describe("starred", func() {
+ It("false includes items without annotations", func() {
+ res, err := repo.(model.ResourceRepository).ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"starred": "false"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ artists := res.(model.Artists)
+
+ var found bool
+ for _, a := range artists {
+ if a.ID == artistWithoutAnnotation.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "Artist without annotation should be included in starred=false filter")
+ })
+
+ It("true excludes items without annotations", func() {
+ res, err := repo.(model.ResourceRepository).ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"starred": "true"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ artists := res.(model.Artists)
+
+ for _, a := range artists {
+ Expect(a.ID).ToNot(Equal(artistWithoutAnnotation.ID))
+ }
+ })
+ })
+ })
+
Describe("MBID and Text Search", func() {
var lib2 model.Library
var lr model.LibraryRepository
@@ -439,7 +515,7 @@ var _ = Describe("ArtistRepository", func() {
Expect(err).ToNot(HaveOccurred())
// Test the search
- results, err := (*testRepo).Search("550e8400-e29b-41d4-a716-446655440010", 0, 10)
+ results, err := (*testRepo).Search("550e8400-e29b-41d4-a716-446655440010", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
if shouldFind {
@@ -470,12 +546,12 @@ var _ = Describe("ArtistRepository", func() {
Expect(err).ToNot(HaveOccurred())
// Restricted user should not find this artist
- results, err := restrictedRepo.Search("a74b1b7f-71a5-4011-9441-d0b5e4122711", 0, 10)
+ results, err := restrictedRepo.Search("a74b1b7f-71a5-4011-9441-d0b5e4122711", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty())
// But admin should find it
- results, err = repo.Search("a74b1b7f-71a5-4011-9441-d0b5e4122711", 0, 10)
+ results, err = repo.Search("a74b1b7f-71a5-4011-9441-d0b5e4122711", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(HaveLen(1))
@@ -487,7 +563,7 @@ var _ = Describe("ArtistRepository", func() {
Context("Text Search", func() {
It("allows admin to find artists by name regardless of library", func() {
- results, err := repo.Search("Beatles", 0, 10)
+ results, err := repo.Search("Beatles", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].Name).To(Equal("The Beatles"))
@@ -507,7 +583,7 @@ var _ = Describe("ArtistRepository", func() {
Expect(err).ToNot(HaveOccurred())
// Restricted user should not find this artist
- results, err := restrictedRepo.Search("Unique Search Name", 0, 10)
+ results, err := restrictedRepo.Search("Unique Search Name", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty(), "Text search should respect library filtering")
@@ -576,11 +652,11 @@ var _ = Describe("ArtistRepository", func() {
It("sees all artists regardless of library permissions", func() {
count, err := repo.CountAll()
Expect(err).ToNot(HaveOccurred())
- Expect(count).To(Equal(int64(2)))
+ Expect(count).To(Equal(int64(4)))
artists, err := repo.GetAll()
Expect(err).ToNot(HaveOccurred())
- Expect(artists).To(HaveLen(2))
+ Expect(artists).To(HaveLen(4))
exists, err := repo.Exists(artistBeatles.ID)
Expect(err).ToNot(HaveOccurred())
@@ -612,10 +688,10 @@ var _ = Describe("ArtistRepository", func() {
// Should see missing artist in GetAll by default for admin users
artists, err := repo.GetAll()
Expect(err).ToNot(HaveOccurred())
- Expect(artists).To(HaveLen(3)) // Including the missing artist
+ Expect(artists).To(HaveLen(5)) // Including the missing artist
// Search never returns missing artists (hardcoded behavior)
- results, err := repo.Search("Missing Artist", 0, 10)
+ results, err := repo.Search("Missing Artist", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty())
})
@@ -669,11 +745,11 @@ var _ = Describe("ArtistRepository", func() {
})
It("Search returns empty results for users without library access", func() {
- results, err := restrictedRepo.Search("Beatles", 0, 10)
+ results, err := restrictedRepo.Search("Beatles", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty())
- results, err = restrictedRepo.Search("Kraftwerk", 0, 10)
+ results, err = restrictedRepo.Search("Kraftwerk", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty())
})
@@ -718,19 +794,19 @@ var _ = Describe("ArtistRepository", func() {
It("CountAll returns correct count after gaining access", func() {
count, err := restrictedRepo.CountAll()
Expect(err).ToNot(HaveOccurred())
- Expect(count).To(Equal(int64(2))) // Beatles and Kraftwerk
+ Expect(count).To(Equal(int64(4))) // Beatles, Kraftwerk, Seatbelts, and The Roots
})
It("GetAll returns artists after gaining access", func() {
artists, err := restrictedRepo.GetAll()
Expect(err).ToNot(HaveOccurred())
- Expect(artists).To(HaveLen(2))
+ Expect(artists).To(HaveLen(4))
var names []string
for _, artist := range artists {
names = append(names, artist.Name)
}
- Expect(names).To(ContainElements("The Beatles", "Kraftwerk"))
+ Expect(names).To(ContainElements("The Beatles", "Kraftwerk", "シートベルツ", "The Roots"))
})
It("Exists returns true for accessible artists", func() {
@@ -747,7 +823,7 @@ var _ = Describe("ArtistRepository", func() {
// With valid library access, should see artists
idx, err := restrictedRepo.GetIndex(false, []int{1})
Expect(err).ToNot(HaveOccurred())
- Expect(idx).To(HaveLen(2))
+ Expect(idx).To(HaveLen(4))
// With non-existent library ID, should see nothing (non-admin user)
idx, err = restrictedRepo.GetIndex(false, []int{999})
@@ -756,6 +832,89 @@ var _ = Describe("ArtistRepository", func() {
})
})
})
+
+ Describe("purgeEmpty", func() {
+ var repo *artistRepository
+ var tmpDir string
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ tmpDir = GinkgoT().TempDir()
+ conf.Server.DataFolder = tmpDir
+
+ ctx := request.WithUser(GinkgoT().Context(), adminUser)
+ repo = NewArtistRepository(ctx, GetDBXBuilder()).(*artistRepository)
+ })
+
+ // Helper to create an artist image file on disk and return its path
+ createImageFile := func(filename string) string {
+ dir := filepath.Join(tmpDir, consts.ArtworkFolder, consts.EntityArtist)
+ Expect(os.MkdirAll(dir, 0755)).To(Succeed())
+ path := filepath.Join(dir, filename)
+ Expect(os.WriteFile(path, []byte("fake image data"), 0600)).To(Succeed())
+ return path
+ }
+
+ It("removes uploaded image files for purged artists", func() {
+ // Create an orphan artist (not in album_artists) with an uploaded image
+ orphanArtist := model.Artist{ID: "orphan-with-image", Name: "Orphan Artist", UploadedImage: "orphan-with-image_Orphan_Artist.jpg"}
+ Expect(repo.Put(&orphanArtist)).To(Succeed())
+ imgPath := createImageFile("orphan-with-image_Orphan_Artist.jpg")
+
+ Expect(repo.purgeEmpty()).To(Succeed())
+
+ // Artist should be gone from DB
+ exists, err := repo.Exists("orphan-with-image")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(exists).To(BeFalse())
+
+ // Image file should be removed from disk
+ _, err = os.Stat(imgPath)
+ Expect(os.IsNotExist(err)).To(BeTrue())
+ })
+
+ It("handles missing image files gracefully", func() {
+ // Artist has UploadedImage set but no actual file on disk
+ orphanArtist := model.Artist{ID: "orphan-no-file", Name: "Ghost Image", UploadedImage: "orphan-no-file_Ghost_Image.jpg"}
+ Expect(repo.Put(&orphanArtist)).To(Succeed())
+
+ Expect(repo.purgeEmpty()).To(Succeed())
+
+ // Artist should be gone from DB
+ exists, err := repo.Exists("orphan-no-file")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(exists).To(BeFalse())
+ })
+
+ It("does not delete images for artists that are kept", func() {
+ // Create an artist with an uploaded image AND an album_artists entry so it won't be purged
+ keptArtist := model.Artist{ID: "kept-artist", Name: "Kept Artist", UploadedImage: "kept-artist_Kept_Artist.jpg"}
+ Expect(repo.Put(&keptArtist)).To(Succeed())
+ imgPath := createImageFile("kept-artist_Kept_Artist.jpg")
+
+ // Insert an album_artists record to keep this artist from being purged
+ _, err := repo.executeSQL(squirrel.Insert("album_artists").
+ SetMap(map[string]any{"album_id": "101", "artist_id": "kept-artist", "role": "artist", "sub_role": ""}))
+ Expect(err).ToNot(HaveOccurred())
+
+ DeferCleanup(func() {
+ _, _ = repo.executeSQL(squirrel.Delete("album_artists").Where(squirrel.Eq{"artist_id": "kept-artist"}))
+ _ = repo.delete(squirrel.Eq{"id": "kept-artist"})
+ })
+
+ Expect(repo.purgeEmpty()).To(Succeed())
+
+ // Artist should still exist (check directly, bypassing library filter)
+ var ids []string
+ err = repo.queryAllSlice(squirrel.Select("id").From("artist").Where(squirrel.Eq{"id": "kept-artist"}), &ids)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(ids).To(HaveLen(1))
+
+ // Image file should still be on disk
+ _, err = os.Stat(imgPath)
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
})
// Helper function to create an artist with proper library association.
diff --git a/persistence/collation_test.go b/persistence/collation_test.go
index 7e1144753..bb1276577 100644
--- a/persistence/collation_test.go
+++ b/persistence/collation_test.go
@@ -32,6 +32,7 @@ var _ = Describe("Collation", func() {
Entry("media_file.sort_title", "media_file", "sort_title"),
Entry("media_file.sort_album_name", "media_file", "sort_album_name"),
Entry("media_file.sort_artist_name", "media_file", "sort_artist_name"),
+ Entry("playlist.name", "playlist", "name"),
Entry("radio.name", "radio", "name"),
Entry("user.name", "user", "name"),
)
@@ -53,6 +54,7 @@ var _ = Describe("Collation", func() {
Entry("media_file.sort_album_name", "media_file", "coalesce(nullif(sort_album_name,''),order_album_name) collate nocase"),
Entry("media_file.sort_artist_name", "media_file", "coalesce(nullif(sort_artist_name,''),order_artist_name) collate nocase"),
Entry("media_file.path", "media_file", "path collate nocase"),
+ Entry("playlist.name", "playlist", "name collate nocase"),
Entry("radio.name", "radio", "name collate nocase"),
Entry("user.user_name", "user", "user_name collate nocase"),
)
diff --git a/persistence/folder_repository.go b/persistence/folder_repository.go
index 96a9bae82..f7bb6a4fe 100644
--- a/persistence/folder_repository.go
+++ b/persistence/folder_repository.go
@@ -4,7 +4,12 @@ import (
"context"
"encoding/json"
"fmt"
+ "iter"
+ "maps"
+ "os"
+ "path/filepath"
"slices"
+ "strings"
"time"
. "github.com/Masterminds/squirrel"
@@ -91,8 +96,82 @@ func (r folderRepository) CountAll(opt ...model.QueryOptions) (int64, error) {
return r.count(query)
}
-func (r folderRepository) GetLastUpdates(lib model.Library) (map[string]model.FolderUpdateInfo, error) {
- sq := r.newSelect().Columns("id", "updated_at", "hash").Where(Eq{"library_id": lib.ID, "missing": false})
+func (r folderRepository) GetFolderUpdateInfo(lib model.Library, targetPaths ...string) (map[string]model.FolderUpdateInfo, error) {
+ // If no specific paths, return all folders in the library
+ if len(targetPaths) == 0 {
+ return r.getFolderUpdateInfoAll(lib)
+ }
+
+ // Check if any path is root (return all folders)
+ for _, targetPath := range targetPaths {
+ if targetPath == "" || targetPath == "." {
+ return r.getFolderUpdateInfoAll(lib)
+ }
+ }
+
+ // Process paths in batches to avoid SQLite's expression tree depth limit (max 1000).
+ // Each path generates ~3 conditions, so batch size of 100 keeps us well under the limit.
+ const batchSize = 100
+ result := make(map[string]model.FolderUpdateInfo)
+
+ for batch := range slices.Chunk(targetPaths, batchSize) {
+ batchResult, err := r.getFolderUpdateInfoBatch(lib, batch)
+ if err != nil {
+ return nil, err
+ }
+ maps.Copy(result, batchResult)
+ }
+
+ return result, nil
+}
+
+// getFolderUpdateInfoAll returns update info for all non-missing folders in the library
+func (r folderRepository) getFolderUpdateInfoAll(lib model.Library) (map[string]model.FolderUpdateInfo, error) {
+ where := And{
+ Eq{"library_id": lib.ID},
+ Eq{"missing": false},
+ }
+ return r.queryFolderUpdateInfo(where)
+}
+
+// getFolderUpdateInfoBatch returns update info for a batch of target paths and their descendants
+func (r folderRepository) getFolderUpdateInfoBatch(lib model.Library, targetPaths []string) (map[string]model.FolderUpdateInfo, error) {
+ where := And{
+ Eq{"library_id": lib.ID},
+ Eq{"missing": false},
+ }
+
+ // Collect folder IDs for exact target folders and path conditions for descendants
+ folderIDs := make([]string, 0, len(targetPaths))
+ pathConditions := make(Or, 0, len(targetPaths)*2)
+
+ for _, targetPath := range targetPaths {
+ // Clean the path to normalize it. Paths stored in the folder table do not have leading/trailing slashes.
+ cleanPath := strings.TrimPrefix(targetPath, string(os.PathSeparator))
+ cleanPath = filepath.Clean(cleanPath)
+
+ // Include the target folder itself by ID
+ folderIDs = append(folderIDs, model.FolderID(lib, cleanPath))
+
+ // Include all descendants: folders whose path field equals or starts with the target path
+ // Note: Folder.Path is the directory path, so children have path = targetPath
+ pathConditions = append(pathConditions, Eq{"path": cleanPath})
+ pathConditions = append(pathConditions, Like{"path": cleanPath + "/%"})
+ }
+
+ // Combine conditions: exact folder IDs OR descendant path patterns
+ if len(folderIDs) > 0 {
+ where = append(where, Or{Eq{"id": folderIDs}, pathConditions})
+ } else if len(pathConditions) > 0 {
+ where = append(where, pathConditions)
+ }
+
+ return r.queryFolderUpdateInfo(where)
+}
+
+// queryFolderUpdateInfo executes the query and returns the result map
+func (r folderRepository) queryFolderUpdateInfo(where And) (map[string]model.FolderUpdateInfo, error) {
+ sq := r.newSelect().Columns("id", "updated_at", "hash").Where(where)
var res []struct {
ID string
UpdatedAt time.Time
@@ -140,16 +219,24 @@ func (r folderRepository) GetTouchedWithPlaylists() (model.FolderCursor, error)
if err != nil {
return nil, err
}
+ return wrapFolderCursor(cursor), nil
+}
+
+func wrapFolderCursor(cursor iter.Seq2[dbFolder, error]) model.FolderCursor {
return func(yield func(model.Folder, error) bool) {
for f, err := range cursor {
+ if f.Folder == nil {
+ yield(model.Folder{}, fmt.Errorf("unexpected nil folder (%v): %w", f, err))
+ return
+ }
if !yield(*f.Folder, err) || err != nil {
return
}
}
- }, nil
+ }
}
-func (r folderRepository) purgeEmpty() error {
+func (r folderRepository) purgeEmpty(libraryIDs ...int) error {
sq := Delete(r.tableName).Where(And{
Eq{"num_audio_files": 0},
Eq{"num_playlists": 0},
@@ -157,6 +244,10 @@ func (r folderRepository) purgeEmpty() error {
ConcatExpr("id not in (select parent_id from folder)"),
ConcatExpr("id not in (select folder_id from media_file)"),
})
+ // If libraryIDs are specified, only purge folders from those libraries
+ if len(libraryIDs) > 0 {
+ sq = sq.Where(Eq{"library_id": libraryIDs})
+ }
c, err := r.executeSQL(sq)
if err != nil {
return fmt.Errorf("purging empty folders: %w", err)
diff --git a/persistence/folder_repository_test.go b/persistence/folder_repository_test.go
new file mode 100644
index 000000000..7b6a0f764
--- /dev/null
+++ b/persistence/folder_repository_test.go
@@ -0,0 +1,254 @@
+package persistence
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/pocketbase/dbx"
+)
+
+var _ = Describe("FolderRepository", func() {
+ var repo model.FolderRepository
+ var ctx context.Context
+ var conn *dbx.DB
+ var testLib, otherLib model.Library
+
+ BeforeEach(func() {
+ ctx = request.WithUser(log.NewContext(context.TODO()), model.User{ID: "userid"})
+ conn = GetDBXBuilder()
+ repo = newFolderRepository(ctx, conn)
+
+ // Use existing library ID 1 from test fixtures
+ libRepo := NewLibraryRepository(ctx, conn)
+ lib, err := libRepo.Get(1)
+ Expect(err).ToNot(HaveOccurred())
+ testLib = *lib
+
+ // Create a second library with its own folder to verify isolation
+ otherLib = model.Library{Name: "Other Library", Path: "/other/path"}
+ Expect(libRepo.Put(&otherLib)).To(Succeed())
+ })
+
+ AfterEach(func() {
+ // Clean up only test folders created by our tests (paths starting with "Test")
+ // This prevents interference with fixture data needed by other tests
+ _, _ = conn.NewQuery("DELETE FROM folder WHERE library_id = 1 AND path LIKE 'Test%'").Execute()
+ _, _ = conn.NewQuery(fmt.Sprintf("DELETE FROM library WHERE id = %d", otherLib.ID)).Execute()
+ })
+
+ Describe("GetFolderUpdateInfo", func() {
+ Context("with no target paths", func() {
+ It("returns all folders in the library", func() {
+ // Create test folders with unique names to avoid conflicts
+ folder1 := model.NewFolder(testLib, "TestGetLastUpdates/Folder1")
+ folder2 := model.NewFolder(testLib, "TestGetLastUpdates/Folder2")
+
+ err := repo.Put(folder1)
+ Expect(err).ToNot(HaveOccurred())
+ err = repo.Put(folder2)
+ Expect(err).ToNot(HaveOccurred())
+
+ otherFolder := model.NewFolder(otherLib, "TestOtherLib/Folder")
+ err = repo.Put(otherFolder)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Query all folders (no target paths) - should only return folders from testLib
+ results, err := repo.GetFolderUpdateInfo(testLib)
+ Expect(err).ToNot(HaveOccurred())
+ // Should include folders from testLib
+ Expect(results).To(HaveKey(folder1.ID))
+ Expect(results).To(HaveKey(folder2.ID))
+ // Should NOT include folders from other library
+ Expect(results).ToNot(HaveKey(otherFolder.ID))
+ })
+ })
+
+ Context("with specific target paths", func() {
+ It("returns folder info for existing folders", func() {
+ // Create test folders with unique names
+ folder1 := model.NewFolder(testLib, "TestSpecific/Rock")
+ folder2 := model.NewFolder(testLib, "TestSpecific/Jazz")
+ folder3 := model.NewFolder(testLib, "TestSpecific/Classical")
+
+ err := repo.Put(folder1)
+ Expect(err).ToNot(HaveOccurred())
+ err = repo.Put(folder2)
+ Expect(err).ToNot(HaveOccurred())
+ err = repo.Put(folder3)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Query specific paths
+ results, err := repo.GetFolderUpdateInfo(testLib, "TestSpecific/Rock", "TestSpecific/Classical")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(2))
+
+ // Verify folder IDs are in results
+ Expect(results).To(HaveKey(folder1.ID))
+ Expect(results).To(HaveKey(folder3.ID))
+ Expect(results).ToNot(HaveKey(folder2.ID))
+
+ // Verify update info is populated
+ Expect(results[folder1.ID].UpdatedAt).ToNot(BeZero())
+ Expect(results[folder1.ID].Hash).To(Equal(folder1.Hash))
+ })
+
+ It("includes all child folders when querying parent", func() {
+ // Create a parent folder with multiple children
+ parent := model.NewFolder(testLib, "TestParent/Music")
+ child1 := model.NewFolder(testLib, "TestParent/Music/Rock/Queen")
+ child2 := model.NewFolder(testLib, "TestParent/Music/Jazz")
+ otherParent := model.NewFolder(testLib, "TestParent2/Music/Jazz")
+
+ Expect(repo.Put(parent)).To(Succeed())
+ Expect(repo.Put(child1)).To(Succeed())
+ Expect(repo.Put(child2)).To(Succeed())
+
+ // Query the parent folder - should return parent and all children
+ results, err := repo.GetFolderUpdateInfo(testLib, "TestParent/Music")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(3))
+ Expect(results).To(HaveKey(parent.ID))
+ Expect(results).To(HaveKey(child1.ID))
+ Expect(results).To(HaveKey(child2.ID))
+ Expect(results).ToNot(HaveKey(otherParent.ID))
+ })
+
+ It("excludes children from other libraries", func() {
+ // Create parent in testLib
+ parent := model.NewFolder(testLib, "TestIsolation/Parent")
+ child := model.NewFolder(testLib, "TestIsolation/Parent/Child")
+
+ Expect(repo.Put(parent)).To(Succeed())
+ Expect(repo.Put(child)).To(Succeed())
+
+ // Create similar path in other library
+ otherParent := model.NewFolder(otherLib, "TestIsolation/Parent")
+ otherChild := model.NewFolder(otherLib, "TestIsolation/Parent/Child")
+
+ Expect(repo.Put(otherParent)).To(Succeed())
+ Expect(repo.Put(otherChild)).To(Succeed())
+
+ // Query should only return folders from testLib
+ results, err := repo.GetFolderUpdateInfo(testLib, "TestIsolation/Parent")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(2))
+ Expect(results).To(HaveKey(parent.ID))
+ Expect(results).To(HaveKey(child.ID))
+ Expect(results).ToNot(HaveKey(otherParent.ID))
+ Expect(results).ToNot(HaveKey(otherChild.ID))
+ })
+
+ It("excludes missing children when querying parent", func() {
+ // Create parent and children, mark one as missing
+ parent := model.NewFolder(testLib, "TestMissingChild/Parent")
+ child1 := model.NewFolder(testLib, "TestMissingChild/Parent/Child1")
+ child2 := model.NewFolder(testLib, "TestMissingChild/Parent/Child2")
+ child2.Missing = true
+
+ Expect(repo.Put(parent)).To(Succeed())
+ Expect(repo.Put(child1)).To(Succeed())
+ Expect(repo.Put(child2)).To(Succeed())
+
+ // Query parent - should only return parent and non-missing child
+ results, err := repo.GetFolderUpdateInfo(testLib, "TestMissingChild/Parent")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(2))
+ Expect(results).To(HaveKey(parent.ID))
+ Expect(results).To(HaveKey(child1.ID))
+ Expect(results).ToNot(HaveKey(child2.ID))
+ })
+
+ It("handles mix of existing and non-existing target paths", func() {
+ // Create folders for one path but not the other
+ existingParent := model.NewFolder(testLib, "TestMixed/Exists")
+ existingChild := model.NewFolder(testLib, "TestMixed/Exists/Child")
+
+ Expect(repo.Put(existingParent)).To(Succeed())
+ Expect(repo.Put(existingChild)).To(Succeed())
+
+ // Query both existing and non-existing paths
+ results, err := repo.GetFolderUpdateInfo(testLib, "TestMixed/Exists", "TestMixed/DoesNotExist")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(2))
+ Expect(results).To(HaveKey(existingParent.ID))
+ Expect(results).To(HaveKey(existingChild.ID))
+ })
+
+ It("handles empty folder path as root", func() {
+ // Test querying for root folder without creating it (fixtures should have one)
+ rootFolderID := model.FolderID(testLib, ".")
+
+ results, err := repo.GetFolderUpdateInfo(testLib, "")
+ Expect(err).ToNot(HaveOccurred())
+ // Should return the root folder if it exists
+ if len(results) > 0 {
+ Expect(results).To(HaveKey(rootFolderID))
+ }
+ })
+
+ It("returns empty map for non-existent folders", func() {
+ results, err := repo.GetFolderUpdateInfo(testLib, "NonExistent/Path")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty())
+ })
+
+ It("skips missing folders", func() {
+ // Create a folder and mark it as missing
+ folder := model.NewFolder(testLib, "TestMissing/Folder")
+ folder.Missing = true
+ err := repo.Put(folder)
+ Expect(err).ToNot(HaveOccurred())
+
+ results, err := repo.GetFolderUpdateInfo(testLib, "TestMissing/Folder")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty())
+ })
+ })
+ })
+
+ Describe("wrapFolderCursor", func() {
+ It("does not panic when the cursor yields a dbFolder with nil Folder", func() {
+ // Simulate what queryWithStableResults does on the rows.Err() path:
+ // it yields a zero-value dbFolder (where Folder is nil) with an error.
+ dbErr := fmt.Errorf("database is locked")
+ cursor := func(yield func(dbFolder, error) bool) {
+ var empty dbFolder // Folder pointer is nil
+ yield(empty, dbErr)
+ }
+
+ // wrapFolderCursor should handle the nil Folder without panicking
+ wrappedCursor := wrapFolderCursor(cursor)
+ var gotErr error
+ Expect(func() {
+ for _, err := range wrappedCursor {
+ gotErr = err
+ }
+ }).ToNot(Panic())
+ Expect(gotErr).To(HaveOccurred())
+ Expect(gotErr.Error()).To(ContainSubstring("unexpected nil folder"))
+ Expect(errors.Is(gotErr, dbErr)).To(BeTrue(), "should wrap the original cursor error")
+ })
+
+ It("yields folders from a valid cursor", func() {
+ folder := &model.Folder{ID: "f1", Name: "Test"}
+ cursor := func(yield func(dbFolder, error) bool) {
+ yield(dbFolder{Folder: folder}, nil)
+ }
+
+ wrappedCursor := wrapFolderCursor(cursor)
+ var folders []model.Folder
+ for f, err := range wrappedCursor {
+ Expect(err).ToNot(HaveOccurred())
+ folders = append(folders, f)
+ }
+ Expect(folders).To(HaveLen(1))
+ Expect(folders[0].ID).To(Equal("f1"))
+ })
+ })
+})
diff --git a/persistence/genre_repository.go b/persistence/genre_repository.go
index 5857350a6..53f324bf4 100644
--- a/persistence/genre_repository.go
+++ b/persistence/genre_repository.go
@@ -33,18 +33,18 @@ func (r *genreRepository) GetAll(opt ...model.QueryOptions) (model.Genres, error
// Override ResourceRepository methods to return Genre objects instead of Tag objects
-func (r *genreRepository) Read(id string) (interface{}, error) {
+func (r *genreRepository) Read(id string) (any, error) {
sel := r.selectGenre().Where(Eq{"tag.id": id})
var res model.Genre
err := r.queryOne(sel, &res)
return &res, err
}
-func (r *genreRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *genreRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
return r.GetAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *genreRepository) NewInstance() interface{} {
+func (r *genreRepository) NewInstance() any {
return &model.Genre{}
}
diff --git a/persistence/genre_repository_test.go b/persistence/genre_repository_test.go
index 67e84ce51..e3779725c 100644
--- a/persistence/genre_repository_test.go
+++ b/persistence/genre_repository_test.go
@@ -182,7 +182,7 @@ var _ = Describe("GenreRepository", func() {
It("should filter by name using like match", func() {
// Test filtering by partial name match using the "name" filter which maps to containsFilter("tag_value")
options := rest.QueryOptions{
- Filters: map[string]interface{}{"name": "%rock%"},
+ Filters: map[string]any{"name": "%rock%"},
}
count, err := restRepo.Count(options)
Expect(err).ToNot(HaveOccurred())
@@ -289,7 +289,7 @@ var _ = Describe("GenreRepository", func() {
It("should allow headless processes to apply explicit library_id filters", func() {
// Filter by specific library
genres, err := headlessRestRepo.ReadAll(rest.QueryOptions{
- Filters: map[string]interface{}{"library_id": 2},
+ Filters: map[string]any{"library_id": 2},
})
Expect(err).ToNot(HaveOccurred())
diff --git a/persistence/helpers.go b/persistence/helpers.go
index 73815ae45..fd6a9a4cd 100644
--- a/persistence/helpers.go
+++ b/persistence/helpers.go
@@ -15,7 +15,7 @@ type PostMapper interface {
PostMapArgs(map[string]any) error
}
-func toSQLArgs(rec interface{}) (map[string]interface{}, error) {
+func toSQLArgs(rec any) (map[string]any, error) {
m := structs.Map(rec)
for k, v := range m {
switch t := v.(type) {
@@ -71,7 +71,7 @@ type existsCond struct {
not bool
}
-func (e existsCond) ToSql() (string, []interface{}, error) {
+func (e existsCond) ToSql() (string, []any, error) {
sql, args, err := e.cond.ToSql()
sql = fmt.Sprintf("exists (select 1 from %s where %s)", e.subTable, sql)
if e.not {
diff --git a/persistence/library_repository.go b/persistence/library_repository.go
index 314b682bb..1d8e6f35e 100644
--- a/persistence/library_repository.go
+++ b/persistence/library_repository.go
@@ -177,7 +177,11 @@ func (r *libraryRepository) ScanEnd(id int) error {
return err
}
// https://www.sqlite.org/pragma.html#pragma_optimize
- _, err = r.executeSQL(Expr("PRAGMA optimize=0x10012;"))
+ // Use mask 0x10000 to check table sizes without running ANALYZE
+ // Running ANALYZE can cause query planner issues with expression-based collation indexes
+ if conf.Server.DevOptimizeDB {
+ _, err = r.executeSQL(Expr("PRAGMA optimize=0x10000;"))
+ }
return err
}
@@ -262,6 +266,10 @@ func (r *libraryRepository) Delete(id int) error {
defer libLock.Unlock()
delete(libCache, id)
+ // Clean up orphaned plugin references for the deleted library
+ if err := cleanupPluginLibraryReferences(r.db, id); err != nil {
+ log.Error(r.ctx, "Failed to cleanup plugin library references", "libraryID", id, err)
+ }
return nil
}
@@ -297,7 +305,7 @@ func (r *libraryRepository) Count(options ...rest.QueryOptions) (int64, error) {
return r.CountAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *libraryRepository) Read(id string) (interface{}, error) {
+func (r *libraryRepository) Read(id string) (any, error) {
idInt, err := strconv.Atoi(id)
if err != nil {
log.Trace(r.ctx, "invalid library id: %s", id, err)
@@ -306,7 +314,7 @@ func (r *libraryRepository) Read(id string) (interface{}, error) {
return r.Get(idInt)
}
-func (r *libraryRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *libraryRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
return r.GetAll(r.parseRestOptions(r.ctx, options...))
}
@@ -314,11 +322,11 @@ func (r *libraryRepository) EntityName() string {
return "library"
}
-func (r *libraryRepository) NewInstance() interface{} {
+func (r *libraryRepository) NewInstance() any {
return &model.Library{}
}
-func (r *libraryRepository) Save(entity interface{}) (string, error) {
+func (r *libraryRepository) Save(entity any) (string, error) {
lib := entity.(*model.Library)
lib.ID = 0 // Reset ID to ensure we create a new library
err := r.Put(lib)
@@ -328,7 +336,7 @@ func (r *libraryRepository) Save(entity interface{}) (string, error) {
return strconv.Itoa(lib.ID), nil
}
-func (r *libraryRepository) Update(id string, entity interface{}, cols ...string) error {
+func (r *libraryRepository) Update(id string, entity any, cols ...string) error {
lib := entity.(*model.Library)
idInt, err := strconv.Atoi(id)
if err != nil {
diff --git a/persistence/library_repository_test.go b/persistence/library_repository_test.go
index 6f4df1beb..3e3972bdb 100644
--- a/persistence/library_repository_test.go
+++ b/persistence/library_repository_test.go
@@ -142,4 +142,62 @@ var _ = Describe("LibraryRepository", func() {
Expect(libAfter.TotalSize).To(Equal(sizeRes.Sum))
Expect(libAfter.TotalDuration).To(Equal(durationRes.Sum))
})
+
+ Describe("ScanBegin and ScanEnd", func() {
+ var lib *model.Library
+
+ BeforeEach(func() {
+ lib = &model.Library{
+ ID: 0,
+ Name: "Test Scan Library",
+ Path: "/music/test-scan",
+ }
+ err := repo.Put(lib)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ DescribeTable("ScanBegin",
+ func(fullScan bool, expectedFullScanInProgress bool) {
+ err := repo.ScanBegin(lib.ID, fullScan)
+ Expect(err).ToNot(HaveOccurred())
+
+ updatedLib, err := repo.Get(lib.ID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updatedLib.LastScanStartedAt).ToNot(BeZero())
+ Expect(updatedLib.FullScanInProgress).To(Equal(expectedFullScanInProgress))
+ },
+ Entry("sets FullScanInProgress to true for full scan", true, true),
+ Entry("sets FullScanInProgress to false for quick scan", false, false),
+ )
+
+ Context("ScanEnd", func() {
+ BeforeEach(func() {
+ err := repo.ScanBegin(lib.ID, true)
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("sets LastScanAt and clears FullScanInProgress and LastScanStartedAt", func() {
+ err := repo.ScanEnd(lib.ID)
+ Expect(err).ToNot(HaveOccurred())
+
+ updatedLib, err := repo.Get(lib.ID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updatedLib.LastScanAt).ToNot(BeZero())
+ Expect(updatedLib.FullScanInProgress).To(BeFalse())
+ Expect(updatedLib.LastScanStartedAt).To(BeZero())
+ })
+
+ It("sets LastScanAt to be after LastScanStartedAt", func() {
+ libBefore, err := repo.Get(lib.ID)
+ Expect(err).ToNot(HaveOccurred())
+
+ err = repo.ScanEnd(lib.ID)
+ Expect(err).ToNot(HaveOccurred())
+
+ libAfter, err := repo.Get(lib.ID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(libAfter.LastScanAt).To(BeTemporally(">=", libBefore.LastScanStartedAt))
+ })
+ })
+ })
})
diff --git a/persistence/mediafile_repository.go b/persistence/mediafile_repository.go
index e7883947a..264778ea0 100644
--- a/persistence/mediafile_repository.go
+++ b/persistence/mediafile_repository.go
@@ -3,13 +3,15 @@ package persistence
import (
"context"
"fmt"
+ "iter"
"slices"
+ "strconv"
+ "strings"
"sync"
"time"
. "github.com/Masterminds/squirrel"
"github.com/deluan/rest"
- "github.com/google/uuid"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
@@ -56,8 +58,11 @@ func (m *dbMediaFile) PostScan() error {
func (m *dbMediaFile) PostMapArgs(args map[string]any) error {
fullText := []string{m.FullTitle(), m.Album, m.Artist, m.AlbumArtist,
m.SortTitle, m.SortAlbumName, m.SortArtistName, m.SortAlbumArtistName, m.DiscSubtitle}
- fullText = append(fullText, m.MediaFile.Participants.AllNames()...)
+ participantNames := m.MediaFile.Participants.AllNames()
+ fullText = append(fullText, participantNames...)
args["full_text"] = formatFullText(fullText...)
+ args["search_participants"] = strings.Join(participantNames, " ")
+ args["search_normalized"] = normalizeForFTS(m.FullTitle(), m.Album, m.Artist, m.AlbumArtist)
args["tags"] = marshalTags(m.MediaFile.Tags)
args["participants"] = marshalParticipants(m.MediaFile.Participants)
return nil
@@ -84,6 +89,7 @@ func NewMediaFileRepository(ctx context.Context, db dbx.Builder) model.MediaFile
"created_at": "media_file.created_at",
"recently_added": mediaFileRecentlyAddedSort(),
"starred_at": "starred, starred_at",
+ "rated_at": "rating, rated_at",
})
return r
}
@@ -92,7 +98,8 @@ var mediaFileFilter = sync.OnceValue(func() map[string]filterFunc {
filters := map[string]filterFunc{
"id": idFilter("media_file"),
"title": fullTextFilter("media_file", "mbz_recording_id", "mbz_release_track_id"),
- "starred": booleanFilter,
+ "starred": annotationBoolFilter("starred"),
+ "has_rating": annotationBoolFilter("rating"),
"genre_id": tagIDFilter,
"missing": booleanFilter,
"artists_id": artistFilter,
@@ -121,12 +128,33 @@ func (r *mediaFileRepository) CountAll(options ...model.QueryOptions) (int64, er
return r.count(query, options...)
}
+func (r *mediaFileRepository) CountBySuffix(options ...model.QueryOptions) (map[string]int64, error) {
+ sel := r.newSelect(options...).
+ Columns("lower(suffix) as suffix", "count(*) as count").
+ GroupBy("lower(suffix)")
+ var res []struct {
+ Suffix string
+ Count int64
+ }
+ err := r.queryAll(sel, &res)
+ if err != nil {
+ return nil, err
+ }
+ counts := make(map[string]int64, len(res))
+ for _, c := range res {
+ counts[c.Suffix] = c.Count
+ }
+ return counts, nil
+}
+
func (r *mediaFileRepository) Exists(id string) (bool, error) {
return r.exists(Eq{"media_file.id": id})
}
func (r *mediaFileRepository) Put(m *model.MediaFile) error {
- m.CreatedAt = time.Now()
+ if m.CreatedAt.IsZero() {
+ m.CreatedAt = time.Now()
+ }
id, err := r.putByMatch(Eq{"path": m.Path, "library_id": m.LibraryID}, m.ID, &dbMediaFile{MediaFile: m})
if err != nil {
return err
@@ -135,6 +163,11 @@ func (r *mediaFileRepository) Put(m *model.MediaFile) error {
return r.updateParticipants(m.ID, m.Participants)
}
+func (r *mediaFileRepository) UpdateProbeData(id string, data string) error {
+ _, err := r.executeSQL(Update(r.tableName).Set("probe_data", data).Where(Eq{"id": id}))
+ return err
+}
+
func (r *mediaFileRepository) selectMediaFile(options ...model.QueryOptions) SelectBuilder {
sql := r.newSelect(options...).Columns("media_file.*", "library.path as library_path", "library.name as library_name").
LeftJoin("library on media_file.library_id = library.id")
@@ -173,31 +206,77 @@ func (r *mediaFileRepository) GetAll(options ...model.QueryOptions) (model.Media
return res.toModels(), nil
}
+func (r *mediaFileRepository) GetAllByTags(tag model.TagName, values []string, options ...model.QueryOptions) (model.MediaFiles, error) {
+ placeholders := make([]string, len(values))
+ args := make([]any, len(values))
+ for i, v := range values {
+ placeholders[i] = "?"
+ args[i] = v
+ }
+ tagFilter := Expr(
+ fmt.Sprintf("exists (select 1 from json_tree(media_file.tags, '$.%s') where key='value' and value in (%s))",
+ tag, strings.Join(placeholders, ",")),
+ args...,
+ )
+
+ var opts model.QueryOptions
+ if len(options) > 0 {
+ opts = options[0]
+ }
+ if opts.Filters != nil {
+ opts.Filters = And{tagFilter, opts.Filters}
+ } else {
+ opts.Filters = tagFilter
+ }
+ return r.GetAll(opts)
+}
+
func (r *mediaFileRepository) GetCursor(options ...model.QueryOptions) (model.MediaFileCursor, error) {
sq := r.selectMediaFile(options...)
cursor, err := queryWithStableResults[dbMediaFile](r.sqlRepository, sq)
if err != nil {
return nil, err
}
- return func(yield func(model.MediaFile, error) bool) {
- for m, err := range cursor {
- if m.MediaFile == nil {
- yield(model.MediaFile{}, fmt.Errorf("unexpected nil mediafile: %v", m))
- return
- }
- if !yield(*m.MediaFile, err) || err != nil {
- return
- }
- }
- }, nil
+ return wrapMediaFileCursor(cursor), nil
}
+// FindByPaths finds media files by their paths.
+// The paths can be library-qualified (format: "libraryID:path") or unqualified ("path").
+// Library-qualified paths search within the specified library, while unqualified paths
+// search across all libraries for backward compatibility.
func (r *mediaFileRepository) FindByPaths(paths []string) (model.MediaFiles, error) {
- sel := r.newSelect().Columns("*").Where(Eq{"path collate nocase": paths})
+ query := Or{}
+
+ for _, path := range paths {
+ parts := strings.SplitN(path, ":", 2)
+ if len(parts) == 2 {
+ // Library-qualified path: "libraryID:path"
+ libraryID, err := strconv.Atoi(parts[0])
+ if err != nil {
+ // Invalid format, skip
+ continue
+ }
+ relativePath := parts[1]
+ query = append(query, And{
+ Eq{"path collate nocase": relativePath},
+ Eq{"library_id": libraryID},
+ })
+ } else {
+ // Unqualified path: search across all libraries
+ query = append(query, Eq{"path collate nocase": path})
+ }
+ }
+
+ if len(query) == 0 {
+ return model.MediaFiles{}, nil
+ }
+
+ sel := r.newSelect().Columns("*").Where(query)
var res dbMediaFiles
if err := r.queryAll(sel, &res); err != nil {
return nil, err
}
+
return res.toModels(), nil
}
@@ -288,25 +367,36 @@ func (r *mediaFileRepository) GetMissingAndMatching(libId int) (model.MediaFileC
if err != nil {
return nil, err
}
+ return wrapMediaFileCursor(cursor), nil
+}
+
+func wrapMediaFileCursor(cursor iter.Seq2[dbMediaFile, error]) model.MediaFileCursor {
return func(yield func(model.MediaFile, error) bool) {
for m, err := range cursor {
+ if m.MediaFile == nil {
+ yield(model.MediaFile{}, fmt.Errorf("unexpected nil mediafile (%v): %w", m, err))
+ return
+ }
if !yield(*m.MediaFile, err) || err != nil {
return
}
}
- }, nil
+ }
}
// FindRecentFilesByMBZTrackID finds recently added files by MusicBrainz Track ID in other libraries
+// It uses a lightweight query without annotation/bookmark joins since those are not needed for matching
func (r *mediaFileRepository) FindRecentFilesByMBZTrackID(missing model.MediaFile, since time.Time) (model.MediaFiles, error) {
- sel := r.selectMediaFile().Where(And{
- NotEq{"media_file.library_id": missing.LibraryID},
- Eq{"media_file.mbz_release_track_id": missing.MbzReleaseTrackID},
- NotEq{"media_file.mbz_release_track_id": ""}, // Exclude empty MBZ Track IDs
- Eq{"media_file.suffix": missing.Suffix},
- Gt{"media_file.created_at": since},
- Eq{"media_file.missing": false},
- }).OrderBy("media_file.created_at DESC")
+ sel := r.newSelect().Columns("media_file.*", "library.path as library_path", "library.name as library_name").
+ LeftJoin("library on media_file.library_id = library.id").
+ Where(And{
+ NotEq{"media_file.library_id": missing.LibraryID},
+ Eq{"media_file.mbz_release_track_id": missing.MbzReleaseTrackID},
+ NotEq{"media_file.mbz_release_track_id": ""}, // Exclude empty MBZ Track IDs
+ Eq{"media_file.suffix": missing.Suffix},
+ Gt{"media_file.created_at": since},
+ Eq{"media_file.missing": false},
+ }).OrderBy("media_file.created_at DESC")
var res dbMediaFiles
err := r.queryAll(sel, &res)
@@ -317,19 +407,22 @@ func (r *mediaFileRepository) FindRecentFilesByMBZTrackID(missing model.MediaFil
}
// FindRecentFilesByProperties finds recently added files by intrinsic properties in other libraries
+// It uses a lightweight query without annotation/bookmark joins since those are not needed for matching
func (r *mediaFileRepository) FindRecentFilesByProperties(missing model.MediaFile, since time.Time) (model.MediaFiles, error) {
- sel := r.selectMediaFile().Where(And{
- NotEq{"media_file.library_id": missing.LibraryID},
- Eq{"media_file.title": missing.Title},
- Eq{"media_file.size": missing.Size},
- Eq{"media_file.suffix": missing.Suffix},
- Eq{"media_file.disc_number": missing.DiscNumber},
- Eq{"media_file.track_number": missing.TrackNumber},
- Eq{"media_file.album": missing.Album},
- Eq{"media_file.mbz_release_track_id": ""}, // Exclude files with MBZ Track ID
- Gt{"media_file.created_at": since},
- Eq{"media_file.missing": false},
- }).OrderBy("media_file.created_at DESC")
+ sel := r.newSelect().Columns("media_file.*", "library.path as library_path", "library.name as library_name").
+ LeftJoin("library on media_file.library_id = library.id").
+ Where(And{
+ NotEq{"media_file.library_id": missing.LibraryID},
+ Eq{"media_file.title": missing.Title},
+ Eq{"media_file.size": missing.Size},
+ Eq{"media_file.suffix": missing.Suffix},
+ Eq{"media_file.disc_number": missing.DiscNumber},
+ Eq{"media_file.track_number": missing.TrackNumber},
+ Eq{"media_file.album": missing.Album},
+ Eq{"media_file.mbz_release_track_id": ""}, // Exclude files with MBZ Track ID
+ Gt{"media_file.created_at": since},
+ Eq{"media_file.missing": false},
+ }).OrderBy("media_file.created_at DESC")
var res dbMediaFiles
err := r.queryAll(sel, &res)
@@ -339,18 +432,21 @@ func (r *mediaFileRepository) FindRecentFilesByProperties(missing model.MediaFil
return res.toModels(), nil
}
-func (r *mediaFileRepository) Search(q string, offset int, size int, options ...model.QueryOptions) (model.MediaFiles, error) {
+var mediaFileSearchConfig = searchConfig{
+ NaturalOrder: "media_file.rowid",
+ OrderBy: []string{"title"},
+ MBIDFields: []string{"mbz_recording_id", "mbz_release_track_id"},
+}
+
+func (r *mediaFileRepository) Search(q string, options ...model.QueryOptions) (model.MediaFiles, error) {
+ var opts model.QueryOptions
+ if len(options) > 0 {
+ opts = options[0]
+ }
var res dbMediaFiles
- if uuid.Validate(q) == nil {
- err := r.searchByMBID(r.selectMediaFile(options...), q, []string{"mbz_recording_id", "mbz_release_track_id"}, &res)
- if err != nil {
- return nil, fmt.Errorf("searching media_file by MBID %q: %w", q, err)
- }
- } else {
- err := r.doSearch(r.selectMediaFile(options...), q, offset, size, &res, "media_file.rowid", "title")
- if err != nil {
- return nil, fmt.Errorf("searching media_file by query %q: %w", q, err)
- }
+ err := r.doSearch(r.selectMediaFile(options...), q, &res, mediaFileSearchConfig, opts)
+ if err != nil {
+ return nil, fmt.Errorf("searching media_file %q: %w", q, err)
}
return res.toModels(), nil
}
@@ -359,11 +455,11 @@ func (r *mediaFileRepository) Count(options ...rest.QueryOptions) (int64, error)
return r.CountAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *mediaFileRepository) Read(id string) (interface{}, error) {
+func (r *mediaFileRepository) Read(id string) (any, error) {
return r.Get(id)
}
-func (r *mediaFileRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *mediaFileRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
return r.GetAll(r.parseRestOptions(r.ctx, options...))
}
@@ -371,7 +467,7 @@ func (r *mediaFileRepository) EntityName() string {
return "mediafile"
}
-func (r *mediaFileRepository) NewInstance() interface{} {
+func (r *mediaFileRepository) NewInstance() any {
return &model.MediaFile{}
}
diff --git a/persistence/mediafile_repository_test.go b/persistence/mediafile_repository_test.go
index 002b82499..5a866379f 100644
--- a/persistence/mediafile_repository_test.go
+++ b/persistence/mediafile_repository_test.go
@@ -2,9 +2,12 @@ package persistence
import (
"context"
+ "errors"
+ "fmt"
"time"
"github.com/Masterminds/squirrel"
+ "github.com/deluan/rest"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
@@ -38,7 +41,45 @@ var _ = Describe("MediaRepository", func() {
})
It("counts the number of mediafiles in the DB", func() {
- Expect(mr.CountAll()).To(Equal(int64(6)))
+ Expect(mr.CountAll()).To(Equal(int64(13)))
+ })
+
+ Describe("CountBySuffix", func() {
+ var mp3File, flacFile1, flacFile2, flacUpperFile model.MediaFile
+
+ BeforeEach(func() {
+ mp3File = model.MediaFile{ID: "suffix-mp3", LibraryID: 1, Suffix: "mp3", Path: "/test/file.mp3"}
+ flacFile1 = model.MediaFile{ID: "suffix-flac1", LibraryID: 1, Suffix: "flac", Path: "/test/file1.flac"}
+ flacFile2 = model.MediaFile{ID: "suffix-flac2", LibraryID: 1, Suffix: "flac", Path: "/test/file2.flac"}
+ flacUpperFile = model.MediaFile{ID: "suffix-FLAC", LibraryID: 1, Suffix: "FLAC", Path: "/test/file.FLAC"}
+
+ Expect(mr.Put(&mp3File)).To(Succeed())
+ Expect(mr.Put(&flacFile1)).To(Succeed())
+ Expect(mr.Put(&flacFile2)).To(Succeed())
+ Expect(mr.Put(&flacUpperFile)).To(Succeed())
+ })
+
+ AfterEach(func() {
+ _ = mr.Delete(mp3File.ID)
+ _ = mr.Delete(flacFile1.ID)
+ _ = mr.Delete(flacFile2.ID)
+ _ = mr.Delete(flacUpperFile.ID)
+ })
+
+ It("counts media files grouped by suffix with lowercase normalization", func() {
+ counts, err := mr.CountBySuffix()
+ Expect(err).ToNot(HaveOccurred())
+
+ // Should have lowercase keys only
+ Expect(counts).To(HaveKey("mp3"))
+ Expect(counts).To(HaveKey("flac"))
+ Expect(counts).ToNot(HaveKey("FLAC"))
+
+ // mp3: 1 file
+ Expect(counts["mp3"]).To(Equal(int64(1)))
+ // flac: 3 files (2 lowercase + 1 uppercase normalized)
+ Expect(counts["flac"]).To(Equal(int64(3)))
+ })
})
It("returns songs ordered by lyrics with a specific title/artist", func() {
@@ -65,6 +106,68 @@ var _ = Describe("MediaRepository", func() {
}
})
+ Describe("Put CreatedAt behavior (#5050)", func() {
+ It("sets CreatedAt to now when inserting a new file with zero CreatedAt", func() {
+ before := time.Now().Add(-time.Second)
+ newFile := model.MediaFile{ID: id.NewRandom(), LibraryID: 1, Path: "/test/created-at-zero.mp3"}
+ Expect(mr.Put(&newFile)).To(Succeed())
+
+ retrieved, err := mr.Get(newFile.ID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(retrieved.CreatedAt).To(BeTemporally(">", before))
+
+ _ = mr.Delete(newFile.ID)
+ })
+
+ It("preserves CreatedAt when inserting a new file with non-zero CreatedAt", func() {
+ originalTime := time.Date(2020, 3, 15, 10, 30, 0, 0, time.UTC)
+ newFile := model.MediaFile{
+ ID: id.NewRandom(),
+ LibraryID: 1,
+ Path: "/test/created-at-preserved.mp3",
+ CreatedAt: originalTime,
+ }
+ Expect(mr.Put(&newFile)).To(Succeed())
+
+ retrieved, err := mr.Get(newFile.ID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(retrieved.CreatedAt).To(BeTemporally("~", originalTime, time.Second))
+
+ _ = mr.Delete(newFile.ID)
+ })
+
+ It("does not reset CreatedAt when updating an existing file", func() {
+ originalTime := time.Date(2019, 6, 1, 12, 0, 0, 0, time.UTC)
+ fileID := id.NewRandom()
+ newFile := model.MediaFile{
+ ID: fileID,
+ LibraryID: 1,
+ Path: "/test/created-at-update.mp3",
+ Title: "Original Title",
+ CreatedAt: originalTime,
+ }
+ Expect(mr.Put(&newFile)).To(Succeed())
+
+ // Update the file with a new title but zero CreatedAt
+ updatedFile := model.MediaFile{
+ ID: fileID,
+ LibraryID: 1,
+ Path: "/test/created-at-update.mp3",
+ Title: "Updated Title",
+ // CreatedAt is zero - should NOT overwrite the stored value
+ }
+ Expect(mr.Put(&updatedFile)).To(Succeed())
+
+ retrieved, err := mr.Get(fileID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(retrieved.Title).To(Equal("Updated Title"))
+ // CreatedAt should still be the original time (not reset)
+ Expect(retrieved.CreatedAt).To(BeTemporally("~", originalTime, time.Second))
+
+ _ = mr.Delete(fileID)
+ })
+ })
+
It("checks existence of mediafiles in the DB", func() {
Expect(mr.Exists(songAntenna.ID)).To(BeTrue())
Expect(mr.Exists("666")).To(BeFalse())
@@ -119,6 +222,74 @@ var _ = Describe("MediaRepository", func() {
Expect(mf.PlayCount).To(Equal(int64(1)))
})
+ Describe("AverageRating", func() {
+ var raw *mediaFileRepository
+
+ BeforeEach(func() {
+ raw = mr.(*mediaFileRepository)
+ })
+
+ It("returns 0 when no ratings exist", func() {
+ newID := id.NewRandom()
+ Expect(mr.Put(&model.MediaFile{LibraryID: 1, ID: newID, Path: "/test/no-rating.mp3"})).To(Succeed())
+
+ mf, err := mr.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mf.AverageRating).To(Equal(0.0))
+
+ _, _ = raw.executeSQL(squirrel.Delete("media_file").Where(squirrel.Eq{"id": newID}))
+ })
+
+ It("returns the user's rating as average when only one user rated", func() {
+ newID := id.NewRandom()
+ Expect(mr.Put(&model.MediaFile{LibraryID: 1, ID: newID, Path: "/test/single-rating.mp3"})).To(Succeed())
+ Expect(mr.SetRating(5, newID)).To(Succeed())
+
+ mf, err := mr.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mf.AverageRating).To(Equal(5.0))
+
+ _, _ = raw.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": newID}))
+ _, _ = raw.executeSQL(squirrel.Delete("media_file").Where(squirrel.Eq{"id": newID}))
+ })
+
+ It("calculates average across multiple users", func() {
+ newID := id.NewRandom()
+ Expect(mr.Put(&model.MediaFile{LibraryID: 1, ID: newID, Path: "/test/multi-rating.mp3"})).To(Succeed())
+
+ Expect(mr.SetRating(3, newID)).To(Succeed())
+
+ user2Ctx := request.WithUser(GinkgoT().Context(), regularUser)
+ user2Repo := NewMediaFileRepository(user2Ctx, GetDBXBuilder())
+ Expect(user2Repo.SetRating(5, newID)).To(Succeed())
+
+ mf, err := mr.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mf.AverageRating).To(Equal(4.0))
+
+ _, _ = raw.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": newID}))
+ _, _ = raw.executeSQL(squirrel.Delete("media_file").Where(squirrel.Eq{"id": newID}))
+ })
+
+ It("excludes zero ratings from average calculation", func() {
+ newID := id.NewRandom()
+ Expect(mr.Put(&model.MediaFile{LibraryID: 1, ID: newID, Path: "/test/zero-excluded.mp3"})).To(Succeed())
+
+ Expect(mr.SetRating(4, newID)).To(Succeed())
+
+ user2Ctx := request.WithUser(GinkgoT().Context(), regularUser)
+ user2Repo := NewMediaFileRepository(user2Ctx, GetDBXBuilder())
+ Expect(user2Repo.SetRating(0, newID)).To(Succeed())
+
+ mf, err := mr.Get(newID)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(mf.AverageRating).To(Equal(4.0))
+
+ _, _ = raw.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": newID}))
+ _, _ = raw.executeSQL(squirrel.Delete("media_file").Where(squirrel.Eq{"id": newID}))
+ })
+ })
+
It("preserves play date if and only if provided date is older", func() {
id := "incplay.playdate"
Expect(mr.Put(&model.MediaFile{LibraryID: 1, ID: id})).To(BeNil())
@@ -203,7 +374,7 @@ var _ = Describe("MediaRepository", func() {
// Update "Old Song": created long ago, updated recently
_, err := db.Update("media_file",
- map[string]interface{}{
+ map[string]any{
"created_at": oldTime,
"updated_at": newTime,
},
@@ -212,7 +383,7 @@ var _ = Describe("MediaRepository", func() {
// Update "Middle Song": created and updated at the same middle time
_, err = db.Update("media_file",
- map[string]interface{}{
+ map[string]any{
"created_at": middleTime,
"updated_at": middleTime,
},
@@ -221,7 +392,7 @@ var _ = Describe("MediaRepository", func() {
// Update "New Song": created recently, updated long ago
_, err = db.Update("media_file",
- map[string]interface{}{
+ map[string]any{
"created_at": newTime,
"updated_at": oldTime,
},
@@ -311,10 +482,54 @@ var _ = Describe("MediaRepository", func() {
})
})
+ Context("Filters", func() {
+ var mfWithoutAnnotation model.MediaFile
+
+ BeforeEach(func() {
+ mfWithoutAnnotation = model.MediaFile{ID: "no-annotation-file", LibraryID: 1, Path: "/test/no-annotation.mp3", Title: "No Annotation"}
+ Expect(mr.Put(&mfWithoutAnnotation)).To(Succeed())
+ })
+
+ AfterEach(func() {
+ _ = mr.Delete(mfWithoutAnnotation.ID)
+ })
+
+ Describe("starred", func() {
+ It("false includes items without annotations", func() {
+ res, err := mr.(model.ResourceRepository).ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"starred": "false"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ files := res.(model.MediaFiles)
+
+ var found bool
+ for _, f := range files {
+ if f.ID == mfWithoutAnnotation.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "MediaFile without annotation should be included in starred=false filter")
+ })
+
+ It("true excludes items without annotations", func() {
+ res, err := mr.(model.ResourceRepository).ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"starred": "true"},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ files := res.(model.MediaFiles)
+
+ for _, f := range files {
+ Expect(f.ID).ToNot(Equal(mfWithoutAnnotation.ID))
+ }
+ })
+ })
+ })
+
Describe("Search", func() {
Context("text search", func() {
It("finds media files by title", func() {
- results, err := mr.Search("Antenna", 0, 10)
+ results, err := mr.Search("Antenna", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(HaveLen(3)) // songAntenna, songAntennaWithLyrics, songAntenna2
for _, result := range results {
@@ -323,7 +538,7 @@ var _ = Describe("MediaRepository", func() {
})
It("finds media files case insensitively", func() {
- results, err := mr.Search("antenna", 0, 10)
+ results, err := mr.Search("antenna", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(HaveLen(3))
for _, result := range results {
@@ -332,7 +547,7 @@ var _ = Describe("MediaRepository", func() {
})
It("returns empty result when no matches found", func() {
- results, err := mr.Search("nonexistent", 0, 10)
+ results, err := mr.Search("nonexistent", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty())
})
@@ -365,7 +580,7 @@ var _ = Describe("MediaRepository", func() {
})
It("finds media file by mbz_recording_id", func() {
- results, err := mr.Search("550e8400-e29b-41d4-a716-446655440020", 0, 10)
+ results, err := mr.Search("550e8400-e29b-41d4-a716-446655440020", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].ID).To(Equal("test-mbid-mediafile"))
@@ -373,7 +588,7 @@ var _ = Describe("MediaRepository", func() {
})
It("finds media file by mbz_release_track_id", func() {
- results, err := mr.Search("550e8400-e29b-41d4-a716-446655440021", 0, 10)
+ results, err := mr.Search("550e8400-e29b-41d4-a716-446655440021", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(HaveLen(1))
Expect(results[0].ID).To(Equal("test-mbid-mediafile"))
@@ -381,7 +596,7 @@ var _ = Describe("MediaRepository", func() {
})
It("returns empty result when MBID is not found", func() {
- results, err := mr.Search("550e8400-e29b-41d4-a716-446655440099", 0, 10)
+ results, err := mr.Search("550e8400-e29b-41d4-a716-446655440099", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty())
})
@@ -401,7 +616,7 @@ var _ = Describe("MediaRepository", func() {
Expect(err).ToNot(HaveOccurred())
// Search never returns missing media files (hardcoded behavior)
- results, err := mr.Search("550e8400-e29b-41d4-a716-446655440022", 0, 10)
+ results, err := mr.Search("550e8400-e29b-41d4-a716-446655440022", model.QueryOptions{Max: 10})
Expect(err).ToNot(HaveOccurred())
Expect(results).To(BeEmpty())
@@ -410,4 +625,132 @@ var _ = Describe("MediaRepository", func() {
})
})
})
+
+ Describe("FindByPaths", func() {
+ // Test fixtures for Unicode and case-sensitivity tests
+ var testFiles []model.MediaFile
+
+ BeforeEach(func() {
+ testFiles = []model.MediaFile{
+ {ID: "findpath-1", LibraryID: 1, Path: "artist/Album/track.mp3", Title: "Track"},
+ {ID: "findpath-2", LibraryID: 1, Path: "artist/Album/UPPER.mp3", Title: "Upper"},
+ // Fullwidth uppercase: ACROSS (U+FF21 U+FF23 U+FF32 U+FF2F U+FF33 U+FF33)
+ {ID: "findpath-3", LibraryID: 1, Path: "plex/02 - ACROSS.flac", Title: "Fullwidth"},
+ // French diacritic: è (U+00E8, can decompose to e + combining grave)
+ {ID: "findpath-4", LibraryID: 1, Path: "artist/Michèle/song.mp3", Title: "French"},
+ }
+ for _, mf := range testFiles {
+ Expect(mr.Put(&mf)).To(Succeed())
+ }
+ })
+
+ AfterEach(func() {
+ for _, mf := range testFiles {
+ _ = mr.Delete(mf.ID)
+ }
+ })
+
+ It("finds files by exact path", func() {
+ results, err := mr.FindByPaths([]string{"1:artist/Album/track.mp3"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].ID).To(Equal("findpath-1"))
+ })
+
+ It("finds files case-insensitively for ASCII characters (NOCASE)", func() {
+ // SQLite's COLLATE NOCASE handles ASCII case-insensitivity
+ results, err := mr.FindByPaths([]string{"1:ARTIST/ALBUM/TRACK.MP3"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].ID).To(Equal("findpath-1"))
+ })
+
+ It("finds fullwidth characters only with exact case match (SQLite NOCASE limitation)", func() {
+ // SQLite's NOCASE does NOT handle fullwidth uppercase/lowercase equivalence
+ // The DB has fullwidth uppercase ACROSS, searching with exact match should work
+ results, err := mr.FindByPaths([]string{"1:plex/02 - ACROSS.flac"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].ID).To(Equal("findpath-3"))
+
+ // Searching with fullwidth lowercase across should NOT match
+ // (this is the SQLite limitation that requires exact matching for non-ASCII)
+ results, err = mr.FindByPaths([]string{"1:plex/02 - across.flac"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty())
+ })
+
+ It("returns multiple files when querying multiple paths", func() {
+ results, err := mr.FindByPaths([]string{
+ "1:artist/Album/track.mp3",
+ "1:artist/Album/UPPER.mp3",
+ })
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(2))
+ })
+
+ It("returns empty slice for non-existent paths", func() {
+ results, err := mr.FindByPaths([]string{"1:nonexistent/path.mp3"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty())
+ })
+
+ It("returns empty slice for empty input", func() {
+ results, err := mr.FindByPaths([]string{})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty())
+ })
+
+ It("handles library-qualified paths correctly", func() {
+ // Library 1 should find the file
+ results, err := mr.FindByPaths([]string{"1:artist/Album/track.mp3"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+
+ // Library 2 should NOT find it (file is in library 1)
+ results, err = mr.FindByPaths([]string{"2:artist/Album/track.mp3"})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty())
+ })
+ })
+
+ Describe("wrapMediaFileCursor", func() {
+ It("does not panic when the cursor yields a dbMediaFile with nil MediaFile", func() {
+ // Simulate what queryWithStableResults does on the rows.Err() path:
+ // it yields a zero-value dbMediaFile (where MediaFile is nil) with an error.
+ dbErr := fmt.Errorf("database is locked")
+ cursor := func(yield func(dbMediaFile, error) bool) {
+ var empty dbMediaFile // MediaFile pointer is nil
+ yield(empty, dbErr)
+ }
+
+ // wrapMediaFileCursor should handle the nil MediaFile without panicking
+ wrappedCursor := wrapMediaFileCursor(cursor)
+ var gotErr error
+ Expect(func() {
+ for _, err := range wrappedCursor {
+ gotErr = err
+ }
+ }).ToNot(Panic())
+ Expect(gotErr).To(HaveOccurred())
+ Expect(gotErr.Error()).To(ContainSubstring("unexpected nil mediafile"))
+ Expect(errors.Is(gotErr, dbErr)).To(BeTrue(), "should wrap the original cursor error")
+ })
+
+ It("yields mediafiles from a valid cursor", func() {
+ mf := &model.MediaFile{ID: "mf1", Title: "Test"}
+ cursor := func(yield func(dbMediaFile, error) bool) {
+ yield(dbMediaFile{MediaFile: mf}, nil)
+ }
+
+ wrappedCursor := wrapMediaFileCursor(cursor)
+ var mediafiles []model.MediaFile
+ for m, err := range wrappedCursor {
+ Expect(err).ToNot(HaveOccurred())
+ mediafiles = append(mediafiles, m)
+ }
+ Expect(mediafiles).To(HaveLen(1))
+ Expect(mediafiles[0].ID).To(Equal("mf1"))
+ })
+ })
})
diff --git a/persistence/persistence.go b/persistence/persistence.go
index ac607f85f..83211bdd5 100644
--- a/persistence/persistence.go
+++ b/persistence/persistence.go
@@ -89,7 +89,15 @@ func (s *SQLStore) ScrobbleBuffer(ctx context.Context) model.ScrobbleBufferRepos
return NewScrobbleBufferRepository(ctx, s.getDBXBuilder())
}
-func (s *SQLStore) Resource(ctx context.Context, m interface{}) model.ResourceRepository {
+func (s *SQLStore) Scrobble(ctx context.Context) model.ScrobbleRepository {
+ return NewScrobbleRepository(ctx, s.getDBXBuilder())
+}
+
+func (s *SQLStore) Plugin(ctx context.Context) model.PluginRepository {
+ return NewPluginRepository(ctx, s.getDBXBuilder())
+}
+
+func (s *SQLStore) Resource(ctx context.Context, m any) model.ResourceRepository {
switch m.(type) {
case model.User:
return s.User(ctx).(model.ResourceRepository)
@@ -113,6 +121,8 @@ func (s *SQLStore) Resource(ctx context.Context, m interface{}) model.ResourceRe
return s.Share(ctx).(model.ResourceRepository)
case model.Tag:
return s.Tag(ctx).(model.ResourceRepository)
+ case model.Plugin:
+ return s.Plugin(ctx).(model.ResourceRepository)
}
log.Error("Resource not implemented", "model", reflect.TypeOf(m).Name())
return nil
@@ -157,7 +167,7 @@ func (s *SQLStore) WithTxImmediate(block func(tx model.DataStore) error, scope .
}, scope...)
}
-func (s *SQLStore) GC(ctx context.Context) error {
+func (s *SQLStore) GC(ctx context.Context, libraryIDs ...int) error {
trace := func(ctx context.Context, msg string, f func() error) func() error {
return func() error {
start := time.Now()
@@ -167,11 +177,17 @@ func (s *SQLStore) GC(ctx context.Context) error {
}
}
+ // If libraryIDs are provided, scope operations to those libraries where possible
+ scoped := len(libraryIDs) > 0
+ if scoped {
+ log.Debug(ctx, "GC: Running selective garbage collection", "libraryIDs", libraryIDs)
+ }
+
err := run.Sequentially(
- trace(ctx, "purge empty albums", func() error { return s.Album(ctx).(*albumRepository).purgeEmpty() }),
+ trace(ctx, "purge empty albums", func() error { return s.Album(ctx).(*albumRepository).purgeEmpty(libraryIDs...) }),
trace(ctx, "purge empty artists", func() error { return s.Artist(ctx).(*artistRepository).purgeEmpty() }),
trace(ctx, "mark missing artists", func() error { return s.Artist(ctx).(*artistRepository).markMissing() }),
- trace(ctx, "purge empty folders", func() error { return s.Folder(ctx).(*folderRepository).purgeEmpty() }),
+ trace(ctx, "purge empty folders", func() error { return s.Folder(ctx).(*folderRepository).purgeEmpty(libraryIDs...) }),
trace(ctx, "clean album annotations", func() error { return s.Album(ctx).(*albumRepository).cleanAnnotations() }),
trace(ctx, "clean artist annotations", func() error { return s.Artist(ctx).(*artistRepository).cleanAnnotations() }),
trace(ctx, "clean media file annotations", func() error { return s.MediaFile(ctx).(*mediaFileRepository).cleanAnnotations() }),
diff --git a/persistence/persistence_suite_test.go b/persistence/persistence_suite_test.go
index 1007d84fe..3ed443129 100644
--- a/persistence/persistence_suite_test.go
+++ b/persistence/persistence_suite_test.go
@@ -5,6 +5,7 @@ import (
"path/filepath"
"testing"
+ "github.com/Masterminds/squirrel"
_ "github.com/mattn/go-sqlite3"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/db"
@@ -56,12 +57,22 @@ func al(al model.Album) model.Album {
return al
}
+func alWithTags(a model.Album, tags model.Tags) model.Album {
+ a = al(a)
+ a.Tags = tags
+ return a
+}
+
var (
- artistKraftwerk = model.Artist{ID: "2", Name: "Kraftwerk", OrderArtistName: "kraftwerk"}
- artistBeatles = model.Artist{ID: "3", Name: "The Beatles", OrderArtistName: "beatles"}
- testArtists = model.Artists{
+ artistKraftwerk = model.Artist{ID: "2", Name: "Kraftwerk", OrderArtistName: "kraftwerk"}
+ artistBeatles = model.Artist{ID: "3", Name: "The Beatles", OrderArtistName: "beatles"}
+ artistCJK = model.Artist{ID: "4", Name: "シートベルツ", SortArtistName: "Seatbelts", OrderArtistName: "seatbelts"}
+ artistPunctuation = model.Artist{ID: "5", Name: "The Roots", OrderArtistName: "roots"}
+ testArtists = model.Artists{
artistKraftwerk,
artistBeatles,
+ artistCJK,
+ artistPunctuation,
}
)
@@ -69,10 +80,19 @@ var (
albumSgtPeppers = al(model.Album{ID: "101", Name: "Sgt Peppers", AlbumArtist: "The Beatles", OrderAlbumName: "sgt peppers", AlbumArtistID: "3", EmbedArtPath: p("/beatles/1/sgt/a day.mp3"), SongCount: 1, MaxYear: 1967})
albumAbbeyRoad = al(model.Album{ID: "102", Name: "Abbey Road", AlbumArtist: "The Beatles", OrderAlbumName: "abbey road", AlbumArtistID: "3", EmbedArtPath: p("/beatles/1/come together.mp3"), SongCount: 1, MaxYear: 1969})
albumRadioactivity = al(model.Album{ID: "103", Name: "Radioactivity", AlbumArtist: "Kraftwerk", OrderAlbumName: "radioactivity", AlbumArtistID: "2", EmbedArtPath: p("/kraft/radio/radio.mp3"), SongCount: 2})
- testAlbums = model.Albums{
+ albumMultiDisc = al(model.Album{ID: "104", Name: "Multi Disc Album", AlbumArtist: "Test Artist", OrderAlbumName: "multi disc album", AlbumArtistID: "1", EmbedArtPath: p("/test/multi/disc1/track1.mp3"), SongCount: 4})
+ albumCJK = al(model.Album{ID: "105", Name: "COWBOY BEBOP", AlbumArtist: "シートベルツ", OrderAlbumName: "cowboy bebop", AlbumArtistID: "4", EmbedArtPath: p("/seatbelts/cowboy-bebop/track1.mp3"), SongCount: 1})
+ albumWithVersion = alWithTags(model.Album{ID: "106", Name: "Abbey Road", AlbumArtist: "The Beatles", OrderAlbumName: "abbey road", AlbumArtistID: "3", EmbedArtPath: p("/beatles/2/come together.mp3"), SongCount: 1, MaxYear: 2019},
+ model.Tags{model.TagAlbumVersion: {"Deluxe Edition"}})
+ albumPunctuation = al(model.Album{ID: "107", Name: "Things Fall Apart", AlbumArtist: "The Roots", OrderAlbumName: "things fall apart", AlbumArtistID: "5", EmbedArtPath: p("/roots/things/track1.mp3"), SongCount: 1})
+ testAlbums = model.Albums{
albumSgtPeppers,
albumAbbeyRoad,
albumRadioactivity,
+ albumMultiDisc,
+ albumCJK,
+ albumWithVersion,
+ albumPunctuation,
}
)
@@ -94,13 +114,28 @@ var (
Lyrics: `[{"lang":"xxx","line":[{"value":"This is a set of lyrics"}],"synced":false}]`,
})
songAntenna2 = mf(model.MediaFile{ID: "1006", Title: "Antenna", ArtistID: "2", Artist: "Kraftwerk", AlbumID: "103"})
- testSongs = model.MediaFiles{
+ // Multi-disc album tracks (intentionally out of order to test sorting)
+ songDisc2Track11 = mf(model.MediaFile{ID: "2001", Title: "Disc 2 Track 11", ArtistID: "1", Artist: "Test Artist", AlbumID: "104", Album: "Multi Disc Album", DiscNumber: 2, TrackNumber: 11, Path: p("/test/multi/disc2/track11.mp3"), OrderAlbumName: "multi disc album", OrderArtistName: "test artist"})
+ songDisc1Track01 = mf(model.MediaFile{ID: "2002", Title: "Disc 1 Track 1", ArtistID: "1", Artist: "Test Artist", AlbumID: "104", Album: "Multi Disc Album", DiscNumber: 1, TrackNumber: 1, Path: p("/test/multi/disc1/track1.mp3"), OrderAlbumName: "multi disc album", OrderArtistName: "test artist"})
+ songDisc2Track01 = mf(model.MediaFile{ID: "2003", Title: "Disc 2 Track 1", ArtistID: "1", Artist: "Test Artist", AlbumID: "104", Album: "Multi Disc Album", DiscNumber: 2, TrackNumber: 1, Path: p("/test/multi/disc2/track1.mp3"), OrderAlbumName: "multi disc album", OrderArtistName: "test artist"})
+ songDisc1Track02 = mf(model.MediaFile{ID: "2004", Title: "Disc 1 Track 2", ArtistID: "1", Artist: "Test Artist", AlbumID: "104", Album: "Multi Disc Album", DiscNumber: 1, TrackNumber: 2, Path: p("/test/multi/disc1/track2.mp3"), OrderAlbumName: "multi disc album", OrderArtistName: "test artist"})
+ songCJK = mf(model.MediaFile{ID: "3001", Title: "プラチナ・ジェット", ArtistID: "4", Artist: "シートベルツ", AlbumID: "105", Album: "COWBOY BEBOP", Path: p("/seatbelts/cowboy-bebop/track1.mp3")})
+ songVersioned = mf(model.MediaFile{ID: "3002", Title: "Come Together", ArtistID: "3", Artist: "The Beatles", AlbumID: "106", Album: "Abbey Road", Path: p("/beatles/2/come together.mp3")})
+ songPunctuation = mf(model.MediaFile{ID: "3003", Title: "!!!!!!!", ArtistID: "5", Artist: "The Roots", AlbumID: "107", Album: "Things Fall Apart", Path: p("/roots/things/track1.mp3")})
+ testSongs = model.MediaFiles{
songDayInALife,
songComeTogether,
songRadioactivity,
songAntenna,
songAntennaWithLyrics,
songAntenna2,
+ songDisc2Track11,
+ songDisc1Track01,
+ songDisc2Track01,
+ songDisc1Track02,
+ songCJK,
+ songVersioned,
+ songPunctuation,
}
)
@@ -119,7 +154,8 @@ var (
var (
adminUser = model.User{ID: "userid", UserName: "userid", Name: "admin", Email: "admin@email.com", IsAdmin: true}
regularUser = model.User{ID: "2222", UserName: "regular-user", Name: "Regular User", Email: "regular@example.com"}
- testUsers = model.Users{adminUser, regularUser}
+ thirdUser = model.User{ID: "3333", UserName: "third-user", Name: "Third User", Email: "third@example.com"}
+ testUsers = model.Users{adminUser, regularUser, thirdUser}
)
func p(path string) string {
@@ -176,6 +212,27 @@ var _ = BeforeSuite(func() {
}
}
+ // Populate album_artists based on the AlbumArtistID relationships in testAlbums
+ artistIDs := map[string]bool{}
+ for _, a := range testArtists {
+ artistIDs[a.ID] = true
+ }
+ for i := range testAlbums {
+ a := testAlbums[i]
+ if a.AlbumArtistID == "" || !artistIDs[a.AlbumArtistID] {
+ continue
+ }
+ _, err := alr.executeSQL(squirrel.Insert("album_artists").SetMap(map[string]any{
+ "album_id": a.ID,
+ "artist_id": a.AlbumArtistID,
+ "role": "artist",
+ "sub_role": "",
+ }))
+ if err != nil {
+ panic(err)
+ }
+ }
+
mr := NewMediaFileRepository(ctx, conn)
for i := range testSongs {
err := mr.Put(&testSongs[i])
diff --git a/persistence/player_repository.go b/persistence/player_repository.go
index 73c820753..6c8339378 100644
--- a/persistence/player_repository.go
+++ b/persistence/player_repository.go
@@ -103,14 +103,14 @@ func (r *playerRepository) Count(options ...rest.QueryOptions) (int64, error) {
return r.CountAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *playerRepository) Read(id string) (interface{}, error) {
+func (r *playerRepository) Read(id string) (any, error) {
sel := r.newRestSelect().Where(Eq{"player.id": id})
var res model.Player
err := r.queryOne(sel, &res)
return &res, err
}
-func (r *playerRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *playerRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
sel := r.newRestSelect(r.parseRestOptions(r.ctx, options...))
res := model.Players{}
err := r.queryAll(sel, &res)
@@ -121,7 +121,7 @@ func (r *playerRepository) EntityName() string {
return "player"
}
-func (r *playerRepository) NewInstance() interface{} {
+func (r *playerRepository) NewInstance() any {
return &model.Player{}
}
@@ -130,7 +130,7 @@ func (r *playerRepository) isPermitted(p *model.Player) bool {
return u.IsAdmin || p.UserId == u.ID
}
-func (r *playerRepository) Save(entity interface{}) (string, error) {
+func (r *playerRepository) Save(entity any) (string, error) {
t := entity.(*model.Player)
if !r.isPermitted(t) {
return "", rest.ErrPermissionDenied
@@ -142,7 +142,7 @@ func (r *playerRepository) Save(entity interface{}) (string, error) {
return id, err
}
-func (r *playerRepository) Update(id string, entity interface{}, cols ...string) error {
+func (r *playerRepository) Update(id string, entity any, cols ...string) error {
t := entity.(*model.Player)
t.ID = id
if !r.isPermitted(t) {
diff --git a/persistence/playlist_repository.go b/persistence/playlist_repository.go
index 046284e1f..8d1bbe0f8 100644
--- a/persistence/playlist_repository.go
+++ b/persistence/playlist_repository.go
@@ -61,14 +61,14 @@ func NewPlaylistRepository(ctx context.Context, db dbx.Builder) model.PlaylistRe
return r
}
-func playlistFilter(_ string, value interface{}) Sqlizer {
+func playlistFilter(_ string, value any) Sqlizer {
return Or{
substringFilter("playlist.name", value),
substringFilter("playlist.comment", value),
}
}
-func smartPlaylistFilter(string, interface{}) Sqlizer {
+func smartPlaylistFilter(string, any) Sqlizer {
return Or{
Eq{"rules": ""},
Eq{"rules": nil},
@@ -96,16 +96,6 @@ func (r *playlistRepository) Exists(id string) (bool, error) {
}
func (r *playlistRepository) Delete(id string) error {
- usr := loggedUser(r.ctx)
- if !usr.IsAdmin {
- pls, err := r.Get(id)
- if err != nil {
- return err
- }
- if pls.OwnerID != usr.ID {
- return rest.ErrPermissionDenied
- }
- }
return r.delete(And{Eq{"id": id}, r.userFilter()})
}
@@ -113,14 +103,6 @@ func (r *playlistRepository) Put(p *model.Playlist) error {
pls := dbPlaylist{Playlist: *p}
if pls.ID == "" {
pls.CreatedAt = time.Now()
- } else {
- ok, err := r.Exists(pls.ID)
- if err != nil {
- return err
- }
- if !ok {
- return model.ErrNotAuthorized
- }
}
pls.UpdatedAt = time.Now()
@@ -132,7 +114,6 @@ func (r *playlistRepository) Put(p *model.Playlist) error {
if p.IsSmartPlaylist() {
// Do not update tracks at this point, as it may take a long time and lock the DB, breaking the scan process
- //r.refreshSmartPlaylist(p)
return nil
}
// Only update tracks if they were specified
@@ -260,10 +241,44 @@ func (r *playlistRepository) refreshSmartPlaylist(pls *model.Playlist) bool {
}
sq := Select("row_number() over (order by "+rules.OrderBy()+") as id", "'"+pls.ID+"' as playlist_id", "media_file.id as media_file_id").
- From("media_file").LeftJoin("annotation on (" +
- "annotation.item_id = media_file.id" +
- " AND annotation.item_type = 'media_file'" +
- " AND annotation.user_id = '" + usr.ID + "')")
+ From("media_file").LeftJoin("annotation on ("+
+ "annotation.item_id = media_file.id"+
+ " AND annotation.item_type = 'media_file'"+
+ " AND annotation.user_id = ?)", usr.ID)
+
+ // Conditionally join album/artist annotation tables only when referenced by criteria or sort
+ requiredJoins := rules.RequiredJoins()
+ sq = r.addSmartPlaylistAnnotationJoins(sq, requiredJoins, usr.ID)
+
+ // Only include media files from libraries the user has access to
+ sq = r.applyLibraryFilter(sq, "media_file")
+
+ // Resolve percentage-based limit to an absolute number before applying criteria
+ if rules.IsPercentageLimit() {
+ // Use only expression-based joins for the COUNT query (sort joins are unnecessary)
+ exprJoins := rules.ExpressionJoins()
+ countSq := Select("count(*) as count").From("media_file").
+ LeftJoin("annotation on ("+
+ "annotation.item_id = media_file.id"+
+ " AND annotation.item_type = 'media_file'"+
+ " AND annotation.user_id = ?)", usr.ID)
+ countSq = r.addSmartPlaylistAnnotationJoins(countSq, exprJoins, usr.ID)
+ countSq = r.applyLibraryFilter(countSq, "media_file")
+ countSq = countSq.Where(rules)
+
+ var res struct{ Count int64 }
+ err = r.queryOne(countSq, &res)
+ if err != nil {
+ log.Error(r.ctx, "Error counting matching tracks for percentage limit", "playlist", pls.Name, "id", pls.ID, err)
+ return false
+ }
+ resolvedLimit := rules.EffectiveLimit(res.Count)
+ log.Debug(r.ctx, "Resolved percentage limit", "playlist", pls.Name, "percent", rules.LimitPercent, "totalMatching", res.Count, "resolvedLimit", resolvedLimit)
+ rules.Limit = resolvedLimit
+ rules.LimitPercent = 0
+ }
+
+ // Apply the criteria rules
sq = r.addCriteria(sq, rules)
insSql := Insert("playlist_tracks").Columns("id", "playlist_id", "media_file_id").Select(sq)
_, err = r.executeSQL(insSql)
@@ -280,18 +295,37 @@ func (r *playlistRepository) refreshSmartPlaylist(pls *model.Playlist) bool {
}
// Update when the playlist was last refreshed (for cache purposes)
- updSql := Update(r.tableName).Set("evaluated_at", time.Now()).Where(Eq{"id": pls.ID})
+ now := time.Now()
+ updSql := Update(r.tableName).Set("evaluated_at", now).Where(Eq{"id": pls.ID})
_, err = r.executeSQL(updSql)
if err != nil {
log.Error(r.ctx, "Error updating smart playlist", "playlist", pls.Name, "id", pls.ID, err)
return false
}
+ pls.EvaluatedAt = &now
+
log.Debug(r.ctx, "Refreshed playlist", "playlist", pls.Name, "id", pls.ID, "numTracks", pls.SongCount, "elapsed", time.Since(start))
return true
}
+func (r *playlistRepository) addSmartPlaylistAnnotationJoins(sq SelectBuilder, joins criteria.JoinType, userID string) SelectBuilder {
+ if joins.Has(criteria.JoinAlbumAnnotation) {
+ sq = sq.LeftJoin("annotation AS album_annotation ON ("+
+ "album_annotation.item_id = media_file.album_id"+
+ " AND album_annotation.item_type = 'album'"+
+ " AND album_annotation.user_id = ?)", userID)
+ }
+ if joins.Has(criteria.JoinArtistAnnotation) {
+ sq = sq.LeftJoin("annotation AS artist_annotation ON ("+
+ "artist_annotation.item_id = media_file.artist_id"+
+ " AND artist_annotation.item_type = 'artist'"+
+ " AND artist_annotation.user_id = ?)", userID)
+ }
+ return sq
+}
+
func (r *playlistRepository) addCriteria(sql SelectBuilder, c criteria.Criteria) SelectBuilder {
sql = sql.Where(c)
if c.Limit > 0 {
@@ -312,10 +346,6 @@ func (r *playlistRepository) updateTracks(id string, tracks model.MediaFiles) er
}
func (r *playlistRepository) updatePlaylist(playlistId string, mediaFileIds []string) error {
- if !r.isWritable(playlistId) {
- return rest.ErrPermissionDenied
- }
-
// Remove old tracks
del := Delete("playlist_tracks").Where(Eq{"playlist_id": playlistId})
_, err := r.executeSQL(del)
@@ -388,6 +418,7 @@ func (r *playlistRepository) loadTracks(sel SelectBuilder, id string) (model.Pla
"coalesce(play_count, 0) as play_count",
"play_date",
"coalesce(rating, 0) as rating",
+ "rated_at",
"f.*",
"playlist_tracks.*",
"library.path as library_path",
@@ -412,11 +443,11 @@ func (r *playlistRepository) Count(options ...rest.QueryOptions) (int64, error)
return r.CountAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *playlistRepository) Read(id string) (interface{}, error) {
+func (r *playlistRepository) Read(id string) (any, error) {
return r.Get(id)
}
-func (r *playlistRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *playlistRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
return r.GetAll(r.parseRestOptions(r.ctx, options...))
}
@@ -424,14 +455,13 @@ func (r *playlistRepository) EntityName() string {
return "playlist"
}
-func (r *playlistRepository) NewInstance() interface{} {
+func (r *playlistRepository) NewInstance() any {
return &model.Playlist{}
}
-func (r *playlistRepository) Save(entity interface{}) (string, error) {
+func (r *playlistRepository) Save(entity any) (string, error) {
pls := entity.(*model.Playlist)
- pls.OwnerID = loggedUser(r.ctx).ID
- pls.ID = "" // Make sure we don't override an existing playlist
+ pls.ID = "" // Force new creation
err := r.Put(pls)
if err != nil {
return "", err
@@ -439,26 +469,11 @@ func (r *playlistRepository) Save(entity interface{}) (string, error) {
return pls.ID, err
}
-func (r *playlistRepository) Update(id string, entity interface{}, cols ...string) error {
+func (r *playlistRepository) Update(id string, entity any, cols ...string) error {
pls := dbPlaylist{Playlist: *entity.(*model.Playlist)}
- current, err := r.Get(id)
- if err != nil {
- return err
- }
- usr := loggedUser(r.ctx)
- if !usr.IsAdmin {
- // Only the owner can update the playlist
- if current.OwnerID != usr.ID {
- return rest.ErrPermissionDenied
- }
- // Regular users can't change the ownership of a playlist
- if pls.OwnerID != "" && pls.OwnerID != usr.ID {
- return rest.ErrPermissionDenied
- }
- }
pls.ID = id
pls.UpdatedAt = time.Now()
- _, err = r.put(id, pls, append(cols, "updatedAt")...)
+ _, err := r.put(id, pls, append(cols, "updatedAt")...)
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
@@ -498,23 +513,31 @@ func (r *playlistRepository) removeOrphans() error {
return nil
}
+// renumber updates the position of all tracks in the playlist to be sequential starting from 1, ordered by their
+// current position. This is needed after removing orphan tracks, to ensure there are no gaps in the track numbering.
+// The two-step approach (negate then reassign via CTE) avoids UNIQUE constraint violations on (playlist_id, id).
func (r *playlistRepository) renumber(id string) error {
- var ids []string
- sq := Select("media_file_id").From("playlist_tracks").Where(Eq{"playlist_id": id}).OrderBy("id")
- err := r.queryAllSlice(sq, &ids)
+ // Step 1: Negate all IDs to clear the positive ID space
+ _, err := r.executeSQL(Expr(
+ `UPDATE playlist_tracks SET id = -id WHERE playlist_id = ? AND id > 0`, id))
if err != nil {
return err
}
- return r.updatePlaylist(id, ids)
-}
-
-func (r *playlistRepository) isWritable(playlistId string) bool {
- usr := loggedUser(r.ctx)
- if usr.IsAdmin {
- return true
+ // Step 2: Assign new sequential positive IDs using UPDATE...FROM with a CTE.
+ // The CTE is fully materialized before the UPDATE begins, avoiding self-referencing issues.
+ // ORDER BY id DESC restores original order since IDs are now negative.
+ _, err = r.executeSQL(Expr(
+ `WITH new_ids AS (
+ SELECT rowid as rid, ROW_NUMBER() OVER (ORDER BY id DESC) as new_id
+ FROM playlist_tracks WHERE playlist_id = ?
+ )
+ UPDATE playlist_tracks SET id = new_ids.new_id
+ FROM new_ids
+ WHERE playlist_tracks.rowid = new_ids.rid AND playlist_tracks.playlist_id = ?`, id, id))
+ if err != nil {
+ return err
}
- pls, err := r.Get(playlistId)
- return err == nil && pls.OwnerID == usr.ID
+ return r.refreshCounters(&model.Playlist{ID: id})
}
var _ model.PlaylistRepository = (*playlistRepository)(nil)
diff --git a/persistence/playlist_repository_test.go b/persistence/playlist_repository_test.go
index 15ae438d9..c091cb32b 100644
--- a/persistence/playlist_repository_test.go
+++ b/persistence/playlist_repository_test.go
@@ -1,23 +1,24 @@
package persistence
import (
- "context"
"time"
"github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/criteria"
"github.com/navidrome/navidrome/model/request"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
+ "github.com/pocketbase/dbx"
)
var _ = Describe("PlaylistRepository", func() {
var repo model.PlaylistRepository
BeforeEach(func() {
- ctx := log.NewContext(context.TODO())
+ ctx := log.NewContext(GinkgoT().Context())
ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: true})
repo = NewPlaylistRepository(ctx, GetDBXBuilder())
})
@@ -160,14 +161,23 @@ var _ = Describe("PlaylistRepository", func() {
})
})
- // TODO Validate these tests
- XContext("child smart playlists", func() {
- When("refresh day has expired", func() {
+ Context("child smart playlists", func() {
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ })
+
+ When("refresh delay has expired", func() {
It("should refresh tracks for smart playlist referenced in parent smart playlist criteria", func() {
conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second
- nestedPls := model.Playlist{Name: "Nested", OwnerID: "userid", Rules: rules}
+ childRules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.Contains{"title": "Day"},
+ },
+ }
+ nestedPls := model.Playlist{Name: "Nested", OwnerID: "userid", Public: true, Rules: childRules}
Expect(repo.Put(&nestedPls)).To(Succeed())
+ DeferCleanup(func() { _ = repo.Delete(nestedPls.ID) })
parentPls := model.Playlist{Name: "Parent", OwnerID: "userid", Rules: &criteria.Criteria{
Expression: criteria.All{
@@ -175,48 +185,524 @@ var _ = Describe("PlaylistRepository", func() {
},
}}
Expect(repo.Put(&parentPls)).To(Succeed())
+ DeferCleanup(func() { _ = repo.Delete(parentPls.ID) })
+ // Nested playlist has not been evaluated yet
nestedPlsRead, err := repo.Get(nestedPls.ID)
Expect(err).ToNot(HaveOccurred())
+ Expect(nestedPlsRead.EvaluatedAt).To(BeNil())
- _, err = repo.GetWithTracks(parentPls.ID, true, false)
+ // Getting parent with refresh should recursively refresh the nested playlist
+ pls, err := repo.GetWithTracks(parentPls.ID, true, false)
Expect(err).ToNot(HaveOccurred())
+ Expect(pls.EvaluatedAt).ToNot(BeNil())
+ Expect(*pls.EvaluatedAt).To(BeTemporally("~", time.Now(), 2*time.Second))
- // Check that the nested playlist was refreshed by parent get by verifying evaluatedAt is updated since first nestedPls get
+ // Parent should have tracks from the nested playlist
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].MediaFileID).To(Equal(songDayInALife.ID))
+
+ // Nested playlist should now have been refreshed (EvaluatedAt set)
nestedPlsAfterParentGet, err := repo.Get(nestedPls.ID)
Expect(err).ToNot(HaveOccurred())
-
- Expect(*nestedPlsAfterParentGet.EvaluatedAt).To(BeTemporally(">", *nestedPlsRead.EvaluatedAt))
+ Expect(nestedPlsAfterParentGet.EvaluatedAt).ToNot(BeNil())
+ Expect(*nestedPlsAfterParentGet.EvaluatedAt).To(BeTemporally("~", time.Now(), 2*time.Second))
})
})
- When("refresh day has not expired", func() {
+ When("refresh delay has not expired", func() {
It("should NOT refresh tracks for smart playlist referenced in parent smart playlist criteria", func() {
conf.Server.SmartPlaylistRefreshDelay = 1 * time.Hour
+ childEvaluatedAt := time.Now().Add(-30 * time.Minute)
- nestedPls := model.Playlist{Name: "Nested", OwnerID: "userid", Rules: rules}
+ childRules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.Contains{"title": "Day"},
+ },
+ }
+ nestedPls := model.Playlist{Name: "Nested", OwnerID: "userid", Public: true, Rules: childRules, EvaluatedAt: &childEvaluatedAt}
Expect(repo.Put(&nestedPls)).To(Succeed())
+ DeferCleanup(func() { _ = repo.Delete(nestedPls.ID) })
+ // Parent has no EvaluatedAt, so it WILL refresh, but the child should not
parentPls := model.Playlist{Name: "Parent", OwnerID: "userid", Rules: &criteria.Criteria{
Expression: criteria.All{
criteria.InPlaylist{"id": nestedPls.ID},
},
}}
Expect(repo.Put(&parentPls)).To(Succeed())
+ DeferCleanup(func() { _ = repo.Delete(parentPls.ID) })
nestedPlsRead, err := repo.Get(nestedPls.ID)
Expect(err).ToNot(HaveOccurred())
- _, err = repo.GetWithTracks(parentPls.ID, true, false)
+ // Getting parent with refresh should NOT recursively refresh the nested playlist
+ parent, err := repo.GetWithTracks(parentPls.ID, true, false)
Expect(err).ToNot(HaveOccurred())
- // Check that the nested playlist was not refreshed by parent get by verifying evaluatedAt is not updated since first nestedPls get
+ // Parent should have been refreshed (its EvaluatedAt was nil)
+ Expect(parent.EvaluatedAt).ToNot(BeNil())
+ Expect(*parent.EvaluatedAt).To(BeTemporally("~", time.Now(), 2*time.Second))
+
+ // Nested playlist should NOT have been refreshed (still within delay window)
nestedPlsAfterParentGet, err := repo.Get(nestedPls.ID)
Expect(err).ToNot(HaveOccurred())
-
+ Expect(*nestedPlsAfterParentGet.EvaluatedAt).To(BeTemporally("~", childEvaluatedAt, time.Second))
Expect(*nestedPlsAfterParentGet.EvaluatedAt).To(Equal(*nestedPlsRead.EvaluatedAt))
})
})
})
})
+
+ Describe("Playlist Track Sorting", func() {
+ var testPlaylistID string
+
+ AfterEach(func() {
+ if testPlaylistID != "" {
+ Expect(repo.Delete(testPlaylistID)).To(BeNil())
+ testPlaylistID = ""
+ }
+ })
+
+ It("sorts tracks correctly by album (disc and track number)", func() {
+ By("creating a playlist with multi-disc album tracks in arbitrary order")
+ newPls := model.Playlist{Name: "Multi-Disc Test", OwnerID: "userid"}
+ // Add tracks in intentionally scrambled order
+ newPls.AddMediaFilesByID([]string{"2001", "2002", "2003", "2004"})
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ By("retrieving tracks sorted by album")
+ tracksRepo := repo.Tracks(newPls.ID, false)
+ tracks, err := tracksRepo.GetAll(model.QueryOptions{Sort: "album", Order: "asc"})
+ Expect(err).ToNot(HaveOccurred())
+
+ By("verifying tracks are sorted by disc number then track number")
+ Expect(tracks).To(HaveLen(4))
+ // Expected order: Disc 1 Track 1, Disc 1 Track 2, Disc 2 Track 1, Disc 2 Track 11
+ Expect(tracks[0].MediaFileID).To(Equal("2002")) // Disc 1, Track 1
+ Expect(tracks[1].MediaFileID).To(Equal("2004")) // Disc 1, Track 2
+ Expect(tracks[2].MediaFileID).To(Equal("2003")) // Disc 2, Track 1
+ Expect(tracks[3].MediaFileID).To(Equal("2001")) // Disc 2, Track 11
+ })
+ })
+
+ Describe("Smart Playlists with Album/Artist Annotation Criteria", func() {
+ var testPlaylistID string
+
+ AfterEach(func() {
+ if testPlaylistID != "" {
+ _ = repo.Delete(testPlaylistID)
+ testPlaylistID = ""
+ }
+ })
+
+ It("matches tracks from starred albums using albumLoved", func() {
+ // albumRadioactivity (ID "103") is starred in test fixtures
+ // Songs in album 103: 1003, 1004, 1005, 1006
+ rules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.Is{"albumLoved": true},
+ },
+ }
+ newPls := model.Playlist{Name: "Starred Album Songs", OwnerID: "userid", Rules: rules}
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second
+ pls, err := repo.GetWithTracks(newPls.ID, true, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ trackIDs := make([]string, len(pls.Tracks))
+ for i, t := range pls.Tracks {
+ trackIDs[i] = t.MediaFileID
+ }
+ Expect(trackIDs).To(ConsistOf("1003", "1004", "1005", "1006"))
+ })
+
+ It("matches tracks from starred artists using artistLoved", func() {
+ // artistBeatles (ID "3") is starred in test fixtures
+ // Songs with ArtistID "3": 1001, 1002, 3002
+ rules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.Is{"artistLoved": true},
+ },
+ }
+ newPls := model.Playlist{Name: "Starred Artist Songs", OwnerID: "userid", Rules: rules}
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second
+ pls, err := repo.GetWithTracks(newPls.ID, true, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ trackIDs := make([]string, len(pls.Tracks))
+ for i, t := range pls.Tracks {
+ trackIDs[i] = t.MediaFileID
+ }
+ Expect(trackIDs).To(ConsistOf("1001", "1002", "3002"))
+ })
+
+ It("matches tracks with combined album and artist criteria", func() {
+ // albumLoved=true → songs from album 103 (1003, 1004, 1005, 1006)
+ // artistLoved=true → songs with artist 3 (1001, 1002)
+ // Using Any: union of both sets
+ rules := &criteria.Criteria{
+ Expression: criteria.Any{
+ criteria.Is{"albumLoved": true},
+ criteria.Is{"artistLoved": true},
+ },
+ }
+ newPls := model.Playlist{Name: "Combined Album+Artist", OwnerID: "userid", Rules: rules}
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second
+ pls, err := repo.GetWithTracks(newPls.ID, true, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ trackIDs := make([]string, len(pls.Tracks))
+ for i, t := range pls.Tracks {
+ trackIDs[i] = t.MediaFileID
+ }
+ Expect(trackIDs).To(ConsistOf("1001", "1002", "1003", "1004", "1005", "1006", "3002"))
+ })
+
+ It("returns no tracks when no albums/artists match", func() {
+ // No album has rating 5 in fixtures
+ rules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.Is{"albumRating": 5},
+ },
+ }
+ newPls := model.Playlist{Name: "No Match", OwnerID: "userid", Rules: rules}
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second
+ pls, err := repo.GetWithTracks(newPls.ID, true, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(pls.Tracks).To(BeEmpty())
+ })
+ })
+
+ Describe("Smart Playlists with Tag Criteria", func() {
+ var mfRepo model.MediaFileRepository
+ var testPlaylistID string
+ var songWithGrouping, songWithoutGrouping model.MediaFile
+
+ BeforeEach(func() {
+ ctx := log.NewContext(GinkgoT().Context())
+ ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: true})
+ mfRepo = NewMediaFileRepository(ctx, GetDBXBuilder())
+
+ // Register 'grouping' as a valid tag for smart playlists
+ criteria.AddTagNames([]string{"grouping"})
+
+ // Create a song with the grouping tag
+ songWithGrouping = model.MediaFile{
+ ID: "test-grouping-1",
+ Title: "Song With Grouping",
+ Artist: "Test Artist",
+ ArtistID: "1",
+ Album: "Test Album",
+ AlbumID: "101",
+ Path: "/test/grouping/song1.mp3",
+ Tags: model.Tags{
+ "grouping": []string{"My Crate"},
+ },
+ Participants: model.Participants{},
+ LibraryID: 1,
+ Lyrics: "[]",
+ }
+ Expect(mfRepo.Put(&songWithGrouping)).To(Succeed())
+
+ // Create a song without the grouping tag
+ songWithoutGrouping = model.MediaFile{
+ ID: "test-grouping-2",
+ Title: "Song Without Grouping",
+ Artist: "Test Artist",
+ ArtistID: "1",
+ Album: "Test Album",
+ AlbumID: "101",
+ Path: "/test/grouping/song2.mp3",
+ Tags: model.Tags{},
+ Participants: model.Participants{},
+ LibraryID: 1,
+ Lyrics: "[]",
+ }
+ Expect(mfRepo.Put(&songWithoutGrouping)).To(Succeed())
+ })
+
+ AfterEach(func() {
+ if testPlaylistID != "" {
+ _ = repo.Delete(testPlaylistID)
+ testPlaylistID = ""
+ }
+ // Clean up test media files
+ _, _ = GetDBXBuilder().Delete("media_file", dbx.HashExp{"id": "test-grouping-1"}).Execute()
+ _, _ = GetDBXBuilder().Delete("media_file", dbx.HashExp{"id": "test-grouping-2"}).Execute()
+ })
+
+ It("matches tracks with a tag value using 'contains' with empty string (issue #4728 workaround)", func() {
+ By("creating a smart playlist that checks if grouping tag has any value")
+ // This is the workaround for issue #4728: using 'contains' with empty string
+ // generates SQL: value LIKE '%%' which matches any non-empty string
+ rules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.Contains{"grouping": ""},
+ },
+ }
+ newPls := model.Playlist{Name: "Tracks with Grouping", OwnerID: "userid", Rules: rules}
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ By("refreshing the smart playlist")
+ conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second // Force refresh
+ pls, err := repo.GetWithTracks(newPls.ID, true, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ By("verifying only the track with grouping tag is matched")
+ Expect(pls.Tracks).To(HaveLen(1))
+ Expect(pls.Tracks[0].MediaFileID).To(Equal(songWithGrouping.ID))
+ })
+
+ It("excludes tracks with a tag value using 'notContains' with empty string", func() {
+ By("creating a smart playlist that checks if grouping tag is NOT set")
+ rules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.NotContains{"grouping": ""},
+ },
+ }
+ newPls := model.Playlist{Name: "Tracks without Grouping", OwnerID: "userid", Rules: rules}
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ By("refreshing the smart playlist")
+ conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second // Force refresh
+ pls, err := repo.GetWithTracks(newPls.ID, true, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ By("verifying the track with grouping is NOT in the playlist")
+ for _, track := range pls.Tracks {
+ Expect(track.MediaFileID).ToNot(Equal(songWithGrouping.ID))
+ }
+
+ By("verifying the track without grouping IS in the playlist")
+ var foundWithoutGrouping bool
+ for _, track := range pls.Tracks {
+ if track.MediaFileID == songWithoutGrouping.ID {
+ foundWithoutGrouping = true
+ break
+ }
+ }
+ Expect(foundWithoutGrouping).To(BeTrue())
+ })
+ })
+
+ Describe("Track Deletion and Renumbering", func() {
+ var testPlaylistID string
+
+ AfterEach(func() {
+ if testPlaylistID != "" {
+ Expect(repo.Delete(testPlaylistID)).To(BeNil())
+ testPlaylistID = ""
+ }
+ })
+
+ // helper to get track positions and media file IDs
+ getTrackInfo := func(playlistID string) (ids []string, mediaFileIDs []string) {
+ pls, err := repo.GetWithTracks(playlistID, false, false)
+ Expect(err).ToNot(HaveOccurred())
+ for _, t := range pls.Tracks {
+ ids = append(ids, t.ID)
+ mediaFileIDs = append(mediaFileIDs, t.MediaFileID)
+ }
+ return
+ }
+
+ It("renumbers correctly after deleting a track from the middle", func() {
+ By("creating a playlist with 4 tracks")
+ newPls := model.Playlist{Name: "Renumber Test Middle", OwnerID: "userid"}
+ newPls.AddMediaFilesByID([]string{"1001", "1002", "1003", "1004"})
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ By("deleting the second track (position 2)")
+ tracksRepo := repo.Tracks(newPls.ID, false)
+ Expect(tracksRepo.Delete("2")).To(Succeed())
+
+ By("verifying remaining tracks are renumbered sequentially")
+ ids, mediaFileIDs := getTrackInfo(newPls.ID)
+ Expect(ids).To(Equal([]string{"1", "2", "3"}))
+ Expect(mediaFileIDs).To(Equal([]string{"1001", "1003", "1004"}))
+ })
+
+ It("renumbers correctly after deleting the first track", func() {
+ By("creating a playlist with 3 tracks")
+ newPls := model.Playlist{Name: "Renumber Test First", OwnerID: "userid"}
+ newPls.AddMediaFilesByID([]string{"1001", "1002", "1003"})
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ By("deleting the first track (position 1)")
+ tracksRepo := repo.Tracks(newPls.ID, false)
+ Expect(tracksRepo.Delete("1")).To(Succeed())
+
+ By("verifying remaining tracks are renumbered sequentially")
+ ids, mediaFileIDs := getTrackInfo(newPls.ID)
+ Expect(ids).To(Equal([]string{"1", "2"}))
+ Expect(mediaFileIDs).To(Equal([]string{"1002", "1003"}))
+ })
+
+ It("renumbers correctly after deleting the last track", func() {
+ By("creating a playlist with 3 tracks")
+ newPls := model.Playlist{Name: "Renumber Test Last", OwnerID: "userid"}
+ newPls.AddMediaFilesByID([]string{"1001", "1002", "1003"})
+ Expect(repo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ By("deleting the last track (position 3)")
+ tracksRepo := repo.Tracks(newPls.ID, false)
+ Expect(tracksRepo.Delete("3")).To(Succeed())
+
+ By("verifying remaining tracks are renumbered sequentially")
+ ids, mediaFileIDs := getTrackInfo(newPls.ID)
+ Expect(ids).To(Equal([]string{"1", "2"}))
+ Expect(mediaFileIDs).To(Equal([]string{"1001", "1002"}))
+ })
+ })
+
+ Describe("Smart Playlists Library Filtering", func() {
+ var mfRepo model.MediaFileRepository
+ var testPlaylistID string
+ var lib2ID int
+ var restrictedUserID string
+ var uniqueLibPath string
+
+ BeforeEach(func() {
+ db := GetDBXBuilder()
+
+ // Generate unique IDs for this test run
+ uniqueSuffix := time.Now().Format("20060102150405.000")
+ restrictedUserID = "restricted-user-" + uniqueSuffix
+ uniqueLibPath = "/music/lib2-" + uniqueSuffix
+
+ // Create a second library with unique name and path to avoid conflicts with other tests
+ _, err := db.DB().Exec("INSERT INTO library (name, path, created_at, updated_at) VALUES (?, ?, datetime('now'), datetime('now'))", "Library 2-"+uniqueSuffix, uniqueLibPath)
+ Expect(err).ToNot(HaveOccurred())
+ err = db.DB().QueryRow("SELECT last_insert_rowid()").Scan(&lib2ID)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Create a restricted user with access only to library 1
+ _, err = db.DB().Exec("INSERT INTO user (id, user_name, name, is_admin, password, created_at, updated_at) VALUES (?, ?, 'Restricted User', false, 'pass', datetime('now'), datetime('now'))", restrictedUserID, restrictedUserID)
+ Expect(err).ToNot(HaveOccurred())
+ _, err = db.DB().Exec("INSERT INTO user_library (user_id, library_id) VALUES (?, 1)", restrictedUserID)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Create test media files in each library
+ ctx := log.NewContext(GinkgoT().Context())
+ ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: true})
+ mfRepo = NewMediaFileRepository(ctx, db)
+
+ // Song in library 1 (accessible by restricted user)
+ songLib1 := model.MediaFile{
+ ID: "lib1-song",
+ Title: "Song in Lib1",
+ Artist: "Test Artist",
+ ArtistID: "1",
+ Album: "Test Album",
+ AlbumID: "101",
+ Path: "/music/lib1/song.mp3",
+ LibraryID: 1,
+ Participants: model.Participants{},
+ Tags: model.Tags{},
+ Lyrics: "[]",
+ }
+ Expect(mfRepo.Put(&songLib1)).To(Succeed())
+
+ // Song in library 2 (NOT accessible by restricted user)
+ songLib2 := model.MediaFile{
+ ID: "lib2-song",
+ Title: "Song in Lib2",
+ Artist: "Test Artist",
+ ArtistID: "1",
+ Album: "Test Album",
+ AlbumID: "101",
+ Path: uniqueLibPath + "/song.mp3",
+ LibraryID: lib2ID,
+ Participants: model.Participants{},
+ Tags: model.Tags{},
+ Lyrics: "[]",
+ }
+ Expect(mfRepo.Put(&songLib2)).To(Succeed())
+ })
+
+ AfterEach(func() {
+ db := GetDBXBuilder()
+ if testPlaylistID != "" {
+ _ = repo.Delete(testPlaylistID)
+ testPlaylistID = ""
+ }
+ // Clean up test data
+ _, _ = db.Delete("media_file", dbx.HashExp{"id": "lib1-song"}).Execute()
+ _, _ = db.Delete("media_file", dbx.HashExp{"id": "lib2-song"}).Execute()
+ _, _ = db.Delete("user_library", dbx.HashExp{"user_id": restrictedUserID}).Execute()
+ _, _ = db.Delete("user", dbx.HashExp{"id": restrictedUserID}).Execute()
+ _, _ = db.DB().Exec("DELETE FROM library WHERE id = ?", lib2ID)
+ })
+
+ It("should only include tracks from libraries the user has access to (issue #4738)", func() {
+ db := GetDBXBuilder()
+ ctx := log.NewContext(GinkgoT().Context())
+
+ // Create the smart playlist as the restricted user
+ restrictedUser := model.User{ID: restrictedUserID, UserName: restrictedUserID, IsAdmin: false}
+ ctx = request.WithUser(ctx, restrictedUser)
+ restrictedRepo := NewPlaylistRepository(ctx, db)
+
+ // Create a smart playlist that matches all songs
+ rules := &criteria.Criteria{
+ Expression: criteria.All{
+ criteria.Gt{"playCount": -1}, // Matches everything
+ },
+ }
+ newPls := model.Playlist{Name: "All Songs", OwnerID: restrictedUserID, Rules: rules}
+ Expect(restrictedRepo.Put(&newPls)).To(Succeed())
+ testPlaylistID = newPls.ID
+
+ By("refreshing the smart playlist")
+ conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second // Force refresh
+ pls, err := restrictedRepo.GetWithTracks(newPls.ID, true, false)
+ Expect(err).ToNot(HaveOccurred())
+
+ By("verifying only the track from library 1 is in the playlist")
+ var foundLib1Song, foundLib2Song bool
+ for _, track := range pls.Tracks {
+ if track.MediaFileID == "lib1-song" {
+ foundLib1Song = true
+ }
+ if track.MediaFileID == "lib2-song" {
+ foundLib2Song = true
+ }
+ }
+ Expect(foundLib1Song).To(BeTrue(), "Song from library 1 should be in the playlist")
+ Expect(foundLib2Song).To(BeFalse(), "Song from library 2 should NOT be in the playlist")
+
+ By("verifying playlist_tracks table only contains the accessible track")
+ var playlistTracksCount int
+ err = db.DB().QueryRow("SELECT count(*) FROM playlist_tracks WHERE playlist_id = ?", newPls.ID).Scan(&playlistTracksCount)
+ Expect(err).ToNot(HaveOccurred())
+ // Count should only include tracks visible to the user (lib1-song)
+ // The count may include other test songs from library 1, but NOT lib2-song
+ var lib2TrackCount int
+ err = db.DB().QueryRow("SELECT count(*) FROM playlist_tracks WHERE playlist_id = ? AND media_file_id = 'lib2-song'", newPls.ID).Scan(&lib2TrackCount)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(lib2TrackCount).To(Equal(0), "lib2-song should not be in playlist_tracks")
+
+ By("verifying SongCount matches visible tracks")
+ Expect(pls.SongCount).To(Equal(len(pls.Tracks)), "SongCount should match the number of visible tracks")
+ })
+ })
})
diff --git a/persistence/playlist_track_repository.go b/persistence/playlist_track_repository.go
index 01eec0d02..1a7062cc2 100644
--- a/persistence/playlist_track_repository.go
+++ b/persistence/playlist_track_repository.go
@@ -55,7 +55,7 @@ func (r *playlistRepository) Tracks(playlistId string, refreshSmartPlaylist bool
"id": "playlist_tracks.id",
"artist": "order_artist_name",
"album_artist": "order_album_artist_name",
- "album": "order_album_name, order_album_artist_name",
+ "album": "order_album_name, album_id, disc_number, track_number, order_artist_name, title",
"title": "order_title",
// To make sure these fields will be whitelisted
"duration": "duration",
@@ -84,7 +84,7 @@ func (r *playlistTrackRepository) Count(options ...rest.QueryOptions) (int64, er
return r.count(query, r.parseRestOptions(r.ctx, options...))
}
-func (r *playlistTrackRepository) Read(id string) (interface{}, error) {
+func (r *playlistTrackRepository) Read(id string) (any, error) {
userID := loggedUser(r.ctx).ID
sel := r.newSelect().
LeftJoin("annotation on ("+
@@ -97,6 +97,7 @@ func (r *playlistTrackRepository) Read(id string) (interface{}, error) {
"coalesce(rating, 0) as rating",
"starred_at",
"play_date",
+ "rated_at",
"f.*",
"playlist_tracks.*",
).
@@ -127,7 +128,7 @@ func (r *playlistTrackRepository) GetAlbumIDs(options ...model.QueryOptions) ([]
return ids, nil
}
-func (r *playlistTrackRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *playlistTrackRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
return r.GetAll(r.parseRestOptions(r.ctx, options...))
}
@@ -135,19 +136,11 @@ func (r *playlistTrackRepository) EntityName() string {
return "playlist_tracks"
}
-func (r *playlistTrackRepository) NewInstance() interface{} {
+func (r *playlistTrackRepository) NewInstance() any {
return &model.PlaylistTrack{}
}
-func (r *playlistTrackRepository) isTracksEditable() bool {
- return r.playlistRepo.isWritable(r.playlistId) && !r.playlist.IsSmartPlaylist()
-}
-
func (r *playlistTrackRepository) Add(mediaFileIds []string) (int, error) {
- if !r.isTracksEditable() {
- return 0, rest.ErrPermissionDenied
- }
-
if len(mediaFileIds) > 0 {
log.Debug(r.ctx, "Adding songs to playlist", "playlistId", r.playlistId, "mediaFileIds", mediaFileIds)
} else {
@@ -195,22 +188,7 @@ func (r *playlistTrackRepository) AddDiscs(discs []model.DiscID) (int, error) {
return r.addMediaFileIds(clauses)
}
-// Get ids from all current tracks
-func (r *playlistTrackRepository) getTracks() ([]string, error) {
- all := r.newSelect().Columns("media_file_id").Where(Eq{"playlist_id": r.playlistId}).OrderBy("id")
- var ids []string
- err := r.queryAllSlice(all, &ids)
- if err != nil {
- log.Error(r.ctx, "Error querying current tracks from playlist", "playlistId", r.playlistId, err)
- return nil, err
- }
- return ids, nil
-}
-
func (r *playlistTrackRepository) Delete(ids ...string) error {
- if !r.isTracksEditable() {
- return rest.ErrPermissionDenied
- }
err := r.delete(And{Eq{"playlist_id": r.playlistId}, Eq{"id": ids}})
if err != nil {
return err
@@ -220,9 +198,6 @@ func (r *playlistTrackRepository) Delete(ids ...string) error {
}
func (r *playlistTrackRepository) DeleteAll() error {
- if !r.isTracksEditable() {
- return rest.ErrPermissionDenied
- }
err := r.delete(Eq{"playlist_id": r.playlistId})
if err != nil {
return err
@@ -231,16 +206,45 @@ func (r *playlistTrackRepository) DeleteAll() error {
return r.playlistRepo.renumber(r.playlistId)
}
+// Reorder moves a track from pos to newPos, shifting other tracks accordingly.
func (r *playlistTrackRepository) Reorder(pos int, newPos int) error {
- if !r.isTracksEditable() {
- return rest.ErrPermissionDenied
+ if pos == newPos {
+ return nil
}
- ids, err := r.getTracks()
+ pid := r.playlistId
+
+ // Step 1: Move the source track out of the way (temporary sentinel value)
+ _, err := r.executeSQL(Expr(
+ `UPDATE playlist_tracks SET id = -999999 WHERE playlist_id = ? AND id = ?`, pid, pos))
if err != nil {
return err
}
- newOrder := slice.Move(ids, pos-1, newPos-1)
- return r.playlistRepo.updatePlaylist(r.playlistId, newOrder)
+
+ // Step 2: Shift the affected range using negative values to avoid unique constraint violations
+ if pos < newPos {
+ _, err = r.executeSQL(Expr(
+ `UPDATE playlist_tracks SET id = -(id - 1) WHERE playlist_id = ? AND id > ? AND id <= ?`,
+ pid, pos, newPos))
+ } else {
+ _, err = r.executeSQL(Expr(
+ `UPDATE playlist_tracks SET id = -(id + 1) WHERE playlist_id = ? AND id >= ? AND id < ?`,
+ pid, newPos, pos))
+ }
+ if err != nil {
+ return err
+ }
+
+ // Step 3: Flip the shifted range back to positive
+ _, err = r.executeSQL(Expr(
+ `UPDATE playlist_tracks SET id = -id WHERE playlist_id = ? AND id < 0 AND id != -999999`, pid))
+ if err != nil {
+ return err
+ }
+
+ // Step 4: Place the source track at its new position
+ _, err = r.executeSQL(Expr(
+ `UPDATE playlist_tracks SET id = ? WHERE playlist_id = ? AND id = -999999`, newPos, pid))
+ return err
}
var _ model.PlaylistTrackRepository = (*playlistTrackRepository)(nil)
diff --git a/persistence/playqueue_repository.go b/persistence/playqueue_repository.go
index 74c80ee92..c952b42b1 100644
--- a/persistence/playqueue_repository.go
+++ b/persistence/playqueue_repository.go
@@ -122,8 +122,8 @@ func (r *playQueueRepository) toModel(pq *playQueue) model.PlayQueue {
UpdatedAt: pq.UpdatedAt,
}
if strings.TrimSpace(pq.Items) != "" {
- tracks := strings.Split(pq.Items, ",")
- for _, t := range tracks {
+ tracks := strings.SplitSeq(pq.Items, ",")
+ for t := range tracks {
q.Items = append(q.Items, model.MediaFile{ID: t})
}
}
diff --git a/persistence/plugin_cleanup.go b/persistence/plugin_cleanup.go
new file mode 100644
index 000000000..0202726e4
--- /dev/null
+++ b/persistence/plugin_cleanup.go
@@ -0,0 +1,86 @@
+package persistence
+
+import (
+ "github.com/pocketbase/dbx"
+)
+
+// cleanupPluginUserReferences removes a user ID from all plugins' users JSON arrays
+// and auto-disables plugins that lose their only permitted user (when users permission is required).
+// This is called from userRepository.Delete() to maintain referential integrity.
+func cleanupPluginUserReferences(db dbx.Builder, userID string) error {
+ // SQLite JSON function: json_remove removes the element at the path where user matches.
+ // We use a subquery with json_each to find and remove the user ID from the array.
+ // This updates all plugins where the users array contains the given user ID.
+ _, err := db.NewQuery(`
+ UPDATE plugin
+ SET users = (
+ SELECT json_group_array(value)
+ FROM json_each(plugin.users)
+ WHERE value != {:userID}
+ ),
+ updated_at = CURRENT_TIMESTAMP
+ WHERE users IS NOT NULL
+ AND users != ''
+ AND EXISTS (SELECT 1 FROM json_each(plugin.users) WHERE value = {:userID})
+ `).Bind(dbx.Params{"userID": userID}).Execute()
+ if err != nil {
+ return err
+ }
+
+ // Auto-disable plugins that:
+ // 1. Are currently enabled
+ // 2. Require users permission (manifest has permissions.users)
+ // 3. Don't have allUsers enabled
+ // 4. Now have an empty users array after cleanup
+ //
+ // The manifest check uses JSON path to see if permissions.users exists.
+ _, err = db.NewQuery(`
+ UPDATE plugin
+ SET enabled = false,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE enabled = true
+ AND all_users = false
+ AND json_extract(manifest, '$.permissions.users') IS NOT NULL
+ AND (users IS NULL OR users = '' OR users = '[]' OR json_array_length(users) = 0)
+ `).Execute()
+ return err
+}
+
+// cleanupPluginLibraryReferences removes a library ID from all plugins' libraries JSON arrays
+// and auto-disables plugins that lose their only permitted library (when library permission is required).
+// This is called from libraryRepository.Delete() to maintain referential integrity.
+func cleanupPluginLibraryReferences(db dbx.Builder, libraryID int) error {
+ // SQLite JSON function: we filter out the library ID from the array.
+ // Libraries are stored as integers in the JSON array.
+ _, err := db.NewQuery(`
+ UPDATE plugin
+ SET libraries = (
+ SELECT json_group_array(value)
+ FROM json_each(plugin.libraries)
+ WHERE CAST(value AS INTEGER) != {:libraryID}
+ ),
+ updated_at = CURRENT_TIMESTAMP
+ WHERE libraries IS NOT NULL
+ AND libraries != ''
+ AND EXISTS (SELECT 1 FROM json_each(plugin.libraries) WHERE CAST(value AS INTEGER) = {:libraryID})
+ `).Bind(dbx.Params{"libraryID": libraryID}).Execute()
+ if err != nil {
+ return err
+ }
+
+ // Auto-disable plugins that:
+ // 1. Are currently enabled
+ // 2. Require library permission (manifest has permissions.library)
+ // 3. Don't have allLibraries enabled
+ // 4. Now have an empty libraries array after cleanup
+ _, err = db.NewQuery(`
+ UPDATE plugin
+ SET enabled = false,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE enabled = true
+ AND all_libraries = false
+ AND json_extract(manifest, '$.permissions.library') IS NOT NULL
+ AND (libraries IS NULL OR libraries = '' OR libraries = '[]' OR json_array_length(libraries) = 0)
+ `).Execute()
+ return err
+}
diff --git a/persistence/plugin_cleanup_test.go b/persistence/plugin_cleanup_test.go
new file mode 100644
index 000000000..bfe6d60ca
--- /dev/null
+++ b/persistence/plugin_cleanup_test.go
@@ -0,0 +1,263 @@
+package persistence
+
+import (
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Plugin Cleanup", func() {
+ var pluginRepo model.PluginRepository
+ var userRepo model.UserRepository
+ var libraryRepo model.LibraryRepository
+
+ BeforeEach(func() {
+ ctx := GinkgoT().Context()
+ ctx = request.WithUser(ctx, model.User{ID: "admin", UserName: "admin", IsAdmin: true})
+ db := GetDBXBuilder()
+ pluginRepo = NewPluginRepository(ctx, db)
+ userRepo = NewUserRepository(ctx, db)
+ libraryRepo = NewLibraryRepository(ctx, db)
+
+ // Clean up any existing plugins
+ all, _ := pluginRepo.GetAll()
+ for _, p := range all {
+ _ = pluginRepo.Delete(p.ID)
+ }
+ })
+
+ AfterEach(func() {
+ // Clean up after tests
+ all, _ := pluginRepo.GetAll()
+ for _, p := range all {
+ _ = pluginRepo.Delete(p.ID)
+ }
+ })
+
+ Describe("cleanupPluginUserReferences", func() {
+ It("removes user ID from plugin users array", func() {
+ // Create a plugin with multiple users
+ plugin := &model.Plugin{
+ ID: "test-plugin",
+ Path: "/plugins/test.wasm",
+ Manifest: `{"name":"test"}`,
+ SHA256: "abc123",
+ Users: `["user1","user2","user3"]`,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Clean up user2 reference
+ db := GetDBXBuilder()
+ Expect(cleanupPluginUserReferences(db, "user2")).To(Succeed())
+
+ // Verify user2 was removed
+ updated, err := pluginRepo.Get("test-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Users).To(Equal(`["user1","user3"]`))
+ Expect(updated.Enabled).To(BeTrue()) // Still has users, should remain enabled
+ })
+
+ It("auto-disables plugin when last permitted user is removed", func() {
+ // Create a plugin that requires users permission with only one user
+ plugin := &model.Plugin{
+ ID: "user-plugin",
+ Path: "/plugins/user.wasm",
+ Manifest: `{"name":"user-plugin","permissions":{"users":{}}}`,
+ SHA256: "def456",
+ Users: `["only-user"]`,
+ AllUsers: false,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Remove the only user
+ db := GetDBXBuilder()
+ Expect(cleanupPluginUserReferences(db, "only-user")).To(Succeed())
+
+ // Verify plugin was auto-disabled
+ updated, err := pluginRepo.Get("user-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Users).To(Equal(`[]`))
+ Expect(updated.Enabled).To(BeFalse())
+ })
+
+ It("does not disable plugin when allUsers is true", func() {
+ plugin := &model.Plugin{
+ ID: "all-users-plugin",
+ Path: "/plugins/all.wasm",
+ Manifest: `{"name":"all-users","permissions":{"users":{}}}`,
+ SHA256: "ghi789",
+ Users: `["user1"]`,
+ AllUsers: true,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Remove the user (but allUsers is true)
+ db := GetDBXBuilder()
+ Expect(cleanupPluginUserReferences(db, "user1")).To(Succeed())
+
+ // Plugin should still be enabled because allUsers is true
+ updated, err := pluginRepo.Get("all-users-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Enabled).To(BeTrue())
+ })
+
+ It("does not affect plugins without users permission requirement", func() {
+ plugin := &model.Plugin{
+ ID: "no-users-perm",
+ Path: "/plugins/noperm.wasm",
+ Manifest: `{"name":"no-perm"}`, // No permissions.users in manifest
+ SHA256: "jkl012",
+ Users: `["user1"]`,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Remove the user
+ db := GetDBXBuilder()
+ Expect(cleanupPluginUserReferences(db, "user1")).To(Succeed())
+
+ // Plugin should still be enabled (no users permission requirement)
+ updated, err := pluginRepo.Get("no-users-perm")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Users).To(Equal(`[]`))
+ Expect(updated.Enabled).To(BeTrue())
+ })
+ })
+
+ Describe("cleanupPluginLibraryReferences", func() {
+ It("removes library ID from plugin libraries array", func() {
+ // Create a plugin with multiple libraries
+ plugin := &model.Plugin{
+ ID: "lib-plugin",
+ Path: "/plugins/lib.wasm",
+ Manifest: `{"name":"lib-plugin"}`,
+ SHA256: "mno345",
+ Libraries: `[1,2,3]`,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Clean up library 2 reference
+ db := GetDBXBuilder()
+ Expect(cleanupPluginLibraryReferences(db, 2)).To(Succeed())
+
+ // Verify library 2 was removed
+ updated, err := pluginRepo.Get("lib-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Libraries).To(Equal(`[1,3]`))
+ })
+
+ It("auto-disables plugin when last permitted library is removed", func() {
+ // Create a plugin that requires library permission with only one library
+ plugin := &model.Plugin{
+ ID: "lib-only-plugin",
+ Path: "/plugins/libonly.wasm",
+ Manifest: `{"name":"lib-only","permissions":{"library":{}}}`,
+ SHA256: "pqr678",
+ Libraries: `[99]`,
+ AllLibraries: false,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Remove the only library
+ db := GetDBXBuilder()
+ Expect(cleanupPluginLibraryReferences(db, 99)).To(Succeed())
+
+ // Verify plugin was auto-disabled
+ updated, err := pluginRepo.Get("lib-only-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Libraries).To(Equal(`[]`))
+ Expect(updated.Enabled).To(BeFalse())
+ })
+
+ It("does not disable plugin when allLibraries is true", func() {
+ plugin := &model.Plugin{
+ ID: "all-libs-plugin",
+ Path: "/plugins/alllibs.wasm",
+ Manifest: `{"name":"all-libs","permissions":{"library":{}}}`,
+ SHA256: "stu901",
+ Libraries: `[1]`,
+ AllLibraries: true,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Remove the library (but allLibraries is true)
+ db := GetDBXBuilder()
+ Expect(cleanupPluginLibraryReferences(db, 1)).To(Succeed())
+
+ // Plugin should still be enabled
+ updated, err := pluginRepo.Get("all-libs-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Enabled).To(BeTrue())
+ })
+ })
+
+ Describe("User Delete integration", func() {
+ It("cleans up plugin references when user is deleted", func() {
+ // Create a test user
+ user := &model.User{
+ ID: "test-delete-user",
+ UserName: "plugin-cleanup-test-user",
+ IsAdmin: false,
+ }
+ user.NewPassword = "password123"
+ Expect(userRepo.Put(user)).To(Succeed())
+
+ // Create a plugin referencing this user
+ plugin := &model.Plugin{
+ ID: "user-ref-plugin",
+ Path: "/plugins/userref.wasm",
+ Manifest: `{"name":"user-ref"}`,
+ SHA256: "xyz123",
+ Users: `["test-delete-user","other-user"]`,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Delete the user
+ Expect(userRepo.Delete("test-delete-user")).To(Succeed())
+
+ // Verify user was removed from plugin
+ updated, err := pluginRepo.Get("user-ref-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Users).To(Equal(`["other-user"]`))
+ })
+ })
+
+ Describe("Library Delete integration", func() {
+ It("cleans up plugin references when library is deleted", func() {
+ // Create a test library (ID > 1 since ID 1 cannot be deleted)
+ library := &model.Library{
+ ID: 99,
+ Name: "Test Library",
+ Path: "/tmp/test-lib",
+ }
+ Expect(libraryRepo.Put(library)).To(Succeed())
+
+ // Create a plugin referencing this library
+ plugin := &model.Plugin{
+ ID: "lib-ref-plugin",
+ Path: "/plugins/libref.wasm",
+ Manifest: `{"name":"lib-ref"}`,
+ SHA256: "abc789",
+ Libraries: `[99,1]`,
+ Enabled: true,
+ }
+ Expect(pluginRepo.Put(plugin)).To(Succeed())
+
+ // Delete the library
+ Expect(libraryRepo.Delete(99)).To(Succeed())
+
+ // Verify library was removed from plugin
+ updated, err := pluginRepo.Get("lib-ref-plugin")
+ Expect(err).ToNot(HaveOccurred())
+ Expect(updated.Libraries).To(Equal(`[1]`))
+ })
+ })
+})
diff --git a/persistence/plugin_repository.go b/persistence/plugin_repository.go
new file mode 100644
index 000000000..35c32de91
--- /dev/null
+++ b/persistence/plugin_repository.go
@@ -0,0 +1,171 @@
+package persistence
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ . "github.com/Masterminds/squirrel"
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/model"
+ "github.com/pocketbase/dbx"
+)
+
+type pluginRepository struct {
+ sqlRepository
+}
+
+func NewPluginRepository(ctx context.Context, db dbx.Builder) model.PluginRepository {
+ r := &pluginRepository{}
+ r.ctx = ctx
+ r.db = db
+ r.registerModel(&model.Plugin{}, map[string]filterFunc{
+ "id": idFilter("plugin"),
+ "enabled": booleanFilter,
+ })
+ return r
+}
+
+func (r *pluginRepository) isPermitted() bool {
+ user := loggedUser(r.ctx)
+ return user.IsAdmin
+}
+
+func (r *pluginRepository) ClearErrors() error {
+ if !r.isPermitted() {
+ return rest.ErrPermissionDenied
+ }
+ _, err := r.db.NewQuery("UPDATE plugin SET last_error = '' WHERE last_error != ''").Execute()
+ return err
+}
+
+func (r *pluginRepository) CountAll(options ...model.QueryOptions) (int64, error) {
+ if !r.isPermitted() {
+ return 0, rest.ErrPermissionDenied
+ }
+ sql := r.newSelect()
+ return r.count(sql, options...)
+}
+
+func (r *pluginRepository) Delete(id string) error {
+ if !r.isPermitted() {
+ return rest.ErrPermissionDenied
+ }
+ return r.delete(Eq{"id": id})
+}
+
+func (r *pluginRepository) Get(id string) (*model.Plugin, error) {
+ if !r.isPermitted() {
+ return nil, rest.ErrPermissionDenied
+ }
+ sel := r.newSelect().Where(Eq{"id": id}).Columns("*")
+ res := model.Plugin{}
+ err := r.queryOne(sel, &res)
+ return &res, err
+}
+
+func (r *pluginRepository) GetAll(options ...model.QueryOptions) (model.Plugins, error) {
+ if !r.isPermitted() {
+ return nil, rest.ErrPermissionDenied
+ }
+ sel := r.newSelect(options...).Columns("*")
+ res := model.Plugins{}
+ err := r.queryAll(sel, &res)
+ return res, err
+}
+
+func (r *pluginRepository) Put(plugin *model.Plugin) error {
+ if !r.isPermitted() {
+ return rest.ErrPermissionDenied
+ }
+
+ plugin.UpdatedAt = time.Now()
+
+ if plugin.ID == "" {
+ return errors.New("plugin ID cannot be empty")
+ }
+
+ // Upsert using INSERT ... ON CONFLICT for atomic operation
+ _, err := r.db.NewQuery(`
+ INSERT INTO plugin (id, path, manifest, config, users, all_users, libraries, all_libraries, allow_write_access, enabled, last_error, sha256, created_at, updated_at)
+ VALUES ({:id}, {:path}, {:manifest}, {:config}, {:users}, {:all_users}, {:libraries}, {:all_libraries}, {:allow_write_access}, {:enabled}, {:last_error}, {:sha256}, {:created_at}, {:updated_at})
+ ON CONFLICT(id) DO UPDATE SET
+ path = excluded.path,
+ manifest = excluded.manifest,
+ config = excluded.config,
+ users = excluded.users,
+ all_users = excluded.all_users,
+ libraries = excluded.libraries,
+ all_libraries = excluded.all_libraries,
+ allow_write_access = excluded.allow_write_access,
+ enabled = excluded.enabled,
+ last_error = excluded.last_error,
+ sha256 = excluded.sha256,
+ updated_at = excluded.updated_at
+ `).Bind(dbx.Params{
+ "id": plugin.ID,
+ "path": plugin.Path,
+ "manifest": plugin.Manifest,
+ "config": plugin.Config,
+ "users": plugin.Users,
+ "all_users": plugin.AllUsers,
+ "libraries": plugin.Libraries,
+ "all_libraries": plugin.AllLibraries,
+ "allow_write_access": plugin.AllowWriteAccess,
+ "enabled": plugin.Enabled,
+ "last_error": plugin.LastError,
+ "sha256": plugin.SHA256,
+ "created_at": time.Now(),
+ "updated_at": plugin.UpdatedAt,
+ }).Execute()
+ return err
+}
+
+func (r *pluginRepository) Count(options ...rest.QueryOptions) (int64, error) {
+ return r.CountAll(r.parseRestOptions(r.ctx, options...))
+}
+
+func (r *pluginRepository) EntityName() string {
+ return "plugin"
+}
+
+func (r *pluginRepository) NewInstance() any {
+ return &model.Plugin{}
+}
+
+func (r *pluginRepository) Read(id string) (any, error) {
+ return r.Get(id)
+}
+
+func (r *pluginRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
+ return r.GetAll(r.parseRestOptions(r.ctx, options...))
+}
+
+func (r *pluginRepository) Save(entity any) (string, error) {
+ p := entity.(*model.Plugin)
+ if !r.isPermitted() {
+ return "", rest.ErrPermissionDenied
+ }
+ err := r.Put(p)
+ if errors.Is(err, model.ErrNotFound) {
+ return "", rest.ErrNotFound
+ }
+ return p.ID, err
+}
+
+func (r *pluginRepository) Update(id string, entity any, cols ...string) error {
+ p := entity.(*model.Plugin)
+ p.ID = id
+ if !r.isPermitted() {
+ return rest.ErrPermissionDenied
+ }
+ err := r.Put(p)
+ if errors.Is(err, model.ErrNotFound) {
+ return rest.ErrNotFound
+ }
+ return err
+}
+
+var _ model.PluginRepository = (*pluginRepository)(nil)
+var _ rest.Repository = (*pluginRepository)(nil)
+var _ rest.Persistable = (*pluginRepository)(nil)
diff --git a/persistence/plugin_repository_test.go b/persistence/plugin_repository_test.go
new file mode 100644
index 000000000..dc68b0892
--- /dev/null
+++ b/persistence/plugin_repository_test.go
@@ -0,0 +1,251 @@
+package persistence
+
+import (
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("PluginRepository", func() {
+ var repo model.PluginRepository
+
+ Describe("Admin User", func() {
+ BeforeEach(func() {
+ ctx := GinkgoT().Context()
+ ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: true})
+ repo = NewPluginRepository(ctx, GetDBXBuilder())
+
+ // Clean up any existing plugins
+ all, _ := repo.GetAll()
+ for _, p := range all {
+ _ = repo.Delete(p.ID)
+ }
+ })
+
+ AfterEach(func() {
+ // Clean up after tests
+ all, _ := repo.GetAll()
+ for _, p := range all {
+ _ = repo.Delete(p.ID)
+ }
+ })
+
+ Describe("CountAll", func() {
+ It("returns 0 when no plugins exist", func() {
+ Expect(repo.CountAll()).To(Equal(int64(0)))
+ })
+
+ It("returns the number of plugins in the DB", func() {
+ _ = repo.Put(&model.Plugin{ID: "test-plugin-1", Path: "/plugins/test1.wasm", Manifest: "{}", SHA256: "abc123"})
+ _ = repo.Put(&model.Plugin{ID: "test-plugin-2", Path: "/plugins/test2.wasm", Manifest: "{}", SHA256: "def456"})
+
+ Expect(repo.CountAll()).To(Equal(int64(2)))
+ })
+ })
+
+ Describe("Delete", func() {
+ It("deletes existing item", func() {
+ plugin := &model.Plugin{ID: "to-delete", Path: "/plugins/delete.wasm", Manifest: "{}", SHA256: "hash"}
+ _ = repo.Put(plugin)
+
+ err := repo.Delete(plugin.ID)
+ Expect(err).To(BeNil())
+
+ _, err = repo.Get(plugin.ID)
+ Expect(err).To(MatchError(model.ErrNotFound))
+ })
+ })
+
+ Describe("Get", func() {
+ It("returns an existing item", func() {
+ plugin := &model.Plugin{ID: "test-get", Path: "/plugins/test.wasm", Manifest: `{"name":"test"}`, SHA256: "hash123"}
+ _ = repo.Put(plugin)
+
+ res, err := repo.Get(plugin.ID)
+ Expect(err).To(BeNil())
+ Expect(res.ID).To(Equal(plugin.ID))
+ Expect(res.Path).To(Equal(plugin.Path))
+ Expect(res.Manifest).To(Equal(plugin.Manifest))
+ })
+
+ It("errors when missing", func() {
+ _, err := repo.Get("notanid")
+ Expect(err).To(MatchError(model.ErrNotFound))
+ })
+ })
+
+ Describe("GetAll", func() {
+ It("returns all items from the DB", func() {
+ _ = repo.Put(&model.Plugin{ID: "plugin-a", Path: "/plugins/a.wasm", Manifest: "{}", SHA256: "hash1"})
+ _ = repo.Put(&model.Plugin{ID: "plugin-b", Path: "/plugins/b.wasm", Manifest: "{}", SHA256: "hash2"})
+
+ all, err := repo.GetAll()
+ Expect(err).To(BeNil())
+ Expect(all).To(HaveLen(2))
+ })
+
+ It("supports pagination", func() {
+ _ = repo.Put(&model.Plugin{ID: "plugin-1", Path: "/plugins/1.wasm", Manifest: "{}", SHA256: "h1"})
+ _ = repo.Put(&model.Plugin{ID: "plugin-2", Path: "/plugins/2.wasm", Manifest: "{}", SHA256: "h2"})
+ _ = repo.Put(&model.Plugin{ID: "plugin-3", Path: "/plugins/3.wasm", Manifest: "{}", SHA256: "h3"})
+
+ page1, err := repo.GetAll(model.QueryOptions{Max: 2, Offset: 0, Sort: "id"})
+ Expect(err).To(BeNil())
+ Expect(page1).To(HaveLen(2))
+
+ page2, err := repo.GetAll(model.QueryOptions{Max: 2, Offset: 2, Sort: "id"})
+ Expect(err).To(BeNil())
+ Expect(page2).To(HaveLen(1))
+ })
+ })
+
+ Describe("Put", func() {
+ It("successfully creates a new plugin", func() {
+ plugin := &model.Plugin{
+ ID: "new-plugin",
+ Path: "/plugins/new.wasm",
+ Manifest: `{"name":"new","version":"1.0"}`,
+ Config: `{"setting":"value"}`,
+ SHA256: "sha256hash",
+ Enabled: false,
+ }
+
+ err := repo.Put(plugin)
+ Expect(err).To(BeNil())
+
+ saved, err := repo.Get(plugin.ID)
+ Expect(err).To(BeNil())
+ Expect(saved.Path).To(Equal(plugin.Path))
+ Expect(saved.Manifest).To(Equal(plugin.Manifest))
+ Expect(saved.Config).To(Equal(plugin.Config))
+ Expect(saved.Enabled).To(BeFalse())
+ Expect(saved.CreatedAt).NotTo(BeZero())
+ Expect(saved.UpdatedAt).NotTo(BeZero())
+ })
+
+ It("successfully updates an existing plugin", func() {
+ plugin := &model.Plugin{
+ ID: "update-plugin",
+ Path: "/plugins/update.wasm",
+ Manifest: `{"name":"test"}`,
+ SHA256: "original",
+ Enabled: false,
+ }
+ _ = repo.Put(plugin)
+
+ plugin.Enabled = true
+ plugin.Config = `{"new":"config"}`
+ plugin.SHA256 = "updated"
+ err := repo.Put(plugin)
+ Expect(err).To(BeNil())
+
+ saved, err := repo.Get(plugin.ID)
+ Expect(err).To(BeNil())
+ Expect(saved.Enabled).To(BeTrue())
+ Expect(saved.Config).To(Equal(`{"new":"config"}`))
+ Expect(saved.SHA256).To(Equal("updated"))
+ })
+
+ It("stores and retrieves last_error", func() {
+ plugin := &model.Plugin{
+ ID: "error-plugin",
+ Path: "/plugins/error.wasm",
+ Manifest: "{}",
+ SHA256: "hash",
+ LastError: "failed to load: missing export",
+ }
+ err := repo.Put(plugin)
+ Expect(err).To(BeNil())
+
+ saved, err := repo.Get(plugin.ID)
+ Expect(err).To(BeNil())
+ Expect(saved.LastError).To(Equal("failed to load: missing export"))
+ })
+
+ It("fails when ID is empty", func() {
+ plugin := &model.Plugin{
+ Path: "/plugins/noid.wasm",
+ Manifest: "{}",
+ SHA256: "hash",
+ }
+ err := repo.Put(plugin)
+ Expect(err).To(HaveOccurred())
+ Expect(err.Error()).To(ContainSubstring("ID cannot be empty"))
+ })
+ })
+
+ Describe("ClearErrors", func() {
+ It("clears last_error on all plugins with errors", func() {
+ _ = repo.Put(&model.Plugin{ID: "ok-plugin", Path: "/plugins/ok.wasm", Manifest: "{}", SHA256: "h1"})
+ _ = repo.Put(&model.Plugin{ID: "err-plugin-1", Path: "/plugins/e1.wasm", Manifest: "{}", SHA256: "h2", LastError: "incompatible version"})
+ _ = repo.Put(&model.Plugin{ID: "err-plugin-2", Path: "/plugins/e2.wasm", Manifest: "{}", SHA256: "h3", LastError: "missing export"})
+
+ err := repo.ClearErrors()
+ Expect(err).To(BeNil())
+
+ all, err := repo.GetAll()
+ Expect(err).To(BeNil())
+ for _, p := range all {
+ Expect(p.LastError).To(BeEmpty(), "plugin %s should have no error", p.ID)
+ }
+ })
+
+ It("succeeds when no plugins have errors", func() {
+ _ = repo.Put(&model.Plugin{ID: "clean-plugin", Path: "/plugins/c.wasm", Manifest: "{}", SHA256: "h1"})
+
+ err := repo.ClearErrors()
+ Expect(err).To(BeNil())
+ })
+ })
+ })
+
+ Describe("Regular User", func() {
+ BeforeEach(func() {
+ ctx := GinkgoT().Context()
+ ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: false})
+ repo = NewPluginRepository(ctx, GetDBXBuilder())
+ })
+
+ Describe("CountAll", func() {
+ It("fails to count items", func() {
+ _, err := repo.CountAll()
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+
+ Describe("Delete", func() {
+ It("fails to delete items", func() {
+ err := repo.Delete("any-id")
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+
+ Describe("Get", func() {
+ It("fails to get items", func() {
+ _, err := repo.Get("any-id")
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+
+ Describe("GetAll", func() {
+ It("fails to get all items", func() {
+ _, err := repo.GetAll()
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+
+ Describe("Put", func() {
+ It("fails to create/update item", func() {
+ err := repo.Put(&model.Plugin{
+ ID: "user-create",
+ Path: "/plugins/create.wasm",
+ Manifest: "{}",
+ SHA256: "hash",
+ })
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+ })
+})
diff --git a/persistence/radio_repository.go b/persistence/radio_repository.go
index cf253d06b..a073643db 100644
--- a/persistence/radio_repository.go
+++ b/persistence/radio_repository.go
@@ -58,34 +58,20 @@ func (r *radioRepository) GetAll(options ...model.QueryOptions) (model.Radios, e
return res, err
}
-func (r *radioRepository) Put(radio *model.Radio) error {
+func (r *radioRepository) Put(radio *model.Radio, colsToUpdate ...string) error {
if !r.isPermitted() {
return rest.ErrPermissionDenied
}
- var values map[string]interface{}
-
radio.UpdatedAt = time.Now()
-
if radio.ID == "" {
radio.CreatedAt = time.Now()
radio.ID = id.NewRandom()
- values, _ = toSQLArgs(*radio)
- } else {
- values, _ = toSQLArgs(*radio)
- update := Update(r.tableName).Where(Eq{"id": radio.ID}).SetMap(values)
- count, err := r.executeSQL(update)
-
- if err != nil {
- return err
- } else if count > 0 {
- return nil
- }
}
-
- values["created_at"] = time.Now()
- insert := Insert(r.tableName).SetMap(values)
- _, err := r.executeSQL(insert)
+ if len(colsToUpdate) > 0 {
+ colsToUpdate = append(colsToUpdate, "UpdatedAt")
+ }
+ _, err := r.put(radio.ID, radio, colsToUpdate...)
return err
}
@@ -97,19 +83,19 @@ func (r *radioRepository) EntityName() string {
return "radio"
}
-func (r *radioRepository) NewInstance() interface{} {
+func (r *radioRepository) NewInstance() any {
return &model.Radio{}
}
-func (r *radioRepository) Read(id string) (interface{}, error) {
+func (r *radioRepository) Read(id string) (any, error) {
return r.Get(id)
}
-func (r *radioRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *radioRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
return r.GetAll(r.parseRestOptions(r.ctx, options...))
}
-func (r *radioRepository) Save(entity interface{}) (string, error) {
+func (r *radioRepository) Save(entity any) (string, error) {
t := entity.(*model.Radio)
if !r.isPermitted() {
return "", rest.ErrPermissionDenied
@@ -121,7 +107,7 @@ func (r *radioRepository) Save(entity interface{}) (string, error) {
return t.ID, err
}
-func (r *radioRepository) Update(id string, entity interface{}, cols ...string) error {
+func (r *radioRepository) Update(id string, entity any, cols ...string) error {
t := entity.(*model.Radio)
t.ID = id
if !r.isPermitted() {
diff --git a/persistence/scrobble_buffer_repository.go b/persistence/scrobble_buffer_repository.go
index d0f88903e..3cfb836bf 100644
--- a/persistence/scrobble_buffer_repository.go
+++ b/persistence/scrobble_buffer_repository.go
@@ -51,7 +51,7 @@ func (r *scrobbleBufferRepository) UserIDs(service string) ([]string, error) {
}
func (r *scrobbleBufferRepository) Enqueue(service, userId, mediaFileId string, playTime time.Time) error {
- ins := Insert(r.tableName).SetMap(map[string]interface{}{
+ ins := Insert(r.tableName).SetMap(map[string]any{
"id": id.NewRandom(),
"user_id": userId,
"service": service,
diff --git a/persistence/scrobble_buffer_repository_test.go b/persistence/scrobble_buffer_repository_test.go
index 62423ff45..edf59ce49 100644
--- a/persistence/scrobble_buffer_repository_test.go
+++ b/persistence/scrobble_buffer_repository_test.go
@@ -24,7 +24,7 @@ var _ = Describe("ScrobbleBufferRepository", func() {
id := id.NewRandom()
ids = append(ids, id)
- ins := squirrel.Insert("scrobble_buffer").SetMap(map[string]interface{}{
+ ins := squirrel.Insert("scrobble_buffer").SetMap(map[string]any{
"id": id,
"user_id": userId,
"service": service,
diff --git a/persistence/scrobble_repository.go b/persistence/scrobble_repository.go
new file mode 100644
index 000000000..219a48198
--- /dev/null
+++ b/persistence/scrobble_repository.go
@@ -0,0 +1,34 @@
+package persistence
+
+import (
+ "context"
+ "time"
+
+ . "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/model"
+ "github.com/pocketbase/dbx"
+)
+
+type scrobbleRepository struct {
+ sqlRepository
+}
+
+func NewScrobbleRepository(ctx context.Context, db dbx.Builder) model.ScrobbleRepository {
+ r := &scrobbleRepository{}
+ r.ctx = ctx
+ r.db = db
+ r.tableName = "scrobbles"
+ return r
+}
+
+func (r *scrobbleRepository) RecordScrobble(mediaFileID string, submissionTime time.Time) error {
+ userID := loggedUser(r.ctx).ID
+ values := map[string]any{
+ "media_file_id": mediaFileID,
+ "user_id": userID,
+ "submission_time": submissionTime.Unix(),
+ }
+ insert := Insert(r.tableName).SetMap(values)
+ _, err := r.executeSQL(insert)
+ return err
+}
diff --git a/persistence/scrobble_repository_test.go b/persistence/scrobble_repository_test.go
new file mode 100644
index 000000000..d43848d03
--- /dev/null
+++ b/persistence/scrobble_repository_test.go
@@ -0,0 +1,84 @@
+package persistence
+
+import (
+ "context"
+ "time"
+
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/id"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/pocketbase/dbx"
+)
+
+var _ = Describe("ScrobbleRepository", func() {
+ var repo model.ScrobbleRepository
+ var rawRepo sqlRepository
+ var ctx context.Context
+ var fileID string
+ var userID string
+
+ BeforeEach(func() {
+ fileID = id.NewRandom()
+ userID = id.NewRandom()
+ ctx = request.WithUser(log.NewContext(GinkgoT().Context()), model.User{ID: userID, UserName: "johndoe", IsAdmin: true})
+ db := GetDBXBuilder()
+ repo = NewScrobbleRepository(ctx, db)
+
+ rawRepo = sqlRepository{
+ ctx: ctx,
+ tableName: "scrobbles",
+ db: db,
+ }
+ })
+
+ AfterEach(func() {
+ _, _ = rawRepo.db.Delete("scrobbles", dbx.HashExp{"media_file_id": fileID}).Execute()
+ _, _ = rawRepo.db.Delete("media_file", dbx.HashExp{"id": fileID}).Execute()
+ _, _ = rawRepo.db.Delete("user", dbx.HashExp{"id": userID}).Execute()
+ })
+
+ Describe("RecordScrobble", func() {
+ It("records a scrobble event", func() {
+ submissionTime := time.Now().UTC()
+
+ // Insert User
+ _, err := rawRepo.db.Insert("user", dbx.Params{
+ "id": userID,
+ "user_name": "user",
+ "password": "pw",
+ "created_at": time.Now(),
+ "updated_at": time.Now(),
+ }).Execute()
+ Expect(err).ToNot(HaveOccurred())
+
+ // Insert MediaFile
+ _, err = rawRepo.db.Insert("media_file", dbx.Params{
+ "id": fileID,
+ "path": "path",
+ "created_at": time.Now(),
+ "updated_at": time.Now(),
+ }).Execute()
+ Expect(err).ToNot(HaveOccurred())
+
+ err = repo.RecordScrobble(fileID, submissionTime)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Verify insertion
+ var scrobble struct {
+ MediaFileID string `db:"media_file_id"`
+ UserID string `db:"user_id"`
+ SubmissionTime int64 `db:"submission_time"`
+ }
+ err = rawRepo.db.Select("*").From("scrobbles").
+ Where(dbx.HashExp{"media_file_id": fileID, "user_id": userID}).
+ One(&scrobble)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(scrobble.MediaFileID).To(Equal(fileID))
+ Expect(scrobble.UserID).To(Equal(userID))
+ Expect(scrobble.SubmissionTime).To(Equal(submissionTime.Unix()))
+ })
+ })
+})
diff --git a/persistence/share_repository.go b/persistence/share_repository.go
index d943943e0..415109640 100644
--- a/persistence/share_repository.go
+++ b/persistence/share_repository.go
@@ -30,7 +30,33 @@ func NewShareRepository(ctx context.Context, db dbx.Builder) model.ShareReposito
return r
}
+// TODO: Ownership checks should be moved to the service layer (core/share.go)
+func (r *shareRepository) checkOwnership(id string) error {
+ usr := loggedUser(r.ctx)
+ if usr.IsAdmin || usr.ID == invalidUserId {
+ return nil
+ }
+ sel := r.newSelect().Columns("user_id").Where(Eq{"id": id})
+ var share struct {
+ UserID string `db:"user_id"`
+ }
+ err := r.queryOne(sel, &share)
+ if err != nil {
+ if errors.Is(err, model.ErrNotFound) {
+ return rest.ErrNotFound
+ }
+ return err
+ }
+ if share.UserID != usr.ID {
+ return rest.ErrPermissionDenied
+ }
+ return nil
+}
+
func (r *shareRepository) Delete(id string) error {
+ if err := r.checkOwnership(id); err != nil {
+ return err
+ }
err := r.delete(Eq{"id": id})
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
@@ -138,9 +164,11 @@ func sortByIdPosition(mfs model.MediaFiles, ids []string) model.MediaFiles {
return sorted
}
-func (r *shareRepository) Update(id string, entity interface{}, cols ...string) error {
+func (r *shareRepository) Update(id string, entity any, cols ...string) error {
s := entity.(*model.Share)
- // TODO Validate record
+ if err := r.checkOwnership(id); err != nil {
+ return err
+ }
s.ID = id
s.UpdatedAt = time.Now()
cols = append(cols, "updated_at")
@@ -151,7 +179,7 @@ func (r *shareRepository) Update(id string, entity interface{}, cols ...string)
return err
}
-func (r *shareRepository) Save(entity interface{}) (string, error) {
+func (r *shareRepository) Save(entity any) (string, error) {
s := entity.(*model.Share)
// TODO Validate record
u := loggedUser(r.ctx)
@@ -179,18 +207,18 @@ func (r *shareRepository) EntityName() string {
return "share"
}
-func (r *shareRepository) NewInstance() interface{} {
+func (r *shareRepository) NewInstance() any {
return &model.Share{}
}
-func (r *shareRepository) Read(id string) (interface{}, error) {
+func (r *shareRepository) Read(id string) (any, error) {
sel := r.selectShare().Where(Eq{"share.id": id})
var res model.Share
err := r.queryOne(sel, &res)
return &res, err
}
-func (r *shareRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *shareRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
sq := r.selectShare(r.parseRestOptions(r.ctx, options...))
res := model.Shares{}
err := r.queryAll(sq, &res)
diff --git a/persistence/share_repository_test.go b/persistence/share_repository_test.go
index 252115175..6988f323f 100644
--- a/persistence/share_repository_test.go
+++ b/persistence/share_repository_test.go
@@ -4,6 +4,7 @@ import (
"context"
"time"
+ "github.com/deluan/rest"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
@@ -47,7 +48,7 @@ var _ = Describe("ShareRepository", func() {
_, err := GetDBXBuilder().NewQuery(`
INSERT INTO share (id, user_id, description, resource_type, resource_ids, created_at, updated_at)
VALUES ({:id}, {:user}, {:desc}, {:type}, {:ids}, {:created}, {:updated})
- `).Bind(map[string]interface{}{
+ `).Bind(map[string]any{
"id": shareID,
"user": adminUser.ID,
"desc": "Headless Test Share",
@@ -79,7 +80,7 @@ var _ = Describe("ShareRepository", func() {
_, err := GetDBXBuilder().NewQuery(`
INSERT INTO share (id, user_id, description, resource_type, resource_ids, created_at, updated_at)
VALUES ({:id}, {:user}, {:desc}, {:type}, {:ids}, {:created}, {:updated})
- `).Bind(map[string]interface{}{
+ `).Bind(map[string]any{
"id": shareID,
"user": adminUser.ID,
"desc": "Headless Get Share",
@@ -110,7 +111,7 @@ var _ = Describe("ShareRepository", func() {
_, err := GetDBXBuilder().NewQuery(`
INSERT INTO share (id, user_id, description, resource_type, resource_ids, created_at, updated_at)
VALUES ({:id}, {:user}, {:desc}, {:type}, {:ids}, {:created}, {:updated})
- `).Bind(map[string]interface{}{
+ `).Bind(map[string]any{
"id": shareID,
"user": adminUser.ID,
"desc": "SQL Test Share",
@@ -130,4 +131,91 @@ var _ = Describe("ShareRepository", func() {
Expect(share.Albums).To(BeEmpty())
})
})
+
+ Describe("Ownership Checks", func() {
+ var ownerUser = model.User{ID: "2222", UserName: "regular-user"}
+ var otherUser = model.User{ID: "3333", UserName: "third-user"}
+
+ insertShare := func(shareID, userID string) {
+ _, err := GetDBXBuilder().NewQuery(`
+ INSERT INTO share (id, user_id, description, resource_type, resource_ids, created_at, updated_at)
+ VALUES ({:id}, {:user}, {:desc}, {:type}, {:ids}, {:created}, {:updated})
+ `).Bind(map[string]any{
+ "id": shareID,
+ "user": userID,
+ "desc": "Test Share",
+ "type": "media_file",
+ "ids": "1001",
+ "created": time.Now(),
+ "updated": time.Now(),
+ }).Execute()
+ Expect(err).ToNot(HaveOccurred())
+ }
+
+ Describe("Delete", func() {
+ It("allows a non-admin user to delete their own share", func() {
+ insertShare("own-share-del", ownerUser.ID)
+ ctx := request.WithUser(log.NewContext(context.TODO()), ownerUser)
+ repo := NewShareRepository(ctx, GetDBXBuilder())
+ err := repo.(rest.Persistable).Delete("own-share-del")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("denies a non-admin user from deleting another user's share", func() {
+ insertShare("other-share-del", ownerUser.ID)
+ ctx := request.WithUser(log.NewContext(context.TODO()), otherUser)
+ repo := NewShareRepository(ctx, GetDBXBuilder())
+ err := repo.(rest.Persistable).Delete("other-share-del")
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+
+ It("allows an admin to delete any user's share", func() {
+ insertShare("admin-del-share", ownerUser.ID)
+ ctx := request.WithUser(log.NewContext(context.TODO()), adminUser)
+ repo := NewShareRepository(ctx, GetDBXBuilder())
+ err := repo.(rest.Persistable).Delete("admin-del-share")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("allows headless context (no user) to delete a share", func() {
+ insertShare("headless-del-share", ownerUser.ID)
+ repo := NewShareRepository(context.Background(), GetDBXBuilder())
+ err := repo.(rest.Persistable).Delete("headless-del-share")
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
+
+ Describe("Update", func() {
+ It("allows a non-admin user to update their own share", func() {
+ insertShare("own-share-upd", ownerUser.ID)
+ ctx := request.WithUser(log.NewContext(context.TODO()), ownerUser)
+ repo := NewShareRepository(ctx, GetDBXBuilder())
+ err := repo.(rest.Persistable).Update("own-share-upd", &model.Share{Description: "Updated"}, "description")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("denies a non-admin user from updating another user's share", func() {
+ insertShare("other-share-upd", ownerUser.ID)
+ ctx := request.WithUser(log.NewContext(context.TODO()), otherUser)
+ repo := NewShareRepository(ctx, GetDBXBuilder())
+ err := repo.(rest.Persistable).Update("other-share-upd", &model.Share{Description: "Hacked"}, "description")
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+
+ It("allows an admin to update any user's share", func() {
+ insertShare("admin-upd-share", ownerUser.ID)
+ ctx := request.WithUser(log.NewContext(context.TODO()), adminUser)
+ repo := NewShareRepository(ctx, GetDBXBuilder())
+ err := repo.(rest.Persistable).Update("admin-upd-share", &model.Share{Description: "Admin Updated"}, "description")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ It("allows headless context (no user) to update a share", func() {
+ insertShare("headless-upd-share", ownerUser.ID)
+ repo := NewShareRepository(context.Background(), GetDBXBuilder())
+ err := repo.(rest.Persistable).Update("headless-upd-share", &model.Share{Description: "Headless"}, "description")
+ Expect(err).ToNot(HaveOccurred())
+ })
+ })
+ })
})
diff --git a/persistence/sql_annotations.go b/persistence/sql_annotations.go
index 6691b553c..07bd96975 100644
--- a/persistence/sql_annotations.go
+++ b/persistence/sql_annotations.go
@@ -4,6 +4,7 @@ import (
"database/sql"
"errors"
"fmt"
+ "strings"
"time"
. "github.com/Masterminds/squirrel"
@@ -17,7 +18,7 @@ const annotationTable = "annotation"
func (r sqlRepository) withAnnotation(query SelectBuilder, idField string) SelectBuilder {
userID := loggedUser(r.ctx).ID
if userID == invalidUserId {
- return query
+ return query.Columns(fmt.Sprintf("%s.average_rating", r.tableName))
}
query = query.
LeftJoin("annotation on ("+
@@ -28,6 +29,7 @@ func (r sqlRepository) withAnnotation(query SelectBuilder, idField string) Selec
"coalesce(rating, 0) as rating",
"starred_at",
"play_date",
+ "rated_at",
)
if conf.Server.AlbumPlayCountMode == consts.AlbumPlayCountModeNormalized && r.tableName == "album" {
query = query.Columns(
@@ -37,9 +39,24 @@ func (r sqlRepository) withAnnotation(query SelectBuilder, idField string) Selec
query = query.Columns("coalesce(play_count, 0) as play_count")
}
+ query = query.Columns(fmt.Sprintf("%s.average_rating", r.tableName))
+
return query
}
+func annotationBoolFilter(field string) func(string, any) Sqlizer {
+ return func(_ string, value any) Sqlizer {
+ v, ok := value.(string)
+ if !ok {
+ return nil
+ }
+ if strings.ToLower(v) == "true" {
+ return Expr(fmt.Sprintf("COALESCE(%s, 0) > 0", field))
+ }
+ return Expr(fmt.Sprintf("COALESCE(%s, 0) = 0", field))
+ }
+}
+
func (r sqlRepository) annId(itemID ...string) And {
userID := loggedUser(r.ctx).ID
return And{
@@ -49,7 +66,7 @@ func (r sqlRepository) annId(itemID ...string) And {
}
}
-func (r sqlRepository) annUpsert(values map[string]interface{}, itemIDs ...string) error {
+func (r sqlRepository) annUpsert(values map[string]any, itemIDs ...string) error {
upd := Update(annotationTable).Where(r.annId(itemIDs...))
for f, v := range values {
upd = upd.Set(f, v)
@@ -73,11 +90,27 @@ func (r sqlRepository) annUpsert(values map[string]interface{}, itemIDs ...strin
func (r sqlRepository) SetStar(starred bool, ids ...string) error {
starredAt := time.Now()
- return r.annUpsert(map[string]interface{}{"starred": starred, "starred_at": starredAt}, ids...)
+ return r.annUpsert(map[string]any{"starred": starred, "starred_at": starredAt}, ids...)
}
func (r sqlRepository) SetRating(rating int, itemID string) error {
- return r.annUpsert(map[string]interface{}{"rating": rating}, itemID)
+ ratedAt := time.Now()
+ err := r.annUpsert(map[string]any{"rating": rating, "rated_at": ratedAt}, itemID)
+ if err != nil {
+ return err
+ }
+ return r.updateAvgRating(itemID)
+}
+
+func (r sqlRepository) updateAvgRating(itemID string) error {
+ upd := Update(r.tableName).
+ Where(Eq{"id": itemID}).
+ Set("average_rating", Expr(
+ "coalesce((select round(avg(rating), 2) from annotation where item_id = ? and item_type = ? and rating > 0), 0)",
+ itemID, r.tableName,
+ ))
+ _, err := r.executeSQL(upd)
+ return err
}
func (r sqlRepository) IncPlayCount(itemID string, ts time.Time) error {
@@ -88,7 +121,7 @@ func (r sqlRepository) IncPlayCount(itemID string, ts time.Time) error {
if c == 0 || errors.Is(err, sql.ErrNoRows) {
userID := loggedUser(r.ctx).ID
- values := map[string]interface{}{}
+ values := map[string]any{}
values["user_id"] = userID
values["item_type"] = r.tableName
values["item_id"] = itemID
@@ -119,7 +152,7 @@ func (r sqlRepository) cleanAnnotations() error {
del := Delete(annotationTable).Where(Eq{"item_type": r.tableName}).Where("item_id not in (select id from " + r.tableName + ")")
c, err := r.executeSQL(del)
if err != nil {
- return fmt.Errorf("error cleaning up annotations: %w", err)
+ return fmt.Errorf("error cleaning up %s annotations: %w", r.tableName, err)
}
if c > 0 {
log.Debug(r.ctx, "Clean-up annotations", "table", r.tableName, "totalDeleted", c)
diff --git a/persistence/sql_annotations_test.go b/persistence/sql_annotations_test.go
new file mode 100644
index 000000000..15efc5dc7
--- /dev/null
+++ b/persistence/sql_annotations_test.go
@@ -0,0 +1,153 @@
+package persistence
+
+import (
+ "context"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Annotation Filters", func() {
+ var (
+ albumRepo *albumRepository
+ albumWithoutAnnotation model.Album
+ )
+
+ BeforeEach(func() {
+ ctx := request.WithUser(context.Background(), model.User{ID: "userid", UserName: "johndoe"})
+ albumRepo = NewAlbumRepository(ctx, GetDBXBuilder()).(*albumRepository)
+
+ // Create album without any annotation (no star, no rating)
+ albumWithoutAnnotation = model.Album{ID: "no-annotation-album", Name: "No Annotation", LibraryID: 1}
+ Expect(albumRepo.Put(&albumWithoutAnnotation)).To(Succeed())
+ })
+
+ AfterEach(func() {
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": albumWithoutAnnotation.ID}))
+ })
+
+ Describe("annotationBoolFilter", func() {
+ DescribeTable("creates correct SQL expressions",
+ func(field, value string, expectedSQL string, expectedArgs []any) {
+ sqlizer := annotationBoolFilter(field)(field, value)
+ sql, args, err := sqlizer.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(Equal(expectedSQL))
+ Expect(args).To(Equal(expectedArgs))
+ },
+ Entry("starred=true", "starred", "true", "COALESCE(starred, 0) > 0", []any(nil)),
+ Entry("starred=false", "starred", "false", "COALESCE(starred, 0) = 0", []any(nil)),
+ Entry("starred=True (case insensitive)", "starred", "True", "COALESCE(starred, 0) > 0", []any(nil)),
+ Entry("rating=true", "rating", "true", "COALESCE(rating, 0) > 0", []any(nil)),
+ )
+
+ It("returns nil if value is not a string", func() {
+ sqlizer := annotationBoolFilter("starred")("starred", 123)
+ Expect(sqlizer).To(BeNil())
+ })
+ })
+
+ Describe("starredFilter", func() {
+ It("false includes items without annotations", func() {
+ albums, err := albumRepo.GetAll(model.QueryOptions{
+ Filters: annotationBoolFilter("starred")("starred", "false"),
+ })
+ Expect(err).ToNot(HaveOccurred())
+
+ var found bool
+ for _, a := range albums {
+ if a.ID == albumWithoutAnnotation.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "Item without annotation should be included in starred=false filter")
+ })
+
+ It("true excludes items without annotations", func() {
+ albums, err := albumRepo.GetAll(model.QueryOptions{
+ Filters: annotationBoolFilter("starred")("starred", "true"),
+ })
+ Expect(err).ToNot(HaveOccurred())
+
+ for _, a := range albums {
+ Expect(a.ID).ToNot(Equal(albumWithoutAnnotation.ID))
+ }
+ })
+ })
+
+ Describe("hasRatingFilter", func() {
+ It("false includes items without annotations", func() {
+ albums, err := albumRepo.GetAll(model.QueryOptions{
+ Filters: annotationBoolFilter("rating")("rating", "false"),
+ })
+ Expect(err).ToNot(HaveOccurred())
+
+ var found bool
+ for _, a := range albums {
+ if a.ID == albumWithoutAnnotation.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "Item without annotation should be included in has_rating=false filter")
+ })
+
+ It("true excludes items without annotations", func() {
+ albums, err := albumRepo.GetAll(model.QueryOptions{
+ Filters: annotationBoolFilter("rating")("rating", "true"),
+ })
+ Expect(err).ToNot(HaveOccurred())
+
+ for _, a := range albums {
+ Expect(a.ID).ToNot(Equal(albumWithoutAnnotation.ID))
+ }
+ })
+
+ It("true includes items with rating > 0", func() {
+ // Create album with rating 1
+ ratedAlbum := model.Album{ID: "rated-album", Name: "Rated Album", LibraryID: 1}
+ Expect(albumRepo.Put(&ratedAlbum)).To(Succeed())
+ Expect(albumRepo.SetRating(1, ratedAlbum.ID)).To(Succeed())
+ defer func() {
+ _, _ = albumRepo.executeSQL(squirrel.Delete("annotation").Where(squirrel.Eq{"item_id": ratedAlbum.ID}))
+ _, _ = albumRepo.executeSQL(squirrel.Delete("album").Where(squirrel.Eq{"id": ratedAlbum.ID}))
+ }()
+
+ albums, err := albumRepo.GetAll(model.QueryOptions{
+ Filters: annotationBoolFilter("rating")("rating", "true"),
+ })
+ Expect(err).ToNot(HaveOccurred())
+
+ var found bool
+ for _, a := range albums {
+ if a.ID == ratedAlbum.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "Album with rating 5 should be included in has_rating=true filter")
+ })
+ })
+
+ It("ignores invalid filter values (not strings)", func() {
+ res, err := albumRepo.ReadAll(rest.QueryOptions{
+ Filters: map[string]any{"starred": 123},
+ })
+ Expect(err).ToNot(HaveOccurred())
+ albums := res.(model.Albums)
+
+ var found bool
+ for _, a := range albums {
+ if a.ID == albumWithoutAnnotation.ID {
+ found = true
+ break
+ }
+ }
+ Expect(found).To(BeTrue(), "Item without annotation should be included when filter is ignored")
+ })
+})
diff --git a/persistence/sql_base_repository.go b/persistence/sql_base_repository.go
index ce026a3c3..fd263d37b 100644
--- a/persistence/sql_base_repository.go
+++ b/persistence/sql_base_repository.go
@@ -196,7 +196,7 @@ func (r *sqlRepository) withTableName(filter filterFunc) filterFunc {
}
// libraryIdFilter is a filter function to be added to resources that have a library_id column.
-func libraryIdFilter(_ string, value interface{}) Sqlizer {
+func libraryIdFilter(_ string, value any) Sqlizer {
return Eq{"library_id": value}
}
@@ -281,7 +281,7 @@ func (r sqlRepository) toSQL(sq Sqlizer) (string, dbx.Params, error) {
return result, params, nil
}
-func (r sqlRepository) queryOne(sq Sqlizer, response interface{}) error {
+func (r sqlRepository) queryOne(sq Sqlizer, response any) error {
query, args, err := r.toSQL(sq)
if err != nil {
return err
@@ -328,7 +328,7 @@ func queryWithStableResults[T any](r sqlRepository, sq SelectBuilder, options ..
}, nil
}
-func (r sqlRepository) queryAll(sq SelectBuilder, response interface{}, options ...model.QueryOptions) error {
+func (r sqlRepository) queryAll(sq SelectBuilder, response any, options ...model.QueryOptions) error {
if len(options) > 0 && options[0].Offset > 0 {
sq = r.optimizePagination(sq, options[0])
}
@@ -347,7 +347,7 @@ func (r sqlRepository) queryAll(sq SelectBuilder, response interface{}, options
}
// queryAllSlice is a helper function to query a single column and return the result in a slice
-func (r sqlRepository) queryAllSlice(sq SelectBuilder, response interface{}) error {
+func (r sqlRepository) queryAllSlice(sq SelectBuilder, response any) error {
query, args, err := r.toSQL(sq)
if err != nil {
return err
@@ -394,7 +394,7 @@ func (r sqlRepository) count(countQuery SelectBuilder, options ...model.QueryOpt
return res.Count, err
}
-func (r sqlRepository) putByMatch(filter Sqlizer, id string, m interface{}, colsToUpdate ...string) (string, error) {
+func (r sqlRepository) putByMatch(filter Sqlizer, id string, m any, colsToUpdate ...string) (string, error) {
if id != "" {
return r.put(id, m, colsToUpdate...)
}
@@ -408,14 +408,14 @@ func (r sqlRepository) putByMatch(filter Sqlizer, id string, m interface{}, cols
return r.put(res.ID, m, colsToUpdate...)
}
-func (r sqlRepository) put(id string, m interface{}, colsToUpdate ...string) (newId string, err error) {
+func (r sqlRepository) put(id string, m any, colsToUpdate ...string) (newId string, err error) {
values, err := toSQLArgs(m)
if err != nil {
return "", fmt.Errorf("error preparing values to write to DB: %w", err)
}
// If there's an ID, try to update first
if id != "" {
- updateValues := map[string]interface{}{}
+ updateValues := map[string]any{}
// This is a map of the columns that need to be updated, if specified
c2upd := slice.ToMap(colsToUpdate, func(s string) (string, struct{}) {
diff --git a/persistence/sql_bookmarks.go b/persistence/sql_bookmarks.go
index 52c4b8e9c..19f16b231 100644
--- a/persistence/sql_bookmarks.go
+++ b/persistence/sql_bookmarks.go
@@ -37,7 +37,7 @@ func (r sqlRepository) bmkID(itemID ...string) And {
func (r sqlRepository) bmkUpsert(itemID, comment string, position int64) error {
client, _ := request.ClientFrom(r.ctx)
user, _ := request.UserFrom(r.ctx)
- values := map[string]interface{}{
+ values := map[string]any{
"comment": comment,
"position": position,
"updated_at": time.Now(),
@@ -148,10 +148,10 @@ func (r sqlRepository) cleanBookmarks() error {
del := Delete(bookmarkTable).Where(Eq{"item_type": r.tableName}).Where("item_id not in (select id from " + r.tableName + ")")
c, err := r.executeSQL(del)
if err != nil {
- return fmt.Errorf("error cleaning up bookmarks: %w", err)
+ return fmt.Errorf("error cleaning up %s bookmarks: %w", r.tableName, err)
}
if c > 0 {
- log.Debug(r.ctx, "Clean-up bookmarks", "totalDeleted", c)
+ log.Debug(r.ctx, "Clean-up bookmarks", "totalDeleted", c, "itemType", r.tableName)
}
return nil
}
diff --git a/persistence/sql_participations.go b/persistence/sql_participations.go
index d88eca45e..38b0203fa 100644
--- a/persistence/sql_participations.go
+++ b/persistence/sql_participations.go
@@ -51,8 +51,10 @@ func unmarshalParticipants(data string) (model.Participants, error) {
}
func (r sqlRepository) updateParticipants(itemID string, participants model.Participants) error {
- ids := participants.AllIDs()
- sqd := Delete(r.tableName + "_artists").Where(And{Eq{r.tableName + "_id": itemID}, NotEq{"artist_id": ids}})
+ // Delete all existing participant entries for this item.
+ // This ensures stale role associations are removed when an artist's role changes
+ // (e.g., an artist was both albumartist and composer, but is now only composer).
+ sqd := Delete(r.tableName + "_artists").Where(Eq{r.tableName + "_id": itemID})
_, err := r.executeSQL(sqd)
if err != nil {
return err
diff --git a/persistence/sql_restful.go b/persistence/sql_restful.go
index ff0d06a8b..02162387c 100644
--- a/persistence/sql_restful.go
+++ b/persistence/sql_restful.go
@@ -109,11 +109,10 @@ func booleanFilter(field string, value any) Sqlizer {
func fullTextFilter(tableName string, mbidFields ...string) func(string, any) Sqlizer {
return func(field string, value any) Sqlizer {
v := strings.ToLower(value.(string))
- cond := cmp.Or(
+ return cmp.Or[Sqlizer](
mbidExpr(tableName, v, mbidFields...),
- fullTextExpr(tableName, v),
+ getSearchStrategy(tableName, v),
)
- return cond
}
}
diff --git a/persistence/sql_restful_test.go b/persistence/sql_restful_test.go
index fd95fbb31..32f418b8e 100644
--- a/persistence/sql_restful_test.go
+++ b/persistence/sql_restful_test.go
@@ -26,11 +26,13 @@ var _ = Describe("sqlRestful", func() {
Expect(r.parseRestFilters(context.Background(), options)).To(BeNil())
})
- It(`returns nil if tries a filter with fullTextExpr("'")`, func() {
+ It(`returns nil if tries a filter with legacySearchExpr("'")`, func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "legacy"
r.filterMappings = map[string]filterFunc{
"name": fullTextFilter("table"),
}
- options.Filters = map[string]interface{}{"name": "'"}
+ options.Filters = map[string]any{"name": "'"}
Expect(r.parseRestFilters(context.Background(), options)).To(BeEmpty())
})
@@ -40,32 +42,32 @@ var _ = Describe("sqlRestful", func() {
return nil
},
}
- options.Filters = map[string]interface{}{"name": "joe"}
+ options.Filters = map[string]any{"name": "joe"}
Expect(r.parseRestFilters(context.Background(), options)).To(BeEmpty())
})
It("returns a '=' condition for 'id' filter", func() {
- options.Filters = map[string]interface{}{"id": "123"}
+ options.Filters = map[string]any{"id": "123"}
Expect(r.parseRestFilters(context.Background(), options)).To(Equal(squirrel.And{squirrel.Eq{"id": "123"}}))
})
It("returns a 'in' condition for multiples 'id' filters", func() {
- options.Filters = map[string]interface{}{"id": []string{"123", "456"}}
+ options.Filters = map[string]any{"id": []string{"123", "456"}}
Expect(r.parseRestFilters(context.Background(), options)).To(Equal(squirrel.And{squirrel.Eq{"id": []string{"123", "456"}}}))
})
It("returns a 'like' condition for other filters", func() {
- options.Filters = map[string]interface{}{"name": "joe"}
+ options.Filters = map[string]any{"name": "joe"}
Expect(r.parseRestFilters(context.Background(), options)).To(Equal(squirrel.And{squirrel.Like{"name": "joe%"}}))
})
It("uses the custom filter", func() {
r.filterMappings = map[string]filterFunc{
- "test": func(field string, value interface{}) squirrel.Sqlizer {
+ "test": func(field string, value any) squirrel.Sqlizer {
return squirrel.Gt{field: value}
},
}
- options.Filters = map[string]interface{}{"test": 100}
+ options.Filters = map[string]any{"test": 100}
Expect(r.parseRestFilters(context.Background(), options)).To(Equal(squirrel.And{squirrel.Gt{"test": 100}}))
})
})
@@ -77,6 +79,7 @@ var _ = Describe("sqlRestful", func() {
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "legacy"
tableName = "test_table"
mbidFields = []string{"mbid", "artist_mbid"}
filter = fullTextFilter(tableName, mbidFields...)
@@ -99,11 +102,11 @@ var _ = Describe("sqlRestful", func() {
uuid := "550e8400-e29b-41d4-a716-446655440000"
result := noMbidFilter("search", uuid)
- // mbidExpr with no fields returns nil, so cmp.Or falls back to fullTextExpr
- expected := squirrel.And{
- squirrel.Like{"test_table.full_text": "% 550e8400-e29b-41d4-a716-446655440000%"},
- }
- Expect(result).To(Equal(expected))
+ // mbidExpr with no fields returns nil, so cmp.Or falls back to search strategy
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(ContainElement("% 550e8400-e29b-41d4-a716-446655440000%"))
})
})
@@ -111,54 +114,75 @@ var _ = Describe("sqlRestful", func() {
It("returns full text search condition only", func() {
result := filter("search", "beatles")
- // mbidExpr returns nil for non-UUIDs, so fullTextExpr result is returned directly
- expected := squirrel.And{
- squirrel.Like{"test_table.full_text": "% beatles%"},
- }
- Expect(result).To(Equal(expected))
+ // mbidExpr returns nil for non-UUIDs, so search strategy result is returned directly
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(ContainElement("% beatles%"))
})
It("handles multi-word search terms", func() {
result := filter("search", "the beatles abbey road")
- // Should return And condition directly
- andCondition, ok := result.(squirrel.And)
- Expect(ok).To(BeTrue())
- Expect(andCondition).To(HaveLen(4))
-
- // Check that all words are present (order may vary)
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "% the%"}))
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "% beatles%"}))
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "% abbey%"}))
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "% road%"}))
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ // All words should be present as LIKE conditions
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(HaveLen(4))
+ Expect(args).To(ContainElement("% the%"))
+ Expect(args).To(ContainElement("% beatles%"))
+ Expect(args).To(ContainElement("% abbey%"))
+ Expect(args).To(ContainElement("% road%"))
})
})
Context("when SearchFullString config changes behavior", func() {
It("uses different separator with SearchFullString=false", func() {
- conf.Server.SearchFullString = false
+ conf.Server.Search.FullString = false
result := filter("search", "test query")
- andCondition, ok := result.(squirrel.And)
- Expect(ok).To(BeTrue())
- Expect(andCondition).To(HaveLen(2))
-
- // Check that all words are present with leading space (order may vary)
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "% test%"}))
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "% query%"}))
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(HaveLen(2))
+ Expect(args).To(ContainElement("% test%"))
+ Expect(args).To(ContainElement("% query%"))
})
It("uses no separator with SearchFullString=true", func() {
- conf.Server.SearchFullString = true
+ conf.Server.Search.FullString = true
result := filter("search", "test query")
- andCondition, ok := result.(squirrel.And)
- Expect(ok).To(BeTrue())
- Expect(andCondition).To(HaveLen(2))
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(HaveLen(2))
+ Expect(args).To(ContainElement("%test%"))
+ Expect(args).To(ContainElement("%query%"))
+ })
+ })
- // Check that all words are present without leading space (order may vary)
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "%test%"}))
- Expect(andCondition).To(ContainElement(squirrel.Like{"test_table.full_text": "%query%"}))
+ Context("single-character queries (regression: must not be rejected)", func() {
+ It("returns valid filter for single-char query with legacy backend", func() {
+ conf.Server.Search.Backend = "legacy"
+ result := filter("search", "a")
+ Expect(result).ToNot(BeNil(), "single-char REST filter must not be dropped")
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("LIKE"))
+ Expect(args).ToNot(BeEmpty())
+ })
+
+ It("returns valid filter for single-char query with FTS backend", func() {
+ conf.Server.Search.Backend = "fts"
+ conf.Server.Search.FullString = false
+ ftsFilter := fullTextFilter(tableName, mbidFields...)
+ result := ftsFilter("search", "a")
+ Expect(result).ToNot(BeNil(), "single-char REST filter must not be dropped")
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("MATCH"))
+ Expect(args).ToNot(BeEmpty())
})
})
@@ -176,10 +200,10 @@ var _ = Describe("sqlRestful", func() {
It("handles special characters that are sanitized", func() {
result := filter("search", "don't")
- expected := squirrel.And{
- squirrel.Like{"test_table.full_text": "% dont%"}, // str.SanitizeStrings removes quotes
- }
- Expect(result).To(Equal(expected))
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(ContainElement("% dont%"))
})
It("returns nil for single quote (SQL injection protection)", func() {
@@ -203,31 +227,30 @@ var _ = Describe("sqlRestful", func() {
result := filter("search", "550e8400-invalid-uuid")
// Should return full text filter since UUID is invalid
- expected := squirrel.And{
- squirrel.Like{"test_table.full_text": "% 550e8400-invalid-uuid%"},
- }
- Expect(result).To(Equal(expected))
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(ContainElement("% 550e8400-invalid-uuid%"))
})
It("handles empty mbid fields array", func() {
emptyMbidFilter := fullTextFilter(tableName, []string{}...)
result := emptyMbidFilter("search", "test")
- // mbidExpr with empty fields returns nil, so cmp.Or falls back to fullTextExpr
- expected := squirrel.And{
- squirrel.Like{"test_table.full_text": "% test%"},
- }
- Expect(result).To(Equal(expected))
+ // mbidExpr with empty fields returns nil, so search strategy result is returned directly
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(ContainElement("% test%"))
})
It("converts value to lowercase before processing", func() {
result := filter("search", "TEST")
- // The function converts to lowercase internally
- expected := squirrel.And{
- squirrel.Like{"test_table.full_text": "% test%"},
- }
- Expect(result).To(Equal(expected))
+ sql, args, err := result.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("test_table.full_text LIKE"))
+ Expect(args).To(ContainElement("% test%"))
})
})
})
diff --git a/persistence/sql_search.go b/persistence/sql_search.go
index 0d3bfb743..43965ebb7 100644
--- a/persistence/sql_search.go
+++ b/persistence/sql_search.go
@@ -15,36 +15,71 @@ func formatFullText(text ...string) string {
return " " + fullText
}
-// doSearch performs a full-text search with the specified parameters.
-// The naturalOrder is used to sort results when no full-text filter is applied. It is useful for cases like
-// OpenSubsonic, where an empty search query should return all results in a natural order. Normally the parameter
-// should be `tableName + ".rowid"`, but some repositories (ex: artist) may use a different natural order.
-func (r sqlRepository) doSearch(sq SelectBuilder, q string, offset, size int, results any, naturalOrder string, orderBys ...string) error {
+// searchConfig holds per-repository constants for doSearch.
+type searchConfig struct {
+ NaturalOrder string // ORDER BY for empty-query results (e.g. "album.rowid")
+ OrderBy []string // ORDER BY for text search results (e.g. ["name"])
+ MBIDFields []string // columns to match when query is a UUID
+ // LibraryFilter overrides the default applyLibraryFilter for FTS Phase 1.
+ // Needed when library access requires a junction table (e.g. artist → library_artist).
+ LibraryFilter func(sq SelectBuilder) SelectBuilder
+}
+
+// searchStrategy defines how to execute a text search against a repository table.
+// options carries filters and pagination that must reach all query phases,
+// including FTS Phase 1 which builds its own query outside sq.
+type searchStrategy interface {
+ Sqlizer
+ execute(r sqlRepository, sq SelectBuilder, dest any, cfg searchConfig, options model.QueryOptions) error
+}
+
+// getSearchStrategy returns the appropriate search strategy based on config and query content.
+// Returns nil when the query produces no searchable tokens.
+func getSearchStrategy(tableName, query string) searchStrategy {
+ if conf.Server.Search.Backend == "legacy" || conf.Server.Search.FullString {
+ return newLegacySearch(tableName, query)
+ }
+ if containsCJK(query) {
+ return newLikeSearch(tableName, query)
+ }
+ return newFTSSearch(tableName, query)
+}
+
+// doSearch dispatches a search query: empty → natural order, UUID → MBID match,
+// otherwise delegates to getSearchStrategy. sq must already have LIMIT/OFFSET set
+// via newSelect(options...). options is forwarded so FTS Phase 1 can apply the same
+// filters and pagination independently.
+func (r sqlRepository) doSearch(sq SelectBuilder, q string, results any, cfg searchConfig, options model.QueryOptions) error {
q = strings.TrimSpace(q)
q = strings.TrimSuffix(q, "*")
+
+ sq = sq.Where(Eq{r.tableName + ".missing": false})
+
+ // Empty query (OpenSubsonic `search3?query=""`) — return all in natural order.
+ if q == "" || q == `""` {
+ sq = sq.OrderBy(cfg.NaturalOrder)
+ return r.queryAll(sq, results, options)
+ }
+
+ // MBID search: if query is a valid UUID, search by MBID fields instead
+ if uuid.Validate(q) == nil && len(cfg.MBIDFields) > 0 {
+ sq = sq.Where(mbidExpr(r.tableName, q, cfg.MBIDFields...))
+ return r.queryAll(sq, results)
+ }
+
+ // Min-length guard: single-character queries are too broad for search3.
+ // This check lives here (not in the strategies) so that fullTextFilter
+ // (REST filter path) can still use single-character queries.
if len(q) < 2 {
return nil
}
- filter := fullTextExpr(r.tableName, q)
- if filter != nil {
- sq = sq.Where(filter)
- sq = sq.OrderBy(orderBys...)
- } else {
- // This is to speed up the results of `search3?query=""`, for OpenSubsonic
- // If the filter is empty, we sort by the specified natural order.
- sq = sq.OrderBy(naturalOrder)
+ strategy := getSearchStrategy(r.tableName, q)
+ if strategy == nil {
+ return nil
}
- sq = sq.Where(Eq{r.tableName + ".missing": false})
- sq = sq.Limit(uint64(size)).Offset(uint64(offset))
- return r.queryAll(sq, results, model.QueryOptions{Offset: offset})
-}
-func (r sqlRepository) searchByMBID(sq SelectBuilder, mbid string, mbidFields []string, results any) error {
- sq = sq.Where(mbidExpr(r.tableName, mbid, mbidFields...))
- sq = sq.Where(Eq{r.tableName + ".missing": false})
-
- return r.queryAll(sq, results)
+ return strategy.execute(r, sq, results, cfg, options)
}
func mbidExpr(tableName, mbid string, mbidFields ...string) Sqlizer {
@@ -58,20 +93,3 @@ func mbidExpr(tableName, mbid string, mbidFields ...string) Sqlizer {
}
return Or(cond)
}
-
-func fullTextExpr(tableName string, s string) Sqlizer {
- q := str.SanitizeStrings(s)
- if q == "" {
- return nil
- }
- var sep string
- if !conf.Server.SearchFullString {
- sep = " "
- }
- parts := strings.Split(q, " ")
- filters := And{}
- for _, part := range parts {
- filters = append(filters, Like{tableName + ".full_text": "%" + sep + part + "%"})
- }
- return filters
-}
diff --git a/persistence/sql_search_fts.go b/persistence/sql_search_fts.go
new file mode 100644
index 000000000..9eb01f0cf
--- /dev/null
+++ b/persistence/sql_search_fts.go
@@ -0,0 +1,422 @@
+package persistence
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ . "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+)
+
+// containsCJK returns true if the string contains any CJK (Chinese/Japanese/Korean) characters.
+// CJK text doesn't use spaces between words, so FTS5's unicode61 tokenizer treats entire
+// CJK phrases as single tokens, making token-based search ineffective for CJK content.
+func containsCJK(s string) bool {
+ for _, r := range s {
+ if unicode.Is(unicode.Han, r) ||
+ unicode.Is(unicode.Hiragana, r) ||
+ unicode.Is(unicode.Katakana, r) ||
+ unicode.Is(unicode.Hangul, r) {
+ return true
+ }
+ }
+ return false
+}
+
+// fts5SpecialChars matches characters that should be stripped from user input.
+// We keep only Unicode letters, numbers, whitespace, * (prefix wildcard), " (phrase quotes),
+// and \x00 (internal placeholder marker). All punctuation is removed because the unicode61
+// tokenizer treats it as token separators, and characters like ' can cause FTS5 parse errors
+// as unbalanced string delimiters.
+var fts5SpecialChars = regexp.MustCompile(`[^\p{L}\p{N}\s*"\x00]`)
+
+// fts5PunctStrip strips everything except letters and numbers (no whitespace, wildcards, or quotes).
+// Used for normalizing words at index time to create concatenated forms (e.g., "R.E.M." → "REM").
+var fts5PunctStrip = regexp.MustCompile(`[^\p{L}\p{N}]`)
+
+// fts5Operators matches FTS5 boolean operators as whole words (case-insensitive).
+var fts5Operators = regexp.MustCompile(`(?i)\b(AND|OR|NOT|NEAR)\b`)
+
+// fts5LeadingStar matches a * at the start of a token. FTS5 only supports * at the end (prefix queries).
+var fts5LeadingStar = regexp.MustCompile(`(^|[\s])\*+`)
+
+// normalizeForFTS takes multiple strings, strips non-letter/non-number characters from each word,
+// and returns a space-separated string of words that changed after stripping (deduplicated).
+// This is used at index time to create concatenated forms: "R.E.M." → "REM", "AC/DC" → "ACDC".
+func normalizeForFTS(values ...string) string {
+ seen := make(map[string]struct{})
+ var result []string
+ for _, v := range values {
+ for _, word := range strings.Fields(v) {
+ stripped := fts5PunctStrip.ReplaceAllString(word, "")
+ if stripped == "" || stripped == word {
+ continue
+ }
+ lower := strings.ToLower(stripped)
+ if _, ok := seen[lower]; ok {
+ continue
+ }
+ seen[lower] = struct{}{}
+ result = append(result, stripped)
+ }
+ }
+ return strings.Join(result, " ")
+}
+
+// isSingleUnicodeLetter returns true if token is exactly one Unicode letter.
+func isSingleUnicodeLetter(token string) bool {
+ r, size := utf8.DecodeRuneInString(token)
+ return size == len(token) && size > 0 && unicode.IsLetter(r)
+}
+
+// namePunctuation is the set of characters commonly used as separators in artist/album
+// names (hyphens, slashes, dots, apostrophes). Only words containing these are candidates
+// for punctuated-word processing; other special characters (^, :, &) are just stripped.
+const namePunctuation = `-/.''`
+
+// processPunctuatedWords handles words with embedded name punctuation before the general
+// special-character stripping. For each punctuated word it produces either:
+// - A quoted phrase for dotted abbreviations: R.E.M. → "R E M"
+// - A phrase+concat OR for other patterns: a-ha → ("a ha" OR aha*)
+func processPunctuatedWords(input string, phrases []string) (string, []string) {
+ words := strings.Fields(input)
+ var result []string
+ for _, w := range words {
+ if strings.HasPrefix(w, "\x00") || strings.ContainsAny(w, `*"`) || !strings.ContainsAny(w, namePunctuation) {
+ result = append(result, w)
+ continue
+ }
+ concat := fts5PunctStrip.ReplaceAllString(w, "")
+ if concat == "" || concat == w {
+ result = append(result, w)
+ continue
+ }
+ subTokens := strings.Fields(fts5SpecialChars.ReplaceAllString(w, " "))
+ if len(subTokens) < 2 {
+ // Single sub-token after splitting (e.g., N' → N): just use the stripped form
+ result = append(result, concat)
+ continue
+ }
+ // Dotted abbreviations (R.E.M., U.K.) — all single letters separated by dots only
+ if isDottedAbbreviation(w, subTokens) {
+ phrases = append(phrases, fmt.Sprintf(`"%s"`, strings.Join(subTokens, " ")))
+ } else {
+ // Punctuated names (a-ha, AC/DC, Jay-Z) — phrase for adjacency + concat for search_normalized
+ phrases = append(phrases, fmt.Sprintf(`("%s" OR %s*)`, strings.Join(subTokens, " "), concat))
+ }
+ result = append(result, fmt.Sprintf("\x00PHRASE%d\x00", len(phrases)-1))
+ }
+ return strings.Join(result, " "), phrases
+}
+
+// isDottedAbbreviation returns true if w uses only dots as punctuation and all sub-tokens
+// are single letters (e.g., "R.E.M.", "U.K." but not "a-ha" or "AC/DC").
+func isDottedAbbreviation(w string, subTokens []string) bool {
+ for _, r := range w {
+ if !unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '.' {
+ return false
+ }
+ }
+ for _, st := range subTokens {
+ if !isSingleUnicodeLetter(st) {
+ return false
+ }
+ }
+ return true
+}
+
+// buildFTS5Query preprocesses user input into a safe FTS5 MATCH expression.
+// It preserves quoted phrases and * prefix wildcards, neutralizes FTS5 operators
+// (by lowercasing them, since FTS5 operators are case-sensitive) and strips
+// special characters to prevent query injection.
+func buildFTS5Query(userInput string) string {
+ q := strings.TrimSpace(userInput)
+ if q == "" || q == `""` {
+ return ""
+ }
+
+ var phrases []string
+ result := q
+ for {
+ start := strings.Index(result, `"`)
+ if start == -1 {
+ break
+ }
+ end := strings.Index(result[start+1:], `"`)
+ if end == -1 {
+ // Unmatched quote — remove it
+ result = result[:start] + result[start+1:]
+ break
+ }
+ end += start + 1
+ phrase := result[start : end+1] // includes quotes
+ phrases = append(phrases, phrase)
+ result = result[:start] + fmt.Sprintf("\x00PHRASE%d\x00", len(phrases)-1) + result[end+1:]
+ }
+
+ // Neutralize FTS5 operators by lowercasing them (FTS5 operators are case-sensitive:
+ // AND, OR, NOT, NEAR are operators, but and, or, not, near are plain tokens)
+ result = fts5Operators.ReplaceAllStringFunc(result, strings.ToLower)
+
+ // Handle words with embedded punctuation (a-ha, AC/DC, R.E.M.) before stripping
+ result, phrases = processPunctuatedWords(result, phrases)
+
+ result = fts5SpecialChars.ReplaceAllString(result, " ")
+ result = fts5LeadingStar.ReplaceAllString(result, "$1")
+ tokens := strings.Fields(result)
+
+ // Append * to plain tokens for prefix matching (e.g., "love" → "love*").
+ // Skip tokens that are already wildcarded or are quoted phrase placeholders.
+ for i, t := range tokens {
+ if strings.HasPrefix(t, "\x00") || strings.HasSuffix(t, "*") {
+ continue
+ }
+ tokens[i] = t + "*"
+ }
+
+ result = strings.Join(tokens, " ")
+
+ for i, phrase := range phrases {
+ placeholder := fmt.Sprintf("\x00PHRASE%d\x00", i)
+ result = strings.ReplaceAll(result, placeholder, phrase)
+ }
+
+ return result
+}
+
+// ftsColumn pairs an FTS5 column name with its BM25 relevance weight.
+type ftsColumn struct {
+ Name string
+ Weight float64
+}
+
+// ftsColumnDefs defines FTS5 columns and their BM25 relevance weights.
+// The order MUST match the column order in the FTS5 table definition (see migrations).
+// All columns are both searched and ranked. When adding indexed-but-not-searched
+// columns in the future, use Weight: 0 to exclude from the search column filter.
+var ftsColumnDefs = map[string][]ftsColumn{
+ "media_file": {
+ {"title", 10.0},
+ {"album", 5.0},
+ {"artist", 3.0},
+ {"album_artist", 3.0},
+ {"sort_title", 1.0},
+ {"sort_album_name", 1.0},
+ {"sort_artist_name", 1.0},
+ {"sort_album_artist_name", 1.0},
+ {"disc_subtitle", 1.0},
+ {"search_participants", 2.0},
+ {"search_normalized", 1.0},
+ },
+ "album": {
+ {"name", 10.0},
+ {"sort_album_name", 1.0},
+ {"album_artist", 3.0},
+ {"search_participants", 2.0},
+ {"discs", 1.0},
+ {"catalog_num", 1.0},
+ {"album_version", 1.0},
+ {"search_normalized", 1.0},
+ },
+ "artist": {
+ {"name", 10.0},
+ {"sort_artist_name", 1.0},
+ {"search_normalized", 1.0},
+ },
+}
+
+// ftsColumnFilters and ftsBM25Weights are precomputed from ftsColumnDefs at init time
+// to avoid per-query allocations.
+var (
+ ftsColumnFilters = map[string]string{}
+ ftsBM25Weights = map[string]string{}
+)
+
+func init() {
+ for table, cols := range ftsColumnDefs {
+ var names []string
+ weights := make([]string, len(cols))
+ for i, c := range cols {
+ if c.Weight > 0 {
+ names = append(names, c.Name)
+ }
+ weights[i] = fmt.Sprintf("%.1f", c.Weight)
+ }
+ ftsColumnFilters[table] = "{" + strings.Join(names, " ") + "}"
+ ftsBM25Weights[table] = strings.Join(weights, ", ")
+ }
+}
+
+// ftsSearch implements searchStrategy using FTS5 full-text search with BM25 ranking.
+type ftsSearch struct {
+ tableName string
+ ftsTable string
+ matchExpr string
+ rankExpr string
+}
+
+// ToSql returns a single-query fallback for the REST filter path (no two-phase split).
+func (s *ftsSearch) ToSql() (string, []interface{}, error) {
+ sql := s.tableName + ".rowid IN (SELECT rowid FROM " + s.ftsTable + " WHERE " + s.ftsTable + " MATCH ?)"
+ return sql, []interface{}{s.matchExpr}, nil
+}
+
+// execute runs a two-phase FTS5 search:
+// - Phase 1: lightweight rowid query (main table + FTS + library filter) for ranking and pagination.
+// - Phase 2: full SELECT with all JOINs, scoped to Phase 1's rowid set.
+//
+// Complex ORDER BY (function calls, aggregations) are dropped from Phase 1.
+func (s *ftsSearch) execute(r sqlRepository, sq SelectBuilder, dest any, cfg searchConfig, options model.QueryOptions) error {
+ qualifiedOrderBys := []string{s.rankExpr}
+ for _, ob := range cfg.OrderBy {
+ if qualified := qualifyOrderBy(s.tableName, ob); qualified != "" {
+ qualifiedOrderBys = append(qualifiedOrderBys, qualified)
+ }
+ }
+
+ // Phase 1: fresh query — must set LIMIT/OFFSET from options explicitly.
+ // Mirror applyOptions behavior: Max=0 means no limit, not LIMIT 0.
+ rowidQuery := Select(s.tableName+".rowid").
+ From(s.tableName).
+ Join(s.ftsTable+" ON "+s.ftsTable+".rowid = "+s.tableName+".rowid AND "+s.ftsTable+" MATCH ?", s.matchExpr).
+ Where(Eq{s.tableName + ".missing": false}).
+ OrderBy(qualifiedOrderBys...)
+ if options.Max > 0 {
+ rowidQuery = rowidQuery.Limit(uint64(options.Max))
+ }
+ if options.Offset > 0 {
+ rowidQuery = rowidQuery.Offset(uint64(options.Offset))
+ }
+
+ // Library filter + musicFolderId must be applied here, before pagination.
+ if cfg.LibraryFilter != nil {
+ rowidQuery = cfg.LibraryFilter(rowidQuery)
+ } else {
+ rowidQuery = r.applyLibraryFilter(rowidQuery)
+ }
+ if options.Filters != nil {
+ rowidQuery = rowidQuery.Where(options.Filters)
+ }
+
+ rowidSQL, rowidArgs, err := rowidQuery.ToSql()
+ if err != nil {
+ return fmt.Errorf("building FTS rowid query: %w", err)
+ }
+
+ // Phase 2: strip LIMIT/OFFSET from sq (Phase 1 handled pagination),
+ // join on the ranked rowid set to hydrate with full columns.
+ sq = sq.RemoveLimit().RemoveOffset()
+ rankedSubquery := fmt.Sprintf(
+ "(SELECT rowid as _rid, row_number() OVER () AS _rn FROM (%s)) AS _ranked",
+ rowidSQL,
+ )
+ sq = sq.Join(rankedSubquery+" ON "+s.tableName+".rowid = _ranked._rid", rowidArgs...)
+ sq = sq.OrderBy("_ranked._rn")
+ return r.queryAll(sq, dest)
+}
+
+// qualifyOrderBy prepends tableName to a simple column name. Returns empty string for
+// complex expressions (function calls, aggregations) that can't be used in Phase 1.
+func qualifyOrderBy(tableName, orderBy string) string {
+ orderBy = strings.TrimSpace(orderBy)
+ if orderBy == "" || strings.ContainsAny(orderBy, "(,") {
+ return ""
+ }
+ parts := strings.Fields(orderBy)
+ if !strings.Contains(parts[0], ".") {
+ parts[0] = tableName + "." + parts[0]
+ }
+ return strings.Join(parts, " ")
+}
+
+// ftsQueryDegraded returns true when the FTS query lost significant discriminating
+// content compared to the original input. This happens when special characters that
+// are part of the entity name (e.g., "1+", "C++", "!!!", "C#") get stripped by FTS
+// tokenization, leaving only very short/broad tokens. Also detects quoted phrases
+// that would be degraded by FTS5's unicode61 tokenizer (e.g., "1+" → token "1").
+func ftsQueryDegraded(original, ftsQuery string) bool {
+ original = strings.TrimSpace(original)
+ if original == "" || ftsQuery == "" {
+ return false
+ }
+ // Strip quotes from original for comparison — we want the raw content
+ stripped := strings.ReplaceAll(original, `"`, "")
+ // Extract the alphanumeric content from the original query
+ alphaNum := fts5PunctStrip.ReplaceAllString(stripped, "")
+ // If the original is entirely alphanumeric, nothing was stripped — not degraded
+ if len(alphaNum) == len(stripped) {
+ return false
+ }
+ // Check if all effective FTS tokens are very short (≤2 chars).
+ // Short tokens with prefix matching are too broad when special chars were stripped.
+ // For quoted phrases, extract the content and check the tokens inside.
+ tokens := strings.Fields(ftsQuery)
+ for _, t := range tokens {
+ t = strings.TrimSuffix(t, "*")
+ // Skip internal phrase placeholders
+ if strings.HasPrefix(t, "\x00") {
+ return false
+ }
+ // For OR groups from processPunctuatedWords (e.g., ("a ha" OR aha*)),
+ // the punctuated word was already handled meaningfully — not degraded.
+ if strings.HasPrefix(t, "(") {
+ return false
+ }
+ // For quoted phrases, check the tokens inside as FTS5 will tokenize them
+ if strings.HasPrefix(t, `"`) {
+ // Extract content between quotes
+ inner := strings.Trim(t, `"`)
+ innerAlpha := fts5PunctStrip.ReplaceAllString(inner, " ")
+ for _, it := range strings.Fields(innerAlpha) {
+ if len(it) > 2 {
+ return false
+ }
+ }
+ continue
+ }
+ if len(t) > 2 {
+ return false
+ }
+ }
+ return true
+}
+
+// newFTSSearch creates an FTS5 search strategy. Falls back to LIKE search if the
+// query produces no FTS tokens (e.g., punctuation-only like "!!!!!!!") or if FTS
+// tokenization stripped significant content from the query (e.g., "1+" → "1*").
+// Returns nil when the query produces no searchable tokens at all.
+func newFTSSearch(tableName, query string) searchStrategy {
+ q := buildFTS5Query(query)
+ if q == "" || ftsQueryDegraded(query, q) {
+ // Fallback: try LIKE search with the raw query
+ cleaned := strings.TrimSpace(strings.ReplaceAll(query, `"`, ""))
+ if cleaned != "" {
+ log.Trace("Search using LIKE fallback for non-tokenizable query", "table", tableName, "query", cleaned)
+ return newLikeSearch(tableName, cleaned)
+ }
+ return nil
+ }
+ ftsTable := tableName + "_fts"
+ matchExpr := q
+ if cols, ok := ftsColumnFilters[tableName]; ok {
+ matchExpr = cols + " : (" + q + ")"
+ }
+
+ rankExpr := ftsTable + ".rank"
+ if weights, ok := ftsBM25Weights[tableName]; ok {
+ rankExpr = "bm25(" + ftsTable + ", " + weights + ")"
+ }
+
+ s := &ftsSearch{
+ tableName: tableName,
+ ftsTable: ftsTable,
+ matchExpr: matchExpr,
+ rankExpr: rankExpr,
+ }
+ log.Trace("Search using FTS5 backend", "table", tableName, "query", q, "filter", s)
+ return s
+}
diff --git a/persistence/sql_search_fts_test.go b/persistence/sql_search_fts_test.go
new file mode 100644
index 000000000..337d54201
--- /dev/null
+++ b/persistence/sql_search_fts_test.go
@@ -0,0 +1,435 @@
+package persistence
+
+import (
+ "context"
+
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = DescribeTable("buildFTS5Query",
+ func(input, expected string) {
+ Expect(buildFTS5Query(input)).To(Equal(expected))
+ },
+ Entry("returns empty string for empty input", "", ""),
+ Entry("returns empty string for whitespace-only input", " ", ""),
+ Entry("appends * to a single word for prefix matching", "beatles", "beatles*"),
+ Entry("appends * to each word for prefix matching", "abbey road", "abbey* road*"),
+ Entry("preserves quoted phrases without appending *", `"the beatles"`, `"the beatles"`),
+ Entry("does not double-append * to existing prefix wildcard", "beat*", "beat*"),
+ Entry("strips FTS5 operators and appends * to lowercased words", "AND OR NOT NEAR", "and* or* not* near*"),
+ Entry("strips special FTS5 syntax characters and appends *", "test^col:val", "test* col* val*"),
+ Entry("handles mixed phrases and words", `"the beatles" abbey`, `"the beatles" abbey*`),
+ Entry("handles prefix with multiple words", "beat* abbey", "beat* abbey*"),
+ Entry("collapses multiple spaces", "abbey road", "abbey* road*"),
+ Entry("strips leading * from tokens and appends trailing *", "*livia", "livia*"),
+ Entry("strips leading * and preserves existing trailing *", "*livia oliv*", "livia* oliv*"),
+ Entry("strips standalone *", "*", ""),
+ Entry("strips apostrophe from input", "Guns N' Roses", "Guns* N* Roses*"),
+ Entry("converts slashed word to phrase+concat OR", "AC/DC", `("AC DC" OR ACDC*)`),
+ Entry("converts hyphenated word to phrase+concat OR", "a-ha", `("a ha" OR aha*)`),
+ Entry("converts partial hyphenated word to phrase+concat OR", "a-h", `("a h" OR ah*)`),
+ Entry("converts hyphenated name to phrase+concat OR", "Jay-Z", `("Jay Z" OR JayZ*)`),
+ Entry("converts contraction to phrase+concat OR", "it's", `("it s" OR its*)`),
+ Entry("handles punctuated word mixed with plain words", "best of a-ha", `best* of* ("a ha" OR aha*)`),
+ Entry("strips miscellaneous punctuation", "rock & roll, vol. 2", "rock* roll* vol* 2*"),
+ Entry("preserves unicode characters with diacritics", "Björk début", "Björk* début*"),
+ Entry("collapses dotted abbreviation into phrase", "R.E.M.", `"R E M"`),
+ Entry("collapses abbreviation without trailing dot", "R.E.M", `"R E M"`),
+ Entry("collapses abbreviation mixed with words", "best of R.E.M.", `best* of* "R E M"`),
+ Entry("collapses two-letter abbreviation", "U.K.", `"U K"`),
+ Entry("does not collapse single letter surrounded by words", "I am fine", "I* am* fine*"),
+ Entry("does not collapse single standalone letter", "A test", "A* test*"),
+ Entry("preserves quoted phrase with punctuation verbatim", `"ac/dc"`, `"ac/dc"`),
+ Entry("preserves quoted abbreviation verbatim", `"R.E.M."`, `"R.E.M."`),
+ Entry("returns empty string for punctuation-only input", "!!!!!!!", ""),
+ Entry("returns empty string for mixed punctuation", "!@#$%^&", ""),
+ Entry("returns empty string for empty quoted phrase", `""`, ""),
+)
+
+var _ = DescribeTable("ftsQueryDegraded",
+ func(original, ftsQuery string, expected bool) {
+ Expect(ftsQueryDegraded(original, ftsQuery)).To(Equal(expected))
+ },
+ Entry("not degraded for empty original", "", "1*", false),
+ Entry("not degraded for empty ftsQuery", "1+", "", false),
+ Entry("not degraded for purely alphanumeric query", "beatles", "beatles*", false),
+ Entry("not degraded when long tokens remain", "test^val", "test* val*", false),
+ Entry("not degraded for quoted phrase with long tokens", `"the beatles"`, `"the beatles"`, false),
+ Entry("degraded for quoted phrase with only short tokens after tokenizer strips special chars", `"1+"`, `"1+"`, true),
+ Entry("not degraded for quoted phrase with meaningful content", `"C++ programming"`, `"C++ programming"`, false),
+ Entry("degraded when special chars stripped leaving short token", "1+", "1*", true),
+ Entry("degraded when special chars stripped leaving two short tokens", "C# 1", "C* 1*", true),
+ Entry("not degraded when at least one long token remains", "1+ beatles", "1* beatles*", false),
+ Entry("not degraded for OR groups from processPunctuatedWords", "AC/DC", `("AC DC" OR ACDC*)`, false),
+)
+
+var _ = DescribeTable("normalizeForFTS",
+ func(expected string, values ...string) {
+ Expect(normalizeForFTS(values...)).To(Equal(expected))
+ },
+ Entry("strips dots and concatenates", "REM", "R.E.M."),
+ Entry("strips slash", "ACDC", "AC/DC"),
+ Entry("strips hyphen", "Aha", "A-ha"),
+ Entry("skips unchanged words", "", "The Beatles"),
+ Entry("handles mixed input", "REM", "R.E.M.", "Automatic for the People"),
+ Entry("deduplicates", "REM", "R.E.M.", "R.E.M."),
+ Entry("strips apostrophe from word", "N", "Guns N' Roses"),
+ Entry("handles multiple values with punctuation", "REM ACDC", "R.E.M.", "AC/DC"),
+)
+
+var _ = DescribeTable("containsCJK",
+ func(input string, expected bool) {
+ Expect(containsCJK(input)).To(Equal(expected))
+ },
+ Entry("returns false for empty string", "", false),
+ Entry("returns false for ASCII text", "hello world", false),
+ Entry("returns false for Latin with diacritics", "Björk début", false),
+ Entry("detects Chinese characters (Han)", "周杰伦", true),
+ Entry("detects Japanese Hiragana", "こんにちは", true),
+ Entry("detects Japanese Katakana", "カタカナ", true),
+ Entry("detects Korean Hangul", "한국어", true),
+ Entry("detects CJK mixed with Latin", "best of 周杰伦", true),
+ Entry("detects single CJK character", "a曲b", true),
+)
+
+var _ = DescribeTable("qualifyOrderBy",
+ func(tableName, orderBy, expected string) {
+ Expect(qualifyOrderBy(tableName, orderBy)).To(Equal(expected))
+ },
+ Entry("returns empty string for empty input", "artist", "", ""),
+ Entry("qualifies simple column with table name", "artist", "name", "artist.name"),
+ Entry("qualifies column with direction", "artist", "name desc", "artist.name desc"),
+ Entry("preserves already-qualified column", "artist", "artist.name", "artist.name"),
+ Entry("preserves already-qualified column with direction", "artist", "artist.name desc", "artist.name desc"),
+ Entry("returns empty for function call expression", "artist", "sum(json_extract(stats, '$.total.m')) desc", ""),
+ Entry("returns empty for expression with comma", "artist", "a, b", ""),
+ Entry("qualifies media_file column", "media_file", "title", "media_file.title"),
+)
+
+var _ = Describe("ftsColumnDefs helpers", func() {
+ Describe("ftsColumnFilters", func() {
+ It("returns column filter for media_file", func() {
+ Expect(ftsColumnFilters).To(HaveKeyWithValue("media_file",
+ "{title album artist album_artist sort_title sort_album_name sort_artist_name sort_album_artist_name disc_subtitle search_participants search_normalized}",
+ ))
+ })
+
+ It("returns column filter for album", func() {
+ Expect(ftsColumnFilters).To(HaveKeyWithValue("album",
+ "{name sort_album_name album_artist search_participants discs catalog_num album_version search_normalized}",
+ ))
+ })
+
+ It("returns column filter for artist", func() {
+ Expect(ftsColumnFilters).To(HaveKeyWithValue("artist",
+ "{name sort_artist_name search_normalized}",
+ ))
+ })
+
+ It("has no entry for unknown table", func() {
+ Expect(ftsColumnFilters).ToNot(HaveKey("unknown"))
+ })
+ })
+
+ Describe("ftsBM25Weights", func() {
+ It("returns weight CSV for media_file", func() {
+ Expect(ftsBM25Weights).To(HaveKeyWithValue("media_file",
+ "10.0, 5.0, 3.0, 3.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0",
+ ))
+ })
+
+ It("returns weight CSV for album", func() {
+ Expect(ftsBM25Weights).To(HaveKeyWithValue("album",
+ "10.0, 1.0, 3.0, 2.0, 1.0, 1.0, 1.0, 1.0",
+ ))
+ })
+
+ It("returns weight CSV for artist", func() {
+ Expect(ftsBM25Weights).To(HaveKeyWithValue("artist",
+ "10.0, 1.0, 1.0",
+ ))
+ })
+
+ It("has no entry for unknown table", func() {
+ Expect(ftsBM25Weights).ToNot(HaveKey("unknown"))
+ })
+ })
+
+ It("has definitions for all known tables", func() {
+ for _, table := range []string{"media_file", "album", "artist"} {
+ Expect(ftsColumnDefs).To(HaveKey(table))
+ Expect(ftsColumnDefs[table]).ToNot(BeEmpty())
+ }
+ })
+
+ It("has matching column count between filter and weights", func() {
+ for table, cols := range ftsColumnDefs {
+ // Column filter only includes Weight > 0 columns
+ filterCount := 0
+ for _, c := range cols {
+ if c.Weight > 0 {
+ filterCount++
+ }
+ }
+ // For now, all columns have Weight > 0, so filter count == total count
+ Expect(filterCount).To(Equal(len(cols)), "table %s: all columns should have positive weights", table)
+ }
+ })
+})
+
+var _ = Describe("newFTSSearch", func() {
+ It("returns nil for empty query", func() {
+ Expect(newFTSSearch("media_file", "")).To(BeNil())
+ })
+
+ It("returns non-nil for single-character query", func() {
+ strategy := newFTSSearch("media_file", "a")
+ Expect(strategy).ToNot(BeNil(), "single-char queries must not be rejected; min-length is enforced in doSearch, not here")
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("MATCH"))
+ })
+
+ It("returns ftsSearch with correct table names and MATCH expression", func() {
+ strategy := newFTSSearch("media_file", "beatles")
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.tableName).To(Equal("media_file"))
+ Expect(fts.ftsTable).To(Equal("media_file_fts"))
+ Expect(fts.matchExpr).To(HavePrefix("{title album artist album_artist"))
+ Expect(fts.matchExpr).To(ContainSubstring("beatles*"))
+ })
+
+ It("ToSql generates rowid IN subquery with MATCH (fallback path)", func() {
+ strategy := newFTSSearch("media_file", "beatles")
+ sql, args, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("media_file.rowid IN"))
+ Expect(sql).To(ContainSubstring("media_file_fts"))
+ Expect(sql).To(ContainSubstring("MATCH"))
+ Expect(args).To(HaveLen(1))
+ })
+
+ It("generates correct FTS table name per entity", func() {
+ for _, table := range []string{"media_file", "album", "artist"} {
+ strategy := newFTSSearch(table, "test")
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.tableName).To(Equal(table))
+ Expect(fts.ftsTable).To(Equal(table + "_fts"))
+ }
+ })
+
+ It("builds bm25() rank expression with column weights", func() {
+ strategy := newFTSSearch("media_file", "beatles")
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.rankExpr).To(HavePrefix("bm25(media_file_fts,"))
+ Expect(fts.rankExpr).To(ContainSubstring("10.0"))
+
+ strategy = newFTSSearch("artist", "beatles")
+ fts, ok = strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.rankExpr).To(HavePrefix("bm25(artist_fts,"))
+ })
+
+ It("falls back to ftsTable.rank for unknown tables", func() {
+ strategy := newFTSSearch("unknown_table", "test")
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.rankExpr).To(Equal("unknown_table_fts.rank"))
+ })
+
+ It("wraps query with column filter for known tables", func() {
+ strategy := newFTSSearch("artist", "Beatles")
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.matchExpr).To(Equal("{name sort_artist_name search_normalized} : (Beatles*)"))
+ })
+
+ It("passes query without column filter for unknown tables", func() {
+ strategy := newFTSSearch("unknown_table", "test")
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.matchExpr).To(Equal("test*"))
+ })
+
+ It("preserves phrase queries inside column filter", func() {
+ strategy := newFTSSearch("media_file", `"the beatles"`)
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.matchExpr).To(ContainSubstring(`"the beatles"`))
+ })
+
+ It("preserves prefix queries inside column filter", func() {
+ strategy := newFTSSearch("media_file", "beat*")
+ fts, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeTrue())
+ Expect(fts.matchExpr).To(ContainSubstring("beat*"))
+ })
+
+ It("falls back to LIKE search for punctuation-only query", func() {
+ strategy := newFTSSearch("media_file", "!!!!!!!")
+ Expect(strategy).ToNot(BeNil())
+ _, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeFalse(), "punctuation-only should fall back to LIKE, not FTS")
+ sql, args, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("LIKE"))
+ Expect(args).To(ContainElement("%!!!!!!!%"))
+ })
+
+ It("falls back to LIKE search for degraded query (special chars stripped leaving short tokens)", func() {
+ strategy := newFTSSearch("album", "1+")
+ Expect(strategy).ToNot(BeNil())
+ _, ok := strategy.(*ftsSearch)
+ Expect(ok).To(BeFalse(), "degraded query should fall back to LIKE, not FTS")
+ sql, args, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("LIKE"))
+ Expect(args).To(ContainElement("%1+%"))
+ })
+
+ It("returns nil for empty string even with LIKE fallback", func() {
+ Expect(newFTSSearch("media_file", "")).To(BeNil())
+ Expect(newFTSSearch("media_file", " ")).To(BeNil())
+ })
+
+ It("returns nil for empty quoted phrase", func() {
+ Expect(newFTSSearch("media_file", `""`)).To(BeNil())
+ })
+})
+
+var _ = Describe("FTS5 Integration Search", func() {
+ var (
+ mr model.MediaFileRepository
+ alr model.AlbumRepository
+ arr model.ArtistRepository
+ )
+
+ BeforeEach(func() {
+ ctx := log.NewContext(context.TODO())
+ ctx = request.WithUser(ctx, adminUser)
+ conn := GetDBXBuilder()
+ mr = NewMediaFileRepository(ctx, conn)
+ alr = NewAlbumRepository(ctx, conn)
+ arr = NewArtistRepository(ctx, conn)
+ })
+
+ Describe("MediaFile search", func() {
+ It("finds media files by title", func() {
+ results, err := mr.Search("Radioactivity", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Title).To(Equal("Radioactivity"))
+ Expect(results[0].ID).To(Equal(songRadioactivity.ID))
+ })
+
+ It("finds media files by artist name", func() {
+ results, err := mr.Search("Beatles", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(3))
+ for _, r := range results {
+ Expect(r.Artist).To(Equal("The Beatles"))
+ }
+ })
+ })
+
+ Describe("Album search", func() {
+ It("finds albums by name", func() {
+ results, err := alr.Search("Sgt Peppers", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Name).To(Equal("Sgt Peppers"))
+ Expect(results[0].ID).To(Equal(albumSgtPeppers.ID))
+ })
+
+ It("finds albums with multi-word search", func() {
+ results, err := alr.Search("Abbey Road", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(2))
+ })
+ })
+
+ Describe("Artist search", func() {
+ It("finds artists by name", func() {
+ results, err := arr.Search("Kraftwerk", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Name).To(Equal("Kraftwerk"))
+ Expect(results[0].ID).To(Equal(artistKraftwerk.ID))
+ })
+ })
+
+ Describe("CJK search", func() {
+ It("finds media files by CJK title", func() {
+ results, err := mr.Search("プラチナ", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Title).To(Equal("プラチナ・ジェット"))
+ Expect(results[0].ID).To(Equal(songCJK.ID))
+ })
+
+ It("finds media files by CJK artist name", func() {
+ results, err := mr.Search("シートベルツ", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Artist).To(Equal("シートベルツ"))
+ })
+
+ It("finds albums by CJK artist name", func() {
+ results, err := alr.Search("シートベルツ", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Name).To(Equal("COWBOY BEBOP"))
+ Expect(results[0].ID).To(Equal(albumCJK.ID))
+ })
+
+ It("finds artists by CJK name", func() {
+ results, err := arr.Search("シートベルツ", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Name).To(Equal("シートベルツ"))
+ Expect(results[0].ID).To(Equal(artistCJK.ID))
+ })
+ })
+
+ Describe("Album version search", func() {
+ It("finds albums by version tag via FTS", func() {
+ results, err := alr.Search("Deluxe", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].ID).To(Equal(albumWithVersion.ID))
+ })
+ })
+
+ Describe("Punctuation-only search", func() {
+ It("finds media files with punctuation-only title", func() {
+ results, err := mr.Search("!!!!!!!", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Title).To(Equal("!!!!!!!"))
+ Expect(results[0].ID).To(Equal(songPunctuation.ID))
+ })
+ })
+
+ Describe("Single-character search (doSearch min-length guard)", func() {
+ It("returns empty results for single-char query via Search", func() {
+ results, err := mr.Search("a", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty(), "doSearch should reject single-char queries")
+ })
+ })
+
+ Describe("Max=0 means no limit (regression: must not produce LIMIT 0)", func() {
+ It("returns results with Max=0", func() {
+ results, err := mr.Search("Beatles", model.QueryOptions{Max: 0})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).ToNot(BeEmpty(), "Max=0 should mean no limit, not LIMIT 0")
+ })
+ })
+})
diff --git a/persistence/sql_search_like.go b/persistence/sql_search_like.go
new file mode 100644
index 000000000..769a911d5
--- /dev/null
+++ b/persistence/sql_search_like.go
@@ -0,0 +1,106 @@
+package persistence
+
+import (
+ "strings"
+
+ . "github.com/Masterminds/squirrel"
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/utils/str"
+)
+
+// likeSearch implements searchStrategy using LIKE-based SQL filters.
+// Used for legacy full_text searches, CJK fallback, and punctuation-only fallback.
+type likeSearch struct {
+ filter Sqlizer
+}
+
+func (s *likeSearch) ToSql() (string, []interface{}, error) {
+ return s.filter.ToSql()
+}
+
+func (s *likeSearch) execute(r sqlRepository, sq SelectBuilder, dest any, cfg searchConfig, options model.QueryOptions) error {
+ sq = sq.Where(s.filter)
+ sq = sq.OrderBy(cfg.OrderBy...)
+ return r.queryAll(sq, dest, options)
+}
+
+// newLegacySearch creates a LIKE search against the full_text column.
+// Returns nil when the query produces no searchable tokens.
+func newLegacySearch(tableName, query string) searchStrategy {
+ filter := legacySearchExpr(tableName, query)
+ if filter == nil {
+ return nil
+ }
+ return &likeSearch{filter: filter}
+}
+
+// newLikeSearch creates a LIKE search against core entity columns (CJK, punctuation fallback).
+// No minimum length is enforced, since single CJK characters are meaningful words.
+// Returns nil when the query produces no searchable tokens.
+func newLikeSearch(tableName, query string) searchStrategy {
+ filter := likeSearchExpr(tableName, query)
+ if filter == nil {
+ return nil
+ }
+ return &likeSearch{filter: filter}
+}
+
+// legacySearchExpr generates LIKE-based search filters against the full_text column.
+// This is the original search implementation, used when Search.Backend="legacy".
+func legacySearchExpr(tableName string, s string) Sqlizer {
+ q := str.SanitizeStrings(s)
+ if q == "" {
+ log.Trace("Search using legacy backend, query is empty", "table", tableName)
+ return nil
+ }
+ var sep string
+ if !conf.Server.Search.FullString {
+ sep = " "
+ }
+ parts := strings.Split(q, " ")
+ filters := And{}
+ for _, part := range parts {
+ filters = append(filters, Like{tableName + ".full_text": "%" + sep + part + "%"})
+ }
+ log.Trace("Search using legacy backend", "query", filters, "table", tableName)
+ return filters
+}
+
+// likeSearchColumns defines the core columns to search with LIKE queries.
+// These are the primary user-visible fields for each entity type.
+// Used as a fallback when FTS5 cannot handle the query (e.g., CJK text, punctuation-only input).
+var likeSearchColumns = map[string][]string{
+ "media_file": {"title", "album", "artist", "album_artist"},
+ "album": {"name", "album_artist"},
+ "artist": {"name"},
+}
+
+// likeSearchExpr generates LIKE-based search filters against core columns.
+// Each word in the query must match at least one column (AND between words),
+// and each word can match any column (OR within a word).
+// Used as a fallback when FTS5 cannot handle the query (e.g., CJK text, punctuation-only input).
+func likeSearchExpr(tableName string, s string) Sqlizer {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ log.Trace("Search using LIKE backend, query is empty", "table", tableName)
+ return nil
+ }
+ columns, ok := likeSearchColumns[tableName]
+ if !ok {
+ log.Trace("Search using LIKE backend, couldn't find columns for this table", "table", tableName)
+ return nil
+ }
+ words := strings.Fields(s)
+ wordFilters := And{}
+ for _, word := range words {
+ colFilters := Or{}
+ for _, col := range columns {
+ colFilters = append(colFilters, Like{tableName + "." + col: "%" + word + "%"})
+ }
+ wordFilters = append(wordFilters, colFilters)
+ }
+ log.Trace("Search using LIKE backend", "query", wordFilters, "table", tableName)
+ return wordFilters
+}
diff --git a/persistence/sql_search_like_test.go b/persistence/sql_search_like_test.go
new file mode 100644
index 000000000..8ee4ef93c
--- /dev/null
+++ b/persistence/sql_search_like_test.go
@@ -0,0 +1,134 @@
+package persistence
+
+import (
+ "context"
+
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("newLegacySearch", func() {
+ It("returns non-nil for single-character query", func() {
+ strategy := newLegacySearch("media_file", "a")
+ Expect(strategy).ToNot(BeNil(), "single-char queries must not be rejected; min-length is enforced in doSearch, not here")
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("LIKE"))
+ })
+})
+
+var _ = Describe("legacySearchExpr", func() {
+ It("returns nil for empty query", func() {
+ Expect(legacySearchExpr("media_file", "")).To(BeNil())
+ })
+
+ It("generates LIKE filter for single word", func() {
+ expr := legacySearchExpr("media_file", "beatles")
+ sql, args, err := expr.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("media_file.full_text LIKE"))
+ Expect(args).To(ContainElement("% beatles%"))
+ })
+
+ It("generates AND of LIKE filters for multiple words", func() {
+ expr := legacySearchExpr("media_file", "abbey road")
+ sql, args, err := expr.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("AND"))
+ Expect(args).To(HaveLen(2))
+ })
+})
+
+var _ = Describe("likeSearchExpr", func() {
+ It("returns nil for empty query", func() {
+ Expect(likeSearchExpr("media_file", "")).To(BeNil())
+ })
+
+ It("returns nil for whitespace-only query", func() {
+ Expect(likeSearchExpr("media_file", " ")).To(BeNil())
+ })
+
+ It("generates LIKE filters against core columns for single CJK word", func() {
+ expr := likeSearchExpr("media_file", "周杰伦")
+ sql, args, err := expr.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ // Should have OR between columns for the single word
+ Expect(sql).To(ContainSubstring("OR"))
+ Expect(sql).To(ContainSubstring("media_file.title LIKE"))
+ Expect(sql).To(ContainSubstring("media_file.album LIKE"))
+ Expect(sql).To(ContainSubstring("media_file.artist LIKE"))
+ Expect(sql).To(ContainSubstring("media_file.album_artist LIKE"))
+ Expect(args).To(HaveLen(4))
+ for _, arg := range args {
+ Expect(arg).To(Equal("%周杰伦%"))
+ }
+ })
+
+ It("generates AND of OR groups for multi-word query", func() {
+ expr := likeSearchExpr("media_file", "周杰伦 greatest")
+ sql, args, err := expr.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ // Two groups AND'd together, each with 4 columns OR'd
+ Expect(sql).To(ContainSubstring("AND"))
+ Expect(args).To(HaveLen(8))
+ })
+
+ It("uses correct columns for album table", func() {
+ expr := likeSearchExpr("album", "周杰伦")
+ sql, args, err := expr.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("album.name LIKE"))
+ Expect(sql).To(ContainSubstring("album.album_artist LIKE"))
+ Expect(args).To(HaveLen(2))
+ })
+
+ It("uses correct columns for artist table", func() {
+ expr := likeSearchExpr("artist", "周杰伦")
+ sql, args, err := expr.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("artist.name LIKE"))
+ Expect(args).To(HaveLen(1))
+ })
+
+ It("returns nil for unknown table", func() {
+ Expect(likeSearchExpr("unknown_table", "周杰伦")).To(BeNil())
+ })
+})
+
+var _ = Describe("Legacy Integration Search", func() {
+ var mr model.MediaFileRepository
+
+ BeforeEach(func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "legacy"
+
+ ctx := log.NewContext(context.TODO())
+ ctx = request.WithUser(ctx, adminUser)
+ conn := GetDBXBuilder()
+ mr = NewMediaFileRepository(ctx, conn)
+ })
+
+ It("returns results using legacy LIKE-based search", func() {
+ results, err := mr.Search("Radioactivity", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(HaveLen(1))
+ Expect(results[0].Title).To(Equal("Radioactivity"))
+ })
+
+ It("returns empty results for single-char query (doSearch min-length guard)", func() {
+ results, err := mr.Search("a", model.QueryOptions{Max: 10})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).To(BeEmpty(), "doSearch should reject single-char queries")
+ })
+
+ It("returns results with Max=0 (regression: must not produce LIMIT 0)", func() {
+ results, err := mr.Search("Beatles", model.QueryOptions{Max: 0})
+ Expect(err).ToNot(HaveOccurred())
+ Expect(results).ToNot(BeEmpty(), "Max=0 should mean no limit, not LIMIT 0")
+ })
+})
diff --git a/persistence/sql_search_test.go b/persistence/sql_search_test.go
index 6bfd88d9f..68ee205b4 100644
--- a/persistence/sql_search_test.go
+++ b/persistence/sql_search_test.go
@@ -1,6 +1,8 @@
package persistence
import (
+ "github.com/navidrome/navidrome/conf"
+ "github.com/navidrome/navidrome/conf/configtest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@@ -11,4 +13,100 @@ var _ = Describe("sqlRepository", func() {
Expect(formatFullText("legiao urbana")).To(Equal(" legiao urbana"))
})
})
+
+ Describe("getSearchStrategy", func() {
+ It("returns FTS strategy by default", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "fts"
+ conf.Server.Search.FullString = false
+
+ strategy := getSearchStrategy("media_file", "test")
+ Expect(strategy).ToNot(BeNil())
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("MATCH"))
+ })
+
+ It("returns legacy LIKE strategy when SearchBackend is legacy", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "legacy"
+ conf.Server.Search.FullString = false
+
+ strategy := getSearchStrategy("media_file", "test")
+ Expect(strategy).ToNot(BeNil())
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("LIKE"))
+ })
+
+ It("falls back to legacy LIKE strategy when SearchFullString is enabled", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "fts"
+ conf.Server.Search.FullString = true
+
+ strategy := getSearchStrategy("media_file", "test")
+ Expect(strategy).ToNot(BeNil())
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("LIKE"))
+ })
+
+ It("routes CJK queries to LIKE strategy instead of FTS", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "fts"
+ conf.Server.Search.FullString = false
+
+ strategy := getSearchStrategy("media_file", "周杰伦")
+ Expect(strategy).ToNot(BeNil())
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ // CJK should use LIKE, not MATCH
+ Expect(sql).To(ContainSubstring("LIKE"))
+ Expect(sql).NotTo(ContainSubstring("MATCH"))
+ })
+
+ It("routes non-CJK queries to FTS strategy", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "fts"
+ conf.Server.Search.FullString = false
+
+ strategy := getSearchStrategy("media_file", "beatles")
+ Expect(strategy).ToNot(BeNil())
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ Expect(sql).To(ContainSubstring("MATCH"))
+ })
+
+ It("returns non-nil for single-character query (no min-length in strategy)", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "fts"
+ conf.Server.Search.FullString = false
+
+ strategy := getSearchStrategy("media_file", "a")
+ Expect(strategy).ToNot(BeNil(), "single-char queries must be accepted by strategies (min-length is enforced in doSearch)")
+ })
+
+ It("returns non-nil for single-character query with legacy backend", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "legacy"
+ conf.Server.Search.FullString = false
+
+ strategy := getSearchStrategy("media_file", "a")
+ Expect(strategy).ToNot(BeNil(), "single-char queries must be accepted by legacy strategy (min-length is enforced in doSearch)")
+ })
+
+ It("uses legacy for CJK when SearchBackend is legacy", func() {
+ DeferCleanup(configtest.SetupConfig())
+ conf.Server.Search.Backend = "legacy"
+ conf.Server.Search.FullString = false
+
+ strategy := getSearchStrategy("media_file", "周杰伦")
+ Expect(strategy).ToNot(BeNil())
+ sql, _, err := strategy.ToSql()
+ Expect(err).ToNot(HaveOccurred())
+ // Legacy should still use full_text column LIKE
+ Expect(sql).To(ContainSubstring("LIKE"))
+ Expect(sql).To(ContainSubstring("full_text"))
+ })
+ })
})
diff --git a/persistence/sql_tags.go b/persistence/sql_tags.go
index 8c3c1e89d..88acebb7f 100644
--- a/persistence/sql_tags.go
+++ b/persistence/sql_tags.go
@@ -60,7 +60,7 @@ func tagIDFilter(name string, idValue any) Sqlizer {
}
// tagLibraryIdFilter filters tags based on library access through the library_tag table
-func tagLibraryIdFilter(_ string, value interface{}) Sqlizer {
+func tagLibraryIdFilter(_ string, value any) Sqlizer {
return Eq{"library_tag.library_id": value}
}
@@ -142,14 +142,14 @@ func (r *baseTagRepository) Count(options ...rest.QueryOptions) (int64, error) {
return r.count(sq, r.parseRestOptions(r.ctx, options...))
}
-func (r *baseTagRepository) Read(id string) (interface{}, error) {
+func (r *baseTagRepository) Read(id string) (any, error) {
query := r.newSelect().Where(Eq{"id": id})
var res model.Tag
err := r.queryOne(query, &res)
return &res, err
}
-func (r *baseTagRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *baseTagRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
query := r.newSelect(r.parseRestOptions(r.ctx, options...))
var res model.TagList
err := r.queryAll(query, &res)
@@ -160,7 +160,7 @@ func (r *baseTagRepository) EntityName() string {
return "tag"
}
-func (r *baseTagRepository) NewInstance() interface{} {
+func (r *baseTagRepository) NewInstance() any {
return model.Tag{}
}
diff --git a/persistence/tag_library_filtering_test.go b/persistence/tag_library_filtering_test.go
index ab0d57d52..ddd897165 100644
--- a/persistence/tag_library_filtering_test.go
+++ b/persistence/tag_library_filtering_test.go
@@ -2,6 +2,7 @@ package persistence
import (
"context"
+ "time"
"github.com/deluan/rest"
"github.com/navidrome/navidrome/conf/configtest"
@@ -45,6 +46,9 @@ var _ = Describe("Tag Library Filtering", func() {
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
+ // Generate unique path suffix to avoid conflicts with other tests
+ uniqueSuffix := time.Now().Format("20060102150405.000")
+
// Clean up database
db := GetDBXBuilder()
_, err := db.NewQuery("DELETE FROM library_tag").Execute()
@@ -57,12 +61,12 @@ var _ = Describe("Tag Library Filtering", func() {
_, err = db.NewQuery("DELETE FROM library WHERE id > 1").Execute()
Expect(err).ToNot(HaveOccurred())
- // Create test libraries
+ // Create test libraries with unique names and paths to avoid conflicts with other tests
_, err = db.NewQuery("INSERT INTO library (id, name, path) VALUES ({:id}, {:name}, {:path})").
- Bind(dbx.Params{"id": libraryID2, "name": "Library 2", "path": "/music/lib2"}).Execute()
+ Bind(dbx.Params{"id": libraryID2, "name": "Library 2-" + uniqueSuffix, "path": "/music/lib2-" + uniqueSuffix}).Execute()
Expect(err).ToNot(HaveOccurred())
_, err = db.NewQuery("INSERT INTO library (id, name, path) VALUES ({:id}, {:name}, {:path})").
- Bind(dbx.Params{"id": libraryID3, "name": "Library 3", "path": "/music/lib3"}).Execute()
+ Bind(dbx.Params{"id": libraryID3, "name": "Library 3-" + uniqueSuffix, "path": "/music/lib3-" + uniqueSuffix}).Execute()
Expect(err).ToNot(HaveOccurred())
// Give admin access to all libraries
@@ -161,7 +165,7 @@ var _ = Describe("Tag Library Filtering", func() {
It("should respect explicit library_id filters within accessible libraries", func() {
tags := readAllTags(®ularUser, rest.QueryOptions{
- Filters: map[string]interface{}{"library_id": libraryID2},
+ Filters: map[string]any{"library_id": libraryID2},
})
// Should see only tags from library 2: pop and rock(lib2)
Expect(tags).To(HaveLen(2))
@@ -170,7 +174,7 @@ var _ = Describe("Tag Library Filtering", func() {
It("should not return tags when filtering by inaccessible library", func() {
tags := readAllTags(®ularUser, rest.QueryOptions{
- Filters: map[string]interface{}{"library_id": libraryID3},
+ Filters: map[string]any{"library_id": libraryID3},
})
// Should return no tags since user can't access library 3
Expect(tags).To(HaveLen(0))
@@ -178,7 +182,7 @@ var _ = Describe("Tag Library Filtering", func() {
It("should filter by library 1 correctly", func() {
tags := readAllTags(®ularUser, rest.QueryOptions{
- Filters: map[string]interface{}{"library_id": libraryID1},
+ Filters: map[string]any{"library_id": libraryID1},
})
// Should see only rock from library 1
Expect(tags).To(HaveLen(1))
@@ -223,7 +227,7 @@ var _ = Describe("Tag Library Filtering", func() {
It("should allow headless processes to apply explicit library_id filters", func() {
tags := readAllTags(nil, rest.QueryOptions{
- Filters: map[string]interface{}{"library_id": libraryID3},
+ Filters: map[string]any{"library_id": libraryID3},
})
// Should see only jazz from library 3
Expect(tags).To(HaveLen(1))
@@ -239,7 +243,7 @@ var _ = Describe("Tag Library Filtering", func() {
It("should respect explicit library_id filters", func() {
tags := readAllTags(&adminUser, rest.QueryOptions{
- Filters: map[string]interface{}{"library_id": libraryID3},
+ Filters: map[string]any{"library_id": libraryID3},
})
// Should see only jazz from library 3
Expect(tags).To(HaveLen(1))
@@ -248,7 +252,7 @@ var _ = Describe("Tag Library Filtering", func() {
It("should filter by library 2 correctly", func() {
tags := readAllTags(&adminUser, rest.QueryOptions{
- Filters: map[string]interface{}{"library_id": libraryID2},
+ Filters: map[string]any{"library_id": libraryID2},
})
// Should see pop and rock from library 2
Expect(tags).To(HaveLen(2))
diff --git a/persistence/tag_repository.go b/persistence/tag_repository.go
index b224450ab..5bb8b3832 100644
--- a/persistence/tag_repository.go
+++ b/persistence/tag_repository.go
@@ -88,10 +88,10 @@ func (r *tagRepository) purgeUnused() error {
`)
c, err := r.executeSQL(del)
if err != nil {
- return fmt.Errorf("error purging unused tags: %w", err)
+ return fmt.Errorf("error purging %s unused tags: %w", r.tableName, err)
}
if c > 0 {
- log.Debug(r.ctx, "Purged unused tags", "totalDeleted", c)
+ log.Debug(r.ctx, "Purged unused tags", "totalDeleted", c, "table", r.tableName)
}
return err
}
diff --git a/persistence/tag_repository_test.go b/persistence/tag_repository_test.go
index c3947a9f7..9a019c30e 100644
--- a/persistence/tag_repository_test.go
+++ b/persistence/tag_repository_test.go
@@ -234,7 +234,7 @@ var _ = Describe("TagRepository", func() {
It("should filter tags by partial value correctly", func() {
options := rest.QueryOptions{
- Filters: map[string]interface{}{"name": "%rock%"}, // Tags containing 'rock'
+ Filters: map[string]any{"name": "%rock%"}, // Tags containing 'rock'
}
result, err := restRepo.ReadAll(options)
Expect(err).ToNot(HaveOccurred())
@@ -249,7 +249,7 @@ var _ = Describe("TagRepository", func() {
It("should filter tags by partial value using LIKE", func() {
options := rest.QueryOptions{
- Filters: map[string]interface{}{"name": "%e%"}, // Tags containing 'e'
+ Filters: map[string]any{"name": "%e%"}, // Tags containing 'e'
}
result, err := restRepo.ReadAll(options)
Expect(err).ToNot(HaveOccurred())
@@ -264,7 +264,7 @@ var _ = Describe("TagRepository", func() {
It("should sort tags by value ascending", func() {
options := rest.QueryOptions{
- Filters: map[string]interface{}{"name": "%r%"}, // Tags containing 'r'
+ Filters: map[string]any{"name": "%r%"}, // Tags containing 'r'
Sort: "name",
Order: "asc",
}
@@ -280,7 +280,7 @@ var _ = Describe("TagRepository", func() {
It("should sort tags by value descending", func() {
options := rest.QueryOptions{
- Filters: map[string]interface{}{"name": "%r%"}, // Tags containing 'r'
+ Filters: map[string]any{"name": "%r%"}, // Tags containing 'r'
Sort: "name",
Order: "desc",
}
diff --git a/persistence/transcoding_repository.go b/persistence/transcoding_repository.go
index 125f57541..870da61c8 100644
--- a/persistence/transcoding_repository.go
+++ b/persistence/transcoding_repository.go
@@ -52,11 +52,11 @@ func (r *transcodingRepository) Count(options ...rest.QueryOptions) (int64, erro
return r.count(Select(), r.parseRestOptions(r.ctx, options...))
}
-func (r *transcodingRepository) Read(id string) (interface{}, error) {
+func (r *transcodingRepository) Read(id string) (any, error) {
return r.Get(id)
}
-func (r *transcodingRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+func (r *transcodingRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
sel := r.newSelect(r.parseRestOptions(r.ctx, options...)).Columns("*")
res := model.Transcodings{}
err := r.queryAll(sel, &res)
@@ -67,11 +67,11 @@ func (r *transcodingRepository) EntityName() string {
return "transcoding"
}
-func (r *transcodingRepository) NewInstance() interface{} {
+func (r *transcodingRepository) NewInstance() any {
return &model.Transcoding{}
}
-func (r *transcodingRepository) Save(entity interface{}) (string, error) {
+func (r *transcodingRepository) Save(entity any) (string, error) {
if !loggedUser(r.ctx).IsAdmin {
return "", rest.ErrPermissionDenied
}
@@ -83,7 +83,7 @@ func (r *transcodingRepository) Save(entity interface{}) (string, error) {
return id, err
}
-func (r *transcodingRepository) Update(id string, entity interface{}, cols ...string) error {
+func (r *transcodingRepository) Update(id string, entity any, cols ...string) error {
if !loggedUser(r.ctx).IsAdmin {
return rest.ErrPermissionDenied
}
diff --git a/persistence/user_repository.go b/persistence/user_repository.go
index a7181b1a7..dc149e8ba 100644
--- a/persistence/user_repository.go
+++ b/persistence/user_repository.go
@@ -57,6 +57,7 @@ func NewUserRepository(ctx context.Context, db dbx.Builder) model.UserRepository
r.db = db
r.tableName = "user"
r.registerModel(&model.User{}, map[string]filterFunc{
+ "id": idFilter(r.tableName),
"password": invalidFilter(ctx),
"name": r.withTableName(startsWithFilter),
})
@@ -339,7 +340,15 @@ func (r *userRepository) Delete(id string) error {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
- return err
+ if err != nil {
+ return err
+ }
+
+ // Clean up orphaned plugin references for the deleted user
+ if err := cleanupPluginUserReferences(r.db, id); err != nil {
+ log.Error(r.ctx, "Failed to cleanup plugin user references", "userID", id, err)
+ }
+ return nil
}
func keyTo32Bytes(input string) []byte {
diff --git a/persistence/user_repository_test.go b/persistence/user_repository_test.go
index 7c0707ecd..8abbf76a9 100644
--- a/persistence/user_repository_test.go
+++ b/persistence/user_repository_test.go
@@ -559,4 +559,15 @@ var _ = Describe("UserRepository", func() {
Expect(user.Libraries[0].ID).To(Equal(1))
})
})
+
+ Describe("filters", func() {
+ It("qualifies id filter with table name", func() {
+ r := repo.(*userRepository)
+ qo := r.parseRestOptions(r.ctx, rest.QueryOptions{Filters: map[string]any{"id": "123"}})
+ sel := r.selectUserWithLibraries(qo)
+ query, _, err := r.toSQL(sel)
+ Expect(err).NotTo(HaveOccurred())
+ Expect(query).To(ContainSubstring("user.id = {:p0}"))
+ })
+ })
})
diff --git a/plugins/.gitignore b/plugins/.gitignore
new file mode 100644
index 000000000..5026985e6
--- /dev/null
+++ b/plugins/.gitignore
@@ -0,0 +1,4 @@
+# Rust build artifacts
+# Cargo.lock is not needed for library crates (this is a cdylib)
+Cargo.lock
+target
\ No newline at end of file
diff --git a/plugins/README.md b/plugins/README.md
index 100230cbf..e37a94d7a 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -1,1760 +1,1077 @@
# Navidrome Plugin System
-## Overview
+Navidrome supports WebAssembly (Wasm) plugins for extending functionality. Plugins run in a secure sandbox and can provide metadata agents, scrobblers, and other integrations through host services like scheduling, caching, WebSockets, and Subsonic API access.
-Navidrome's plugin system is a WebAssembly (WASM) based extension mechanism that enables developers to expand Navidrome's functionality without modifying the core codebase. The plugin system supports several capabilities that can be implemented by plugins:
+The plugin system is built on **[Extism](https://extism.org/)**, a cross-language framework for building WebAssembly plugins. This means you can write plugins in any language that Extism supports (Go, Rust, Python, TypeScript, and more) using their Plugin Development Kits (PDKs).
-1. **MetadataAgent** - For fetching artist and album information, images, etc.
-2. **Scrobbler** - For implementing scrobbling functionality with external services
-3. **SchedulerCallback** - For executing code after a specified delay or on a recurring schedule
-4. **WebSocketCallback** - For interacting with WebSocket endpoints and handling WebSocket events
-5. **LifecycleManagement** - For plugin initialization and configuration (one-time `OnInit` only; not invoked per-request)
+**Essential Extism Resources:**
+- [Extism Documentation](https://extism.org/docs/overview) – Core concepts and architecture
+- [Plugin Development Kits (PDKs)](https://extism.org/docs/concepts/pdk) – Language-specific libraries for writing plugins
+- [Go PDK](https://github.com/extism/go-pdk) – Recommended for Go plugins with TinyGo
+- [Rust PDK](https://github.com/extism/rust-pdk) – For Rust plugins
+- [Python PDK](https://github.com/extism/python-pdk) – Experimental Python support
+- [JavaScript PDK](https://github.com/extism/js-pdk) – For TypeScript/JavaScript plugins
-## Plugin Architecture
+## Table of Contents
-The plugin system is built on the following key components:
+- [Quick Start](#quick-start)
+- [Plugin Basics](#plugin-basics)
+- [Capabilities](#capabilities)
+ - [MetadataAgent](#metadataagent)
+ - [Scrobbler](#scrobbler)
+ - [Lifecycle](#lifecycle)
+- [Host Services](#host-services)
+ - [HTTP Requests](#http-requests)
+ - [Scheduler](#scheduler)
+ - [Cache](#cache)
+ - [KVStore](#kvstore)
+ - [WebSocket](#websocket)
+ - [Library](#library)
+ - [Artwork](#artwork)
+ - [SubsonicAPI](#subsonicapi)
+ - [Config](#config)
+ - [Users](#users)
+- [Configuration](#configuration)
+- [Building Plugins](#building-plugins)
+- [Examples](#examples)
+- [Security](#security)
-### 1. Plugin Manager
+---
-The `Manager` (implemented in `plugins/manager.go`) is the core component that:
+## Quick Start
-- Scans for plugins in the configured plugins directory
-- Loads and compiles plugins
-- Provides access to loaded plugins through capability-specific interfaces
+### 1. Create a minimal plugin
-### 2. Plugin Protocol
-
-Plugins communicate with Navidrome using Protocol Buffers (protobuf) over a WASM runtime. The protocol is defined in `plugins/api/api.proto` which specifies the capabilities and messages that plugins can implement.
-
-### 3. Plugin Adapters
-
-Adapters bridge between the plugin API and Navidrome's internal interfaces:
-
-- `wasmMediaAgent` adapts `MetadataAgent` to the internal `agents.Interface`
-- `wasmScrobblerPlugin` adapts `Scrobbler` to the internal `scrobbler.Scrobbler`
-- `wasmSchedulerCallback` adapts `SchedulerCallback` to the internal `SchedulerCallback`
-
-* **Plugin Instance Pooling**: Instances are managed in an internal pool (default 8 max, 1m TTL).
-* **WASM Compilation & Caching**: Modules are pre-compiled concurrently (max 2) and cached in `[CacheFolder]/plugins`, reducing startup time. The compilation timeout can be configured via `DevPluginCompilationTimeout` in development.
-
-### 4. Host Services
-
-Navidrome provides host services that plugins can call to access functionality like HTTP requests and scheduling.
-These services are defined in `plugins/host/` and implemented in corresponding host files:
-
-- HTTP service (in `plugins/host_http.go`) for making external requests
-- Scheduler service (in `plugins/host_scheduler.go`) for scheduling timed events
-- Config service (in `plugins/host_config.go`) for accessing plugin-specific configuration
-- WebSocket service (in `plugins/host_websocket.go`) for WebSocket communication
-- Cache service (in `plugins/host_cache.go`) for TTL-based plugin caching
-- Artwork service (in `plugins/host_artwork.go`) for generating public artwork URLs
-- SubsonicAPI service (in `plugins/host_subsonicapi.go`) for accessing Navidrome's Subsonic API
-
-### Available Host Services
-
-The following host services are available to plugins:
-
-#### HttpService
-
-```protobuf
-// HTTP methods available to plugins
-service HttpService {
- rpc Get(HttpRequest) returns (HttpResponse);
- rpc Post(HttpRequest) returns (HttpResponse);
- rpc Put(HttpRequest) returns (HttpResponse);
- rpc Delete(HttpRequest) returns (HttpResponse);
- rpc Patch(HttpRequest) returns (HttpResponse);
- rpc Head(HttpRequest) returns (HttpResponse);
- rpc Options(HttpRequest) returns (HttpResponse);
-}
-```
-
-#### ConfigService
-
-```protobuf
-service ConfigService {
- rpc GetPluginConfig(GetPluginConfigRequest) returns (GetPluginConfigResponse);
-}
-```
-
-The ConfigService allows plugins to access plugin-specific configuration. See the [config.proto](host/config/config.proto) file for the full API.
-
-#### ArtworkService
-
-```protobuf
-service ArtworkService {
- rpc GetArtistUrl(GetArtworkUrlRequest) returns (GetArtworkUrlResponse);
- rpc GetAlbumUrl(GetArtworkUrlRequest) returns (GetArtworkUrlResponse);
- rpc GetTrackUrl(GetArtworkUrlRequest) returns (GetArtworkUrlResponse);
-}
-```
-
-Provides methods to get public URLs for artwork images:
-
-- `GetArtistUrl(id string, size int) string`: Returns a public URL for an artist's artwork
-- `GetAlbumUrl(id string, size int) string`: Returns a public URL for an album's artwork
-- `GetTrackUrl(id string, size int) string`: Returns a public URL for a track's artwork
-
-The `size` parameter is optional (use 0 for original size). The URLs returned are based on the server's ShareURL configuration.
-
-Example:
+Create `main.go`:
```go
-url := artwork.GetArtistUrl("123", 300) // Get artist artwork URL with size 300px
-url := artwork.GetAlbumUrl("456", 0) // Get album artwork URL in original size
+package main
+
+import "github.com/extism/go-pdk"
+
+func main() {}
+
+// Implement your capability functions here
```
-#### CacheService
-
-```protobuf
-service CacheService {
- // Set a string value in the cache
- rpc SetString(SetStringRequest) returns (SetResponse);
-
- // Get a string value from the cache
- rpc GetString(GetRequest) returns (GetStringResponse);
-
- // Set an integer value in the cache
- rpc SetInt(SetIntRequest) returns (SetResponse);
-
- // Get an integer value from the cache
- rpc GetInt(GetRequest) returns (GetIntResponse);
-
- // Set a float value in the cache
- rpc SetFloat(SetFloatRequest) returns (SetResponse);
-
- // Get a float value from the cache
- rpc GetFloat(GetRequest) returns (GetFloatResponse);
-
- // Set a byte slice value in the cache
- rpc SetBytes(SetBytesRequest) returns (SetResponse);
-
- // Get a byte slice value from the cache
- rpc GetBytes(GetRequest) returns (GetBytesResponse);
-
- // Remove a value from the cache
- rpc Remove(RemoveRequest) returns (RemoveResponse);
-
- // Check if a key exists in the cache
- rpc Has(HasRequest) returns (HasResponse);
-}
-```
-
-The CacheService provides a TTL-based cache for plugins. Each plugin gets its own isolated cache instance. By default, cached items expire after 24 hours unless a custom TTL is specified.
-
-Key features:
-
-- **Isolated Caches**: Each plugin has its own cache namespace, so different plugins can use the same key names without conflicts
-- **Typed Values**: Store and retrieve values with their proper types (string, int64, float64, or byte slice)
-- **Configurable TTL**: Set custom expiration times per item, or use the default 24-hour TTL
-- **Type Safety**: The system handles type checking, returning "not exists" if there's a type mismatch
-
-Example usage:
-
-```go
-// Store a string value with default TTL (24 hours)
-cacheService.SetString(ctx, &cache.SetStringRequest{
- Key: "user_preference",
- Value: "dark_mode",
-})
-
-// Store an integer with custom TTL (5 minutes)
-cacheService.SetInt(ctx, &cache.SetIntRequest{
- Key: "api_call_count",
- Value: 42,
- TtlSeconds: 300, // 5 minutes
-})
-
-// Retrieve a value
-resp, err := cacheService.GetString(ctx, &cache.GetRequest{
- Key: "user_preference",
-})
-if err != nil {
- // Handle error
-}
-if resp.Exists {
- // Use resp.Value
-} else {
- // Key doesn't exist or has expired
-}
-
-// Check if a key exists
-hasResp, err := cacheService.Has(ctx, &cache.HasRequest{
- Key: "api_call_count",
-})
-if hasResp.Exists {
- // Key exists and hasn't expired
-}
-
-// Remove a value
-cacheService.Remove(ctx, &cache.RemoveRequest{
- Key: "user_preference",
-})
-```
-
-See the [cache.proto](host/cache/cache.proto) file for the full API definition.
-
-#### SchedulerService
-
-The SchedulerService provides a unified interface for scheduling both one-time and recurring tasks, as well as accessing current time information. See the [scheduler.proto](host/scheduler/scheduler.proto) file for the full API.
-
-```protobuf
-service SchedulerService {
- // One-time event scheduling
- rpc ScheduleOneTime(ScheduleOneTimeRequest) returns (ScheduleResponse);
-
- // Recurring event scheduling
- rpc ScheduleRecurring(ScheduleRecurringRequest) returns (ScheduleResponse);
-
- // Cancel any scheduled job
- rpc CancelSchedule(CancelRequest) returns (CancelResponse);
-
- // Get current time in multiple formats
- rpc TimeNow(TimeNowRequest) returns (TimeNowResponse);
-}
-```
-
-**Key Features:**
-
-- **One-time scheduling**: Schedule a callback to be executed once after a specified delay.
-- **Recurring scheduling**: Schedule a callback to be executed repeatedly according to a cron expression.
-- **Current time access**: Get the current time in standardized formats for time-based operations.
-
-**TimeNow Function:**
-
-The `TimeNow` function returns the current time in three formats:
-
-```protobuf
-message TimeNowResponse {
- string rfc3339_nano = 1; // RFC3339 format with nanosecond precision
- int64 unix_milli = 2; // Unix timestamp in milliseconds
- string local_time_zone = 3; // Local timezone name (e.g., "UTC", "America/New_York")
-}
-```
-
-This allows plugins to:
-
-- Get high-precision timestamps for logging and event correlation
-- Perform time-based calculations using Unix timestamps
-- Handle timezone-aware operations by knowing the server's local timezone
-
-Example usage:
-
-```go
-// Get current time information
-timeResp, err := scheduler.TimeNow(ctx, &scheduler.TimeNowRequest{})
-if err != nil {
- return err
-}
-
-// Use the different time formats
-timestamp := timeResp.Rfc3339Nano // "2024-01-15T10:30:45.123456789Z"
-unixMs := timeResp.UnixMilli // 1705312245123
-timezone := timeResp.LocalTimeZone // "UTC"
-```
-
-Plugins using this service must implement the `SchedulerCallback` interface:
-
-```protobuf
-service SchedulerCallback {
- rpc OnSchedulerCallback(SchedulerCallbackRequest) returns (SchedulerCallbackResponse);
-}
-```
-
-The `IsRecurring` field in the request allows plugins to differentiate between one-time and recurring callbacks.
-
-#### WebSocketService
-
-The WebSocketService enables plugins to connect to and interact with WebSocket endpoints. See the [websocket.proto](host/websocket/websocket.proto) file for the full API.
-
-```protobuf
-service WebSocketService {
- // Connect to a WebSocket endpoint
- rpc Connect(ConnectRequest) returns (ConnectResponse);
-
- // Send a text message
- rpc SendText(SendTextRequest) returns (SendTextResponse);
-
- // Send binary data
- rpc SendBinary(SendBinaryRequest) returns (SendBinaryResponse);
-
- // Close a connection
- rpc Close(CloseRequest) returns (CloseResponse);
-}
-```
-
-- **Connect**: Establish a WebSocket connection to a specified URL with optional headers
-- **SendText**: Send text messages over an established connection
-- **SendBinary**: Send binary data over an established connection
-- **Close**: Close a WebSocket connection with optional close code and reason
-
-Plugins using this service must implement the `WebSocketCallback` interface to handle incoming messages and connection events:
-
-```protobuf
-service WebSocketCallback {
- rpc OnTextMessage(OnTextMessageRequest) returns (OnTextMessageResponse);
- rpc OnBinaryMessage(OnBinaryMessageRequest) returns (OnBinaryMessageResponse);
- rpc OnError(OnErrorRequest) returns (OnErrorResponse);
- rpc OnClose(OnCloseRequest) returns (OnCloseResponse);
-}
-```
-
-Example usage:
-
-```go
-// Connect to a WebSocket server
-connectResp, err := websocket.Connect(ctx, &websocket.ConnectRequest{
- Url: "wss://example.com/ws",
- Headers: map[string]string{"Authorization": "Bearer token"},
- ConnectionId: "my-connection-id",
-})
-if err != nil {
- return err
-}
-
-// Send a text message
-_, err = websocket.SendText(ctx, &websocket.SendTextRequest{
- ConnectionId: "my-connection-id",
- Message: "Hello WebSocket",
-})
-
-// Send binary data
-_, err = websocket.SendBinary(ctx, &websocket.SendBinaryRequest{
- ConnectionId: "my-connection-id",
- Data: []byte{0x01, 0x02, 0x03},
-})
-
-// Close the connection when done
-_, err = websocket.Close(ctx, &websocket.CloseRequest{
- ConnectionId: "my-connection-id",
- Code: 1000, // Normal closure
- Reason: "Done",
-})
-```
-
-#### SubsonicAPIService
-
-```protobuf
-service SubsonicAPIService {
- rpc Call(CallRequest) returns (CallResponse);
-}
-```
-
-The SubsonicAPIService provides plugins with access to Navidrome's Subsonic API endpoints. This allows plugins to query and interact with Navidrome's music library data using the same API that external Subsonic clients use.
-
-Key features:
-
-- **Library Access**: Query artists, albums, tracks, playlists, and other music library data
-- **Search Functionality**: Search across the music library using various criteria
-- **Metadata Retrieval**: Get detailed information about music items including ratings, play counts, etc.
-- **Authentication Handled**: The service automatically handles authentication using internal auth context
-- **JSON Responses**: All responses are returned as JSON strings for easy parsing
-
-**Important Security Notes:**
-
-- Plugins must specify a username via the `u` parameter in the URL - this determines which user's library view and permissions apply
-- The service uses internal authentication, so plugins don't need to provide passwords or API keys
-- All Subsonic API security and access controls apply based on the specified user
-
-Example usage:
-
-```go
-// Get ping response to test connectivity
-resp, err := subsonicAPI.Call(ctx, &subsonicapi.CallRequest{
- Url: "/rest/ping?u=admin",
-})
-if err != nil {
- return err
-}
-// resp.Json contains the JSON response
-
-// Search for artists
-resp, err = subsonicAPI.Call(ctx, &subsonicapi.CallRequest{
- Url: "/rest/search3?u=admin&query=Beatles&artistCount=10",
-})
-
-// Get album details
-resp, err = subsonicAPI.Call(ctx, &subsonicapi.CallRequest{
- Url: "/rest/getAlbum?u=admin&id=123",
-})
-
-// Check for errors
-if resp.Error != "" {
- // Handle error - could be missing parameters, invalid user, etc.
- log.Printf("SubsonicAPI error: %s", resp.Error)
-}
-```
-
-**Common URL Patterns:**
-
-- `/rest/ping?u=USERNAME` - Test API connectivity
-- `/rest/search3?u=USERNAME&query=TERM` - Search library
-- `/rest/getArtists?u=USERNAME` - Get all artists
-- `/rest/getAlbum?u=USERNAME&id=ID` - Get album details
-- `/rest/getPlaylists?u=USERNAME` - Get user playlists
-
-**Required Parameters:**
-
-- `u` (username): Required for all requests - determines user context and permissions
-- `f=json`: Recommended to get JSON responses (easier to parse than XML)
-
-The service accepts standard Subsonic API endpoints and parameters. Refer to the [Subsonic API documentation](http://www.subsonic.org/pages/api.jsp) for complete endpoint details, but note that authentication parameters (`p`, `t`, `s`, `c`, `v`) are handled automatically.
-
-See the [subsonicapi.proto](host/subsonicapi/subsonicapi.proto) file for the full API definition.
-
-## Plugin Permission System
-
-Navidrome implements a permission-based security system that controls which host services plugins can access. This system enforces security at load-time by only making authorized services available to plugins in their WebAssembly runtime environment.
-
-### How Permissions Work
-
-The permission system follows a **secure-by-default** approach:
-
-1. **Default Behavior**: Plugins have access to **no host services** unless explicitly declared
-2. **Load-time Enforcement**: Only services listed in a plugin's permissions are loaded into its WASM runtime
-3. **Runtime Security**: Unauthorized services are completely unavailable - attempts to call them result in "function not exported" errors
-
-This design ensures that even if malicious code tries to access unauthorized services, the calls will fail because the functions simply don't exist in the plugin's runtime environment.
-
-### Permission Syntax
-
-Permissions are declared in the plugin's `manifest.json` file using the `permissions` field as an object:
+Create `manifest.json`:
```json
{
- "name": "my-plugin",
- "author": "Plugin Developer",
- "version": "1.0.0",
- "description": "A plugin that fetches data and caches results",
- "website": "https://github.com/plugindeveloper/my-plugin",
- "capabilities": ["MetadataAgent"],
- "permissions": {
- "http": {
- "reason": "To fetch metadata from external APIs",
- "allowedUrls": {
- "https://api.musicbrainz.org": ["GET"],
- "https://coverartarchive.org": ["GET"]
- },
- "allowLocalNetwork": false
- },
- "cache": {
- "reason": "To cache API responses and reduce rate limiting"
- },
- "subsonicapi": {
- "reason": "To query music library for artist and album information",
- "allowedUsernames": ["metadata-user"],
- "allowAdmins": false
- }
- }
+ "name": "My Plugin",
+ "author": "Your Name",
+ "version": "1.0.0"
}
```
-Each permission is represented as a key in the permissions object. The value must be an object containing a `reason` field that explains why the permission is needed.
+### 2. Build with TinyGo and package as .ndp
-**Important**: Some permissions require additional configuration fields:
+```bash
+# Compile to WebAssembly
+tinygo build -o plugin.wasm -target wasip1 -buildmode=c-shared .
-- **`http`**: Requires `allowedUrls` object mapping URL patterns to allowed HTTP methods, and optional `allowLocalNetwork` boolean
-- **`websocket`**: Requires `allowedUrls` array of WebSocket URL patterns, and optional `allowLocalNetwork` boolean
-- **`subsonicapi`**: Requires `reason` field, with optional `allowedUsernames` array and `allowAdmins` boolean for fine-grained access control
-- **`config`**, **`cache`**, **`scheduler`**, **`artwork`**: Only require the `reason` field
-
-**Security Benefits of Required Reasons:**
-
-- **Transparency**: Users can see exactly what each plugin will do with its permissions
-- **Security Auditing**: Makes it easier to identify suspicious or overly broad permission requests
-- **Developer Accountability**: Forces plugin authors to justify each permission they request
-- **Trust Building**: Clear explanations help users make informed decisions about plugin installation
-
-If no permissions are needed, use an empty permissions object: `"permissions": {}`.
-
-### Available Permissions
-
-The following permission keys correspond to host services:
-
-| Permission | Host Service | Description | Required Fields |
-| ------------- | ------------------ | -------------------------------------------------- | ----------------------------------------------------- |
-| `http` | HttpService | Make HTTP requests (GET, POST, PUT, DELETE, etc..) | `reason`, `allowedUrls` |
-| `websocket` | WebSocketService | Connect to and communicate via WebSockets | `reason`, `allowedUrls` |
-| `cache` | CacheService | Store and retrieve cached data with TTL | `reason` |
-| `config` | ConfigService | Access Navidrome configuration values | `reason` |
-| `scheduler` | SchedulerService | Schedule one-time and recurring tasks | `reason` |
-| `artwork` | ArtworkService | Generate public URLs for artwork images | `reason` |
-| `subsonicapi` | SubsonicAPIService | Access Navidrome's Subsonic API endpoints | `reason`, optional: `allowedUsernames`, `allowAdmins` |
-
-#### HTTP Permission Structure
-
-HTTP permissions require explicit URL whitelisting for security:
-
-```json
-{
- "http": {
- "reason": "To fetch artist data from MusicBrainz and album covers from Cover Art Archive",
- "allowedUrls": {
- "https://musicbrainz.org/ws/2/*": ["GET"],
- "https://coverartarchive.org/*": ["GET"],
- "https://api.example.com/submit": ["POST"]
- },
- "allowLocalNetwork": false
- }
-}
+# Package as .ndp (zip archive)
+zip -j my-plugin.ndp manifest.json plugin.wasm
```
-**Fields:**
+### 3. Install
-- `reason` (required): Explanation of why HTTP access is needed
-- `allowedUrls` (required): Object mapping URL patterns to allowed HTTP methods
-- `allowLocalNetwork` (optional, default false): Whether to allow requests to localhost/private IPs
-
-**URL Pattern Matching:**
-
-- Exact URLs: `"https://api.example.com/endpoint": ["GET"]`
-- Wildcard paths: `"https://api.example.com/*": ["GET", "POST"]`
-- Subdomain wildcards: `"https://*.example.com": ["GET"]`
-
-**Important**: Redirect destinations must also be included in `allowedUrls` if you want to follow redirects.
-
-#### WebSocket Permission Structure
-
-WebSocket permissions require explicit URL whitelisting:
-
-```json
-{
- "websocket": {
- "reason": "To connect to Discord gateway for real-time Rich Presence updates",
- "allowedUrls": ["wss://gateway.discord.gg", "wss://*.discord.gg"],
- "allowLocalNetwork": false
- }
-}
-```
-
-**Fields:**
-
-- `reason` (required): Explanation of why WebSocket access is needed
-- `allowedUrls` (required): Array of WebSocket URL patterns (must start with `ws://` or `wss://`)
-- `allowLocalNetwork` (optional, default false): Whether to allow connections to localhost/private IPs
-
-#### SubsonicAPI Permission Structure
-
-SubsonicAPI permissions control which users plugins can access Navidrome's Subsonic API as, providing fine-grained security controls:
-
-```json
-{
- "subsonicapi": {
- "reason": "To query music library data for recommendation engine",
- "allowedUsernames": ["plugin-user", "readonly-user"],
- "allowAdmins": false
- }
-}
-```
-
-**Fields:**
-
-- `reason` (required): Explanation of why SubsonicAPI access is needed
-- `allowedUsernames` (optional): Array of specific usernames the plugin is allowed to use. If empty or omitted, any username can be used
-- `allowAdmins` (optional, default false): Whether the plugin can make API calls using admin user accounts
-
-**Security Model:**
-
-The SubsonicAPI service enforces strict user-based access controls:
-
-- **Username Validation**: The plugin must provide a valid `u` (username) parameter in all API calls
-- **User Context**: All API responses are filtered based on the specified user's permissions and library access
-- **Admin Protection**: By default, plugins cannot use admin accounts for API calls to prevent privilege escalation
-- **Username Restrictions**: When `allowedUsernames` is specified, only those users can be used
-
-**Common Permission Patterns:**
-
-```jsonc
-// Allow any non-admin user (most permissive)
-{
- "subsonicapi": {
- "reason": "To search music library for metadata enhancement",
- "allowAdmins": false
- }
-}
-
-// Allow only specific users (most secure)
-{
- "subsonicapi": {
- "reason": "To access playlists for synchronization with external service",
- "allowedUsernames": ["sync-user"],
- "allowAdmins": false
- }
-}
-
-// Allow admin users (use with caution)
-{
- "subsonicapi": {
- "reason": "To perform administrative tasks like library statistics",
- "allowAdmins": true
- }
-}
-
-// Restrict to specific users but allow admins
-{
- "subsonicapi": {
- "reason": "To backup playlists for authorized users only",
- "allowedUsernames": ["backup-admin", "user1", "user2"],
- "allowAdmins": true
- }
-}
-```
-
-**Important Notes:**
-
-- Username matching is case-insensitive
-- If `allowedUsernames` is empty or omitted, any username can be used (subject to `allowAdmins` setting)
-- Admin restriction (`allowAdmins: false`) is checked after username validation
-- Invalid or non-existent usernames will result in API call errors
-
-### Permission Validation
-
-The plugin system validates permissions during loading:
-
-1. **Schema Validation**: The manifest is validated against the JSON schema
-2. **Permission Recognition**: Unknown permission keys are silently accepted for forward compatibility
-3. **Service Loading**: Only services with corresponding permissions are made available to the plugin
-
-### Security Model
-
-The permission system provides multiple layers of security:
-
-#### 1. Principle of Least Privilege
-
-- Plugins start with zero permissions
-- Only explicitly requested services are available
-- No way to escalate privileges at runtime
-
-#### 2. Load-time Enforcement
-
-- Unauthorized services are not loaded into the WASM runtime
-- No performance overhead for permission checks during execution
-- Impossible to bypass restrictions through code manipulation
-
-#### 3. Service Isolation
-
-- Each plugin gets its own isolated service instances
-- Plugins cannot interfere with each other's service usage
-- Host services are sandboxed within the WASM environment
-
-### Best Practices for Plugin Developers
-
-#### Request Minimal Permissions
-
-```jsonc
-// Good: No permissions if none needed
-{
- "permissions": {}
-}
-
-// Good: Only request what you need with clear reasoning
-{
- "permissions": {
- "http": {
- "reason": "To fetch artist biography from MusicBrainz database",
- "allowedUrls": {
- "https://musicbrainz.org/ws/2/artist/*": ["GET"]
- },
- "allowLocalNetwork": false
- }
- }
-}
-
-// Avoid: Requesting unnecessary permissions
-{
- "permissions": {
- "http": {
- "reason": "To fetch data",
- "allowedUrls": {
- "https://*": ["*"]
- },
- "allowLocalNetwork": true
- },
- "cache": {
- "reason": "For caching"
- },
- "scheduler": {
- "reason": "For scheduling"
- },
- "websocket": {
- "reason": "For real-time updates",
- "allowedUrls": ["wss://*"],
- "allowLocalNetwork": true
- }
- }
-}
-```
-
-#### Write Clear Permission Reasons
-
-Provide specific, descriptive reasons for each permission that explain exactly what the plugin does. Good reasons should:
-
-- Specify **what data** will be accessed/fetched
-- Mention **which external services** will be contacted (if applicable)
-- Explain **why** the permission is necessary for the plugin's functionality
-- Use clear, non-technical language that users can understand
-
-```jsonc
-// Good: Specific and informative
-{
- "http": {
- "reason": "To fetch album reviews from AllMusic API and artist biographies from MusicBrainz",
- "allowedUrls": {
- "https://www.allmusic.com/api/*": ["GET"],
- "https://musicbrainz.org/ws/2/*": ["GET"]
- },
- "allowLocalNetwork": false
- },
- "cache": {
- "reason": "To cache API responses for 24 hours to respect rate limits and improve performance"
- }
-}
-
-// Bad: Vague and unhelpful
-{
- "http": {
- "reason": "To make requests",
- "allowedUrls": {
- "https://*": ["*"]
- },
- "allowLocalNetwork": true
- },
- "cache": {
- "reason": "For caching"
- }
-}
-```
-
-#### Handle Missing Permissions Gracefully
-
-Your plugin should provide clear error messages when permissions are missing:
-
-```go
-func (p *Plugin) GetArtistInfo(ctx context.Context, req *api.ArtistInfoRequest) (*api.ArtistInfoResponse, error) {
- // This will fail with "function not exported" if http permission is missing
- resp, err := p.httpClient.Get(ctx, &http.HttpRequest{Url: apiURL})
- if err != nil {
- // Check if it's a permission error
- if strings.Contains(err.Error(), "not exported") {
- return &api.ArtistInfoResponse{
- Error: "Plugin requires 'http' permission (reason: 'To fetch artist metadata from external APIs') - please add to manifest.json",
- }, nil
- }
- return &api.ArtistInfoResponse{Error: err.Error()}, nil
- }
- // ... process response
-}
-```
-
-### Troubleshooting Permissions
-
-#### Common Error Messages
-
-**"function not exported in module env"**
-
-- Cause: Plugin trying to call a service without proper permission
-- Solution: Add the required permission to your manifest.json
-
-**"manifest validation failed" or "missing required field"**
-
-- Cause: Plugin manifest is missing required fields (e.g., `allowedUrls` for HTTP/WebSocket permissions)
-- Solution: Ensure your manifest includes all required fields for each permission type
-
-**Permission silently ignored**
-
-- Cause: Using a permission key not recognized by current Navidrome version
-- Effect: The unknown permission is silently ignored (no error or warning)
-- Solution: This is actually normal behavior for forward compatibility
-
-#### Debugging Permission Issues
-
-1. **Check the manifest**: Ensure required permissions are spelled correctly and present
-2. **Verify required fields**: Check that HTTP and WebSocket permissions include `allowedUrls` and other required fields
-3. **Review logs**: Check for plugin loading errors, manifest validation errors, and WASM runtime errors
-4. **Test incrementally**: Add permissions one at a time to identify which services your plugin needs
-5. **Verify service names**: Ensure permission keys match exactly: `http`, `cache`, `config`, `scheduler`, `websocket`, `artwork`, `subsonicapi`
-6. **Validate manifest**: Use a JSON schema validator to check your manifest against the schema
-
-### Future Considerations
-
-The permission system is designed for extensibility:
-
-- **Unknown permissions** are allowed in manifests for forward compatibility
-- **New services** can be added with corresponding permission keys
-- **Permission scoping** could be added in the future (e.g., read-only vs. read-write access)
-
-This ensures that plugins developed today will continue to work as the system evolves, while maintaining strong security boundaries.
-
-## Plugin System Implementation
-
-Navidrome's plugin system is built using the following key libraries:
-
-### 1. WebAssembly Runtime (Wazero)
-
-The plugin system uses [Wazero](https://github.com/tetratelabs/wazero), a WebAssembly runtime written in pure Go. Wazero was chosen for several reasons:
-
-- **No CGO dependency**: Unlike other WebAssembly runtimes, Wazero is implemented in pure Go, which simplifies cross-compilation and deployment.
-- **Performance**: It provides efficient compilation and caching of WebAssembly modules.
-- **Security**: Wazero enforces strict sandboxing, which is important for running third-party plugin code safely.
-
-The plugin manager uses Wazero to:
-
-- Compile and cache WebAssembly modules
-- Create isolated runtime environments for each plugin
-- Instantiate plugin modules when they're called
-- Provide host functions that plugins can call
-
-### 2. Go-plugin Framework
-
-Navidrome builds on [go-plugin](https://github.com/knqyf263/go-plugin), a Go plugin system over WebAssembly that provides:
-
-- **Code generation**: Custom Protocol Buffer compiler plugin (`protoc-gen-go-plugin`) that generates Go code for both the host and WebAssembly plugins
-- **Host function system**: Framework for exposing host functionality to plugins safely
-- **Interface versioning**: Built-in mechanism for handling API compatibility between the host and plugins
-- **Type conversion**: Utilities for marshaling and unmarshaling data between Go and WebAssembly
-
-This framework significantly simplifies plugin development by handling the low-level details of WebAssembly communication, allowing plugin developers to focus on implementing capabilities interfaces.
-
-### 3. Protocol Buffers (Protobuf)
-
-[Protocol Buffers](https://developers.google.com/protocol-buffers) serve as the interface definition language for the plugin system. Navidrome uses:
-
-- **protoc-gen-go-plugin**: A custom protobuf compiler plugin that generates Go code for both the Navidrome host and WebAssembly plugins
-- Protobuf messages for structured data exchange between the host and plugins
-
-The protobuf definitions are located in:
-
-- `plugins/api/api.proto`: Core plugin capability interfaces
-- `plugins/host/http/http.proto`: HTTP service interface
-- `plugins/host/scheduler/scheduler.proto`: Scheduler service interface
-- `plugins/host/config/config.proto`: Config service interface
-- `plugins/host/websocket/websocket.proto`: WebSocket service interface
-- `plugins/host/cache/cache.proto`: Cache service interface
-- `plugins/host/artwork/artwork.proto`: Artwork service interface
-- `plugins/host/subsonicapi/subsonicapi.proto`: SubsonicAPI service interface
-
-### 4. Integration Architecture
-
-The plugin system integrates these libraries through several key components:
-
-- **Plugin Manager**: Manages the lifecycle of plugins, from discovery to loading
-- **Compilation Cache**: Improves performance by caching compiled WebAssembly modules
-- **Host Function Bridge**: Exposes Navidrome functionality to plugins through WebAssembly imports
-- **Capability Adapters**: Convert between the plugin API and Navidrome's internal interfaces
-
-Each plugin method call:
-
-1. Creates a new isolated plugin instance using Wazero
-2. Executes the method in the sandboxed environment
-3. Converts data between Go and WebAssembly formats using the protobuf-generated code
-4. Cleans up the instance after the call completes
-
-This stateless design ensures that plugins remain isolated and can't interfere with Navidrome's core functionality or each other.
-
-## Configuration
-
-Plugins are configured in Navidrome's main configuration via the `Plugins` section:
+Copy `my-plugin.ndp` to your Navidrome plugins folder and enable plugins in your config:
```toml
[Plugins]
-# Enable or disable plugin support
Enabled = true
-
-# Directory where plugins are stored (defaults to [DataFolder]/plugins)
Folder = "/path/to/plugins"
```
-By default, the plugins folder is created under `[DataFolder]/plugins` with restrictive permissions (`0700`) to limit access to the Navidrome user.
+---
-### Plugin-specific Configuration
+## Plugin Basics
-You can also provide plugin-specific configuration using the `PluginConfig` section. Each plugin can have its own configuration map using the **folder name** as the key:
+### What is a Plugin?
-```toml
-[PluginConfig.my-plugin-folder]
-api_key = "your-api-key"
-user_id = "your-user-id"
-enable_feature = "true"
+A Navidrome plugin is an `.ndp` package file (zip archive) containing:
-[PluginConfig.another-plugin-folder]
-server_url = "https://example.com/api"
-timeout = "30"
-```
+1. **`manifest.json`** – Plugin metadata (name, author, version, permissions)
+2. **`plugin.wasm`** – Compiled WebAssembly module with capability functions
-These configuration values are passed to plugins during initialization through the `OnInit` method in the `LifecycleManagement` capability.
-Plugins that implement the `LifecycleManagement` capability will receive their configuration as a map of string keys and values.
-
-## Plugin Directory Structure
-
-Each plugin must be located in its own directory under the plugins folder:
+### Plugin Package Structure
```
-plugins/
-├── my-plugin/
-│ ├── plugin.wasm # Compiled WebAssembly module
-│ └── manifest.json # Plugin manifest defining metadata and capabilities
-├── another-plugin/
-│ ├── plugin.wasm
-│ └── manifest.json
+my-plugin.ndp (zip archive)
+├── manifest.json # Required: Plugin metadata
+└── plugin.wasm # Required: Compiled WebAssembly module
```
-**Note**: Plugin identification has changed! Navidrome now uses the **folder name** as the unique identifier for plugins, not the `name` field in `manifest.json`. This means:
+### Plugin Naming
-- **Multiple plugins can have the same `name` in their manifest**, as long as they are in different folders
-- **Plugin loading and commands use the folder name**, not the manifest name
-- **Folder names must be unique** across all plugins in your plugins directory
+Plugins are identified by their **filename** (without `.ndp` extension), not the manifest `name` field:
-This change allows you to have multiple versions or variants of the same plugin (e.g., `lastfm-official`, `lastfm-custom`, `lastfm-dev`) that all have the same manifest name but coexist peacefully.
+- `my-plugin.ndp` → plugin ID is `my-plugin`
+- The manifest `name` is the display name shown in the UI
-### Example: Multiple Plugin Variants
+This allows users to have multiple instances of the same plugin with different configs by renaming the files.
-```
-plugins/
-├── lastfm-official/
-│ ├── plugin.wasm
-│ └── manifest.json # {"name": "LastFM Agent", ...}
-├── lastfm-custom/
-│ ├── plugin.wasm
-│ └── manifest.json # {"name": "LastFM Agent", ...}
-└── lastfm-dev/
- ├── plugin.wasm
- └── manifest.json # {"name": "LastFM Agent", ...}
-```
+### The Manifest
-All three plugins can have the same `"name": "LastFM Agent"` in their manifest, but they are identified and loaded by their folder names:
-
-```bash
-# Load specific variants
-navidrome plugin refresh lastfm-official
-navidrome plugin refresh lastfm-custom
-navidrome plugin refresh lastfm-dev
-
-# Configure each variant separately
-[PluginConfig.lastfm-official]
-api_key = "production-key"
-
-[PluginConfig.lastfm-dev]
-api_key = "development-key"
-```
-
-### Using Symlinks for Plugin Variants
-
-Symlinks provide a powerful way to create multiple configurations for the same plugin without duplicating files. When you create a symlink to a plugin directory, Navidrome treats the symlink as a separate plugin with its own configuration.
-
-**Example: Discord Rich Presence with Multiple Configurations**
-
-```bash
-# Create symlinks for different environments
-cd /path/to/navidrome/plugins
-ln -s /path/to/discord-rich-presence-plugin drp-prod
-ln -s /path/to/discord-rich-presence-plugin drp-dev
-ln -s /path/to/discord-rich-presence-plugin drp-test
-```
-
-Directory structure:
-
-```
-plugins/
-├── drp-prod -> /path/to/discord-rich-presence-plugin/
-├── drp-dev -> /path/to/discord-rich-presence-plugin/
-├── drp-test -> /path/to/discord-rich-presence-plugin/
-```
-
-Each symlink can have its own configuration:
-
-```toml
-[PluginConfig.drp-prod]
-clientid = "production-client-id"
-users = "admin:prod-token"
-
-[PluginConfig.drp-dev]
-clientid = "development-client-id"
-users = "admin:dev-token,testuser:test-token"
-
-[PluginConfig.drp-test]
-clientid = "test-client-id"
-users = "testuser:test-token"
-```
-
-**Key Benefits:**
-
-- **Single Source**: One plugin implementation serves multiple use cases
-- **Independent Configuration**: Each symlink has its own configuration namespace
-- **Development Workflow**: Easy to test different configurations without code changes
-- **Resource Sharing**: All symlinks share the same compiled WASM binary
-
-**Important Notes:**
-
-- The **symlink name** (not the target folder name) is used as the plugin ID
-- Configuration keys use the symlink name: `PluginConfig.`
-- Each symlink appears as a separate plugin in `navidrome plugin list`
-- CLI commands use the symlink name: `navidrome plugin refresh drp-dev`
-
-## Plugin Package Format (.ndp)
-
-Navidrome Plugin Packages (.ndp) are ZIP archives that bundle all files needed for a plugin. They can be installed using the `navidrome plugin install` command.
-
-### Package Structure
-
-A valid .ndp file must contain:
-
-```
-plugin-name.ndp (ZIP file)
-├── plugin.wasm # Required: The compiled WebAssembly module
-├── manifest.json # Required: Plugin manifest with metadata
-├── README.md # Optional: Documentation
-└── LICENSE # Optional: License information
-```
-
-### Creating a Plugin Package
-
-To create a plugin package:
-
-1. Compile your plugin to WebAssembly (plugin.wasm)
-2. Create a manifest.json file with required fields
-3. Include any documentation files you want to bundle
-4. Create a ZIP archive of all files
-5. Rename the ZIP file to have a .ndp extension
-
-### Installing a Plugin Package
-
-Use the Navidrome CLI to install plugins:
-
-```bash
-navidrome plugin install /path/to/plugin-name.ndp
-```
-
-This will extract the plugin to a directory in your configured plugins folder.
-
-## Plugin Management
-
-Navidrome provides a command-line interface for managing plugins. To use these commands, the plugin system must be enabled in your configuration.
-
-### Available Commands
-
-```bash
-# List all installed plugins
-navidrome plugin list
-
-# Show detailed information about a plugin package or installed plugin
-navidrome plugin info plugin-name-or-package.ndp
-
-# Install a plugin from a .ndp file
-navidrome plugin install /path/to/plugin.ndp
-
-# Remove an installed plugin (use folder name)
-navidrome plugin remove plugin-folder-name
-
-# Update an existing plugin
-navidrome plugin update /path/to/updated-plugin.ndp
-
-# Reload a plugin without restarting Navidrome (use folder name)
-navidrome plugin refresh plugin-folder-name
-
-# Create a symlink to a plugin development folder
-navidrome plugin dev /path/to/dev/folder
-```
-
-### Plugin Development
-
-The `dev` and `refresh` commands are particularly useful for plugin development:
-
-#### Development Workflow
-
-1. Create a plugin development folder with required files (`manifest.json` and `plugin.wasm`)
-2. Run `navidrome plugin dev /path/to/your/plugin` to create a symlink in the plugins directory
-3. Make changes to your plugin code
-4. Recompile the WebAssembly module
-5. Run `navidrome plugin refresh your-plugin-folder-name` to reload the plugin without restarting Navidrome
-
-The `dev` command creates a symlink from your development folder to the plugins directory, allowing you to edit the plugin files directly in your development environment without copying them to the plugins directory after each change.
-
-The refresh process:
-
-- Reloads the plugin manifest
-- Recompiles the WebAssembly module
-- Updates the plugin registration
-- Makes the updated plugin immediately available to Navidrome
-
-### Plugin Security
-
-Navidrome provides multiple layers of security for plugin execution:
-
-1. **WebAssembly Sandbox**: Plugins run in isolated WebAssembly environments with no direct system access
-2. **Permission System**: Plugins can only access host services they explicitly request in their manifest (see [Plugin Permission System](#plugin-permission-system))
-3. **File System Security**: The plugins folder is configured with restricted permissions (0700) accessible only by the user running Navidrome
-4. **Resource Isolation**: Each plugin instance is isolated and cannot interfere with other plugins or core Navidrome functionality
-
-The permission system ensures that plugins follow the principle of least privilege - they start with no access to host services and must explicitly declare what they need. This prevents malicious or poorly written plugins from accessing unauthorized functionality.
-
-Always ensure you trust the source of any plugins you install, and review their requested permissions before installation.
-
-## Plugin Manifest
-
-**Capability Names Are Case-Sensitive**: Entries in the `capabilities` array must exactly match one of the supported capabilities: `MetadataAgent`, `Scrobbler`, `SchedulerCallback`, `WebSocketCallback`, or `LifecycleManagement`.
-**Manifest Validation**: The `manifest.json` is validated against the embedded JSON schema (`plugins/schema/manifest.schema.json`). Invalid manifests will be rejected during plugin discovery.
-
-Every plugin must provide a `manifest.json` file that declares metadata, capabilities, and permissions:
+Every plugin must include a `manifest.json` file. Example:
```json
{
- "name": "my-awesome-plugin",
- "author": "Your Name",
+ "name": "My Plugin",
+ "author": "Author Name",
"version": "1.0.0",
- "description": "A plugin that does awesome things",
- "website": "https://github.com/yourname/my-awesome-plugin",
- "capabilities": [
- "MetadataAgent",
- "Scrobbler",
- "SchedulerCallback",
- "WebSocketCallback",
- "LifecycleManagement"
- ],
+ "description": "What this plugin does",
+ "website": "https://example.com",
"permissions": {
"http": {
- "reason": "To fetch metadata from external music APIs"
- },
- "cache": {
- "reason": "To cache API responses and reduce rate limiting"
- },
- "config": {
- "reason": "To read API keys and service configuration"
- },
- "scheduler": {
- "reason": "To schedule periodic data refresh tasks"
+ "reason": "Fetch metadata from external API",
+ "requiredHosts": ["api.example.com", "*.musicbrainz.org"]
}
}
}
```
-Required fields:
+**Required fields:** `name`, `author`, `version`
-- `name`: Display name of the plugin (used for documentation/display purposes; folder name is used for identification)
-- `author`: The creator or organization behind the plugin
-- `version`: Version identifier (recommended to follow semantic versioning)
-- `description`: A brief description of what the plugin does
-- `website`: Website URL for the plugin documentation, source code, or homepage (must be a valid URI)
-- `capabilities`: Array of capability types the plugin implements
-- `permissions`: Object mapping host service names to their configurations (use empty object `{}` for no permissions)
+#### Experimental Features
-Currently supported capabilities:
+Plugins can opt-in to experimental WebAssembly features that may change or be removed in future versions. Currently supported:
-- `MetadataAgent` - For implementing media metadata providers
-- `Scrobbler` - For implementing scrobbling plugins
-- `SchedulerCallback` - For implementing timed callbacks
-- `WebSocketCallback` - For interacting with WebSocket endpoints and handling WebSocket events
-- `LifecycleManagement` - For handling plugin initialization and configuration
+- **`threads`** – Enables WebAssembly threads support (for plugins compiled with multi-threading)
-## Plugin Loading Process
+```json
+{
+ "name": "Threaded Plugin",
+ "author": "Author Name",
+ "version": "1.0.0",
+ "experimental": {
+ "threads": {
+ "reason": "Required for concurrent audio processing"
+ }
+ }
+}
+```
-1. The Plugin Manager scans the plugins directory and all subdirectories
-2. For each subdirectory containing a `plugin.wasm` file and valid `manifest.json`, the manager:
- - Validates the manifest and checks for supported capabilities
- - Pre-compiles the WASM module in the background
- - Registers the plugin using the **folder name** as the unique identifier in the plugin registry
-3. Plugins can be loaded on-demand by folder name or all at once, depending on the manager's method calls
+> **Note:** Experimental features may have compatibility or performance implications. Use only when necessary.
-## Writing a Plugin
+---
-### Requirements
+## Capabilities
-1. Your plugin must be compiled to WebAssembly (WASM)
-2. Your plugin must implement at least one of the capability interfaces defined in `api.proto`
-3. Your plugin must be placed in its own directory with a proper `manifest.json`
+Capabilities define what your plugin can do. They're automatically detected based on which functions you export.
-### Plugin Registration Functions
+### MetadataAgent
-The plugin API provides several registration functions that plugins can call during initialization to register capabilities and obtain host services. These functions should typically be called in your plugin's `init()` function.
+Provides artist and album metadata. Export one or more of these functions:
-#### Standard Registration Functions
+| Function | Input | Output | Description |
+|---------------------------|----------------------------|----------------------------------|----------------------|
+| `nd_get_artist_mbid` | `{id, name}` | `{mbid}` | Get MusicBrainz ID |
+| `nd_get_artist_url` | `{id, name, mbid?}` | `{url}` | Get artist URL |
+| `nd_get_artist_biography` | `{id, name, mbid?}` | `{biography}` | Get artist biography |
+| `nd_get_similar_artists` | `{id, name, mbid?, limit}` | `{artists: [{name, mbid?}]}` | Get similar artists |
+| `nd_get_artist_images` | `{id, name, mbid?}` | `{images: [{url, size}]}` | Get artist images |
+| `nd_get_artist_top_songs` | `{id, name, mbid?, count}` | `{songs: [{name, mbid?}]}` | Get top songs |
+| `nd_get_album_info` | `{name, artist, mbid?}` | `{name, mbid, description, url}` | Get album info |
+| `nd_get_album_images` | `{name, artist, mbid?}` | `{images: [{url, size}]}` | Get album images |
+
+**Example:**
```go
-func RegisterMetadataAgent(agent MetadataAgent)
-func RegisterScrobbler(scrobbler Scrobbler)
-func RegisterSchedulerCallback(callback SchedulerCallback)
-func RegisterLifecycleManagement(lifecycle LifecycleManagement)
-func RegisterWebSocketCallback(callback WebSocketCallback)
+type ArtistInput struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ MBID string `json:"mbid,omitempty"`
+}
+
+type BiographyOutput struct {
+ Biography string `json:"biography"`
+}
+
+//go:wasmexport nd_get_artist_biography
+func ndGetArtistBiography() int32 {
+ var input ArtistInput
+ if err := pdk.InputJSON(&input); err != nil {
+ pdk.SetError(err)
+ return 1
+ }
+
+ // Fetch biography from your data source...
+ output := BiographyOutput{Biography: "Artist biography..."}
+ pdk.OutputJSON(output)
+ return 0
+}
```
-These functions register plugins for the standard capability interfaces:
+To use the plugin as a metadata agent, add it to your config:
-- **RegisterMetadataAgent**: Register a plugin that provides artist/album metadata and images
-- **RegisterScrobbler**: Register a plugin that handles scrobbling to external services
-- **RegisterSchedulerCallback**: Register a plugin that handles scheduled callbacks (single callback per plugin)
-- **RegisterLifecycleManagement**: Register a plugin that handles initialization and configuration
-- **RegisterWebSocketCallback**: Register a plugin that handles WebSocket events
+```toml
+Agents = "lastfm,spotify,my-plugin"
+```
-**Basic Usage Example:**
+### Scrobbler
+
+Integrates with external scrobbling services. Export one or more of these functions:
+
+| Function | Input | Output | Description |
+|------------------------------|-----------------------|----------------|-----------------------------|
+| `nd_scrobbler_is_authorized` | `{username}` | `bool` | Check if user is authorized |
+| `nd_scrobbler_now_playing` | See below | (none) | Send now playing |
+| `nd_scrobbler_scrobble` | See below | (none) | Submit a scrobble |
+
+> **Important:** Scrobbler plugins require the `users` permission in their manifest. Scrobble events are only sent for users assigned to the plugin through Navidrome's configuration. The `nd_scrobbler_is_authorized` function is called after the server-side user check passes.
+
+**Manifest permission:**
+
+```json
+{
+ "permissions": {
+ "users": {
+ "reason": "Receive scrobble events for users assigned to this plugin"
+ }
+ }
+}
+```
+
+**NowPlaying/Scrobble Input:**
+
+```json
+{
+ "username": "john",
+ "track": {
+ "id": "track-id",
+ "title": "Song Title",
+ "album": "Album Name",
+ "artist": "Artist Name",
+ "albumArtist": "Album Artist",
+ "duration": 180.5,
+ "trackNumber": 1,
+ "discNumber": 1,
+ "mbzRecordingId": "...",
+ "mbzAlbumId": "...",
+ "mbzArtistId": "..."
+ },
+ "timestamp": 1703270400
+}
+```
+
+**Error Handling:**
+
+On success, return `0`. On failure, use `pdk.SetError()` with one of these error types:
+
+- `scrobbler(not_authorized)` – User needs to re-authorize
+- `scrobbler(retry_later)` – Temporary failure, Navidrome will retry
+- `scrobbler(unrecoverable)` – Permanent failure, scrobble discarded
```go
-type MyPlugin struct {
- // plugin implementation
-}
+import "github.com/navidrome/navidrome/plugins/pdk/go/scrobbler"
-func init() {
- plugin := &MyPlugin{}
-
- // Register capabilities your plugin implements
- api.RegisterScrobbler(plugin)
- api.RegisterLifecycleManagement(plugin)
-}
+// Return error using predefined constants
+return scrobbler.ScrobblerErrorNotAuthorized
+return scrobbler.ScrobblerErrorRetryLater
+return scrobbler.ScrobblerErrorUnrecoverable
```
-#### RegisterNamedSchedulerCallback
+### Lifecycle
-```go
-func RegisterNamedSchedulerCallback(name string, cb SchedulerCallback) scheduler.SchedulerService
-```
+Optional initialization callback. Export this function to run code when your plugin loads:
-This function registers a named scheduler callback and returns a scheduler service instance. Named callbacks allow a single plugin to register multiple scheduler callbacks for different purposes, each with its own identifier.
+| Function | Input | Output | Description |
+|--------------|-------|------------|--------------------------------|
+| `nd_on_init` | `{}` | `{error?}` | Called once after plugin loads |
-**Parameters:**
+Useful for initializing connections, scheduling recurring tasks, etc.
-- `name` (string): A unique identifier for this scheduler callback within the plugin. This name is used to route scheduled events to the correct callback handler.
-- `cb` (SchedulerCallback): An object that implements the `SchedulerCallback` interface
-
-**Returns:**
-
-- `scheduler.SchedulerService`: A scheduler service instance that can be used to schedule one-time or recurring tasks for this specific callback
-
-**Usage Example** (from Discord Rich Presence plugin):
-
-```go
-func init() {
- // Register multiple named scheduler callbacks for different purposes
- plugin.sched = api.RegisterNamedSchedulerCallback("close-activity", plugin)
- plugin.rpc.sched = api.RegisterNamedSchedulerCallback("heartbeat", plugin.rpc)
-}
-
-// The plugin implements SchedulerCallback to handle "close-activity" events
-func (d *DiscordRPPlugin) OnSchedulerCallback(ctx context.Context, req *api.SchedulerCallbackRequest) (*api.SchedulerCallbackResponse, error) {
- log.Printf("Removing presence for user %s", req.ScheduleId)
- // Handle close-activity scheduling events
- return nil, d.rpc.clearActivity(ctx, req.ScheduleId)
-}
-
-// The rpc component implements SchedulerCallback to handle "heartbeat" events
-func (r *discordRPC) OnSchedulerCallback(ctx context.Context, req *api.SchedulerCallbackRequest) (*api.SchedulerCallbackResponse, error) {
- // Handle heartbeat scheduling events
- return nil, r.sendHeartbeat(ctx, req.ScheduleId)
-}
-
-// Use the returned scheduler service to schedule tasks
-func (d *DiscordRPPlugin) NowPlaying(ctx context.Context, request *api.ScrobblerNowPlayingRequest) (*api.ScrobblerNowPlayingResponse, error) {
- // Schedule a one-time callback to clear activity when track ends
- _, err = d.sched.ScheduleOneTime(ctx, &scheduler.ScheduleOneTimeRequest{
- ScheduleId: request.Username,
- DelaySeconds: request.Track.Length - request.Track.Position + 5,
- })
- return nil, err
-}
-
-func (r *discordRPC) connect(ctx context.Context, username string, token string) error {
- // Schedule recurring heartbeats for Discord connection
- _, err := r.sched.ScheduleRecurring(ctx, &scheduler.ScheduleRecurringRequest{
- CronExpression: "@every 41s",
- ScheduleId: username,
- })
- return err
-}
-```
-
-**Key Benefits:**
-
-- **Multiple Schedulers**: A single plugin can have multiple named scheduler callbacks for different purposes (e.g., "heartbeat", "cleanup", "refresh")
-- **Isolated Scheduling**: Each named callback gets its own scheduler service, allowing independent scheduling management
-- **Clear Separation**: Different callback handlers can be implemented on different objects within your plugin
-- **Flexible Routing**: The scheduler automatically routes callbacks to the correct handler based on the registration name
-
-**Important Notes:**
-
-- The `name` parameter must be unique within your plugin, but can be the same across different plugins
-- The returned scheduler service is specifically tied to the named callback you registered
-- Scheduled events will call the `OnSchedulerCallback` method on the object you provided during registration
-- You must implement the `SchedulerCallback` interface on the object you register
-
-#### RegisterSchedulerCallback vs RegisterNamedSchedulerCallback
-
-- **Use `RegisterSchedulerCallback`** when your plugin only needs a single scheduler callback
-- **Use `RegisterNamedSchedulerCallback`** when your plugin needs multiple scheduler callbacks for different purposes (like the Discord plugin's "heartbeat" and "close-activity" callbacks)
-
-The named version allows better organization and separation of concerns when you have complex scheduling requirements.
-
-### Capability Interfaces
-
-#### Metadata Agent
-
-A capability fetches metadata about artists and albums. Implement this interface to add support for fetching data from external sources.
-
-```protobuf
-service MetadataAgent {
- // Artist metadata methods
- rpc GetArtistMBID(ArtistMBIDRequest) returns (ArtistMBIDResponse);
- rpc GetArtistURL(ArtistURLRequest) returns (ArtistURLResponse);
- rpc GetArtistBiography(ArtistBiographyRequest) returns (ArtistBiographyResponse);
- rpc GetSimilarArtists(ArtistSimilarRequest) returns (ArtistSimilarResponse);
- rpc GetArtistImages(ArtistImageRequest) returns (ArtistImageResponse);
- rpc GetArtistTopSongs(ArtistTopSongsRequest) returns (ArtistTopSongsResponse);
-
- // Album metadata methods
- rpc GetAlbumInfo(AlbumInfoRequest) returns (AlbumInfoResponse);
- rpc GetAlbumImages(AlbumImagesRequest) returns (AlbumImagesResponse);
-}
-```
-
-#### Scrobbler
-
-This capability enables scrobbling to external services. Implement this interface to add support for custom scrobblers.
-
-```protobuf
-service Scrobbler {
- rpc IsAuthorized(ScrobblerIsAuthorizedRequest) returns (ScrobblerIsAuthorizedResponse);
- rpc NowPlaying(ScrobblerNowPlayingRequest) returns (ScrobblerNowPlayingResponse);
- rpc Scrobble(ScrobblerScrobbleRequest) returns (ScrobblerScrobbleResponse);
-}
-```
-
-#### Scheduler Callback
-
-This capability allows plugins to receive one-time or recurring scheduled callbacks. Implement this interface to add
-support for scheduled tasks. See the [SchedulerService](#scheduler-service) for more information.
-
-```protobuf
-service SchedulerCallback {
- rpc OnSchedulerCallback(SchedulerCallbackRequest) returns (SchedulerCallbackResponse);
-}
-```
-
-#### WebSocket Callback
-
-This capability allows plugins to interact with WebSocket endpoints and handle WebSocket events. Implement this interface to add support for WebSocket-based communication.
-
-```protobuf
-service WebSocketCallback {
- // Called when a text message is received
- rpc OnTextMessage(OnTextMessageRequest) returns (OnTextMessageResponse);
-
- // Called when a binary message is received
- rpc OnBinaryMessage(OnBinaryMessageRequest) returns (OnBinaryMessageResponse);
-
- // Called when an error occurs
- rpc OnError(OnErrorRequest) returns (OnErrorResponse);
-
- // Called when the connection is closed
- rpc OnClose(OnCloseRequest) returns (OnCloseResponse);
-}
-```
-
-Plugins can use the WebSocket host service to connect to WebSocket endpoints, send messages, and handle responses:
-
-```go
-// Define a connection ID first
-connectionID := "my-connection-id"
-
-// Connect to a WebSocket server
-connectResp, err := websocket.Connect(ctx, &websocket.ConnectRequest{
- Url: "wss://example.com/ws",
- Headers: map[string]string{"Authorization": "Bearer token"},
- ConnectionId: connectionID,
-})
-if err != nil {
- return err
-}
-
-// Send a text message
-_, err = websocket.SendText(ctx, &websocket.SendTextRequest{
- ConnectionId: connectionID,
- Message: "Hello WebSocket",
-})
-
-// Close the connection when done
-_, err = websocket.Close(ctx, &websocket.CloseRequest{
- ConnectionId: connectionID,
- Code: 1000, // Normal closure
- Reason: "Done",
-})
-```
+---
## Host Services
-Navidrome provides several host services that plugins can use to interact with external systems and access functionality. Plugins must declare permissions for each service they want to use in their `manifest.json`.
+Host services let your plugin call back into Navidrome for advanced functionality. Each service requires declaring the permission in your manifest.
-### HTTP Service
+### HTTP Requests
-The HTTP service allows plugins to make HTTP requests to external APIs and services. To use this service, declare the `http` permission in your manifest.
+Make HTTP requests using the Extism PDK's built-in HTTP support. See your [Extism PDK documentation](https://extism.org/docs/concepts/pdk) for more details on making requests.
-#### Basic Usage
+**Manifest permission:**
```json
{
"permissions": {
"http": {
- "reason": "To fetch artist metadata from external music APIs"
+ "reason": "Fetch metadata from external API",
+ "requiredHosts": ["api.example.com", "*.musicbrainz.org"]
}
}
}
```
-#### Granular Permissions
-
-For enhanced security, you can specify granular HTTP permissions that restrict which URLs and HTTP methods your plugin can access:
-
-```json
-{
- "permissions": {
- "http": {
- "reason": "To fetch album reviews from AllMusic and artist data from MusicBrainz",
- "allowedUrls": {
- "https://api.allmusic.com": ["GET", "POST"],
- "https://*.musicbrainz.org": ["GET"],
- "https://coverartarchive.org": ["GET"],
- "*": ["GET"]
- },
- "allowLocalNetwork": false
- }
- }
-}
-```
-
-**Permission Fields:**
-
-- `reason` (required): Clear explanation of why HTTP access is needed
-- `allowedUrls` (required): Map of URL patterns to allowed HTTP methods
-
- - Must contain at least one URL pattern
- - For unrestricted access, use: `{"*": ["*"]}`
- - Keys can be exact URLs, wildcard patterns, or `*` for any URL
- - Values are arrays of HTTP methods: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS`, or `*` for any method
- - **Important**: Redirect destinations must also be included in this list. If a URL redirects to another URL not in `allowedUrls`, the redirect will be blocked.
-
-- `allowLocalNetwork` (optional, default: `false`): Whether to allow requests to localhost/private IPs
-
-**URL Pattern Matching:**
-
-- Exact URLs: `https://api.example.com`
-- Wildcard subdomains: `https://*.example.com` (matches any subdomain)
-- Wildcard paths: `https://example.com/api/*` (matches any path under /api/)
-- Global wildcard: `*` (matches any URL - use with caution)
-
-**Examples:**
-
-```json
-// Allow only GET requests to specific APIs
-{
- "allowedUrls": {
- "https://api.last.fm": ["GET"],
- "https://ws.audioscrobbler.com": ["GET"]
- }
-}
-
-// Allow any method to a trusted domain, GET everywhere else
-{
- "allowedUrls": {
- "https://my-trusted-api.com": ["*"],
- "*": ["GET"]
- }
-}
-
-// Handle redirects by including redirect destinations
-{
- "allowedUrls": {
- "https://short.ly/api123": ["GET"], // Original URL
- "https://api.actual-service.com": ["GET"] // Redirect destination
- }
-}
-
-// Strict permissions for a secure plugin (blocks redirects by not including redirect destinations)
-{
- "allowedUrls": {
- "https://api.musicbrainz.org/ws/2": ["GET"]
- },
- "allowLocalNetwork": false
-}
-```
-
-#### Security Considerations
-
-The HTTP service implements several security features:
-
-1. **Local Network Protection**: By default, requests to localhost and private IP ranges are blocked
-2. **URL Filtering**: Only URLs matching `allowedUrls` patterns are allowed
-3. **Method Restrictions**: HTTP methods are validated against the allowed list for each URL pattern
-4. **Redirect Security**:
- - Redirect destinations must also match `allowedUrls` patterns and methods
- - Maximum of 5 redirects per request to prevent redirect loops
- - To block all redirects, simply don't include any redirect destinations in `allowedUrls`
-
-**Private IP Ranges Blocked (when `allowLocalNetwork: false`):**
-
-- IPv4: `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `127.0.0.0/8`, `169.254.0.0/16`
-- IPv6: `::1`, `fe80::/10`, `fc00::/7`
-- Hostnames: `localhost`
-
-#### Making HTTP Requests
+**Usage:**
```go
-import "github.com/navidrome/navidrome/plugins/host/http"
+req := pdk.NewHTTPRequest(pdk.MethodGet, "https://api.example.com/data")
+req.SetHeader("Authorization", "Bearer " + apiKey)
+resp := req.Send()
-// GET request
-resp, err := httpClient.Get(ctx, &http.HttpRequest{
- Url: "https://api.example.com/data",
- Headers: map[string]string{
- "Authorization": "Bearer " + token,
- "User-Agent": "MyPlugin/1.0",
- },
- TimeoutMs: 5000,
-})
-
-// POST request with body
-resp, err := httpClient.Post(ctx, &http.HttpRequest{
- Url: "https://api.example.com/submit",
- Headers: map[string]string{
- "Content-Type": "application/json",
- },
- Body: []byte(`{"key": "value"}`),
- TimeoutMs: 10000,
-})
-
-// Handle response
-if err != nil {
- return &api.Response{Error: "HTTP request failed: " + err.Error()}, nil
-}
-
-if resp.Error != "" {
- return &api.Response{Error: "HTTP error: " + resp.Error}, nil
-}
-
-if resp.Status != 200 {
- return &api.Response{Error: fmt.Sprintf("HTTP %d: %s", resp.Status, string(resp.Body))}, nil
-}
-
-// Use response data
-data := resp.Body
-headers := resp.Headers
-```
-
-### Other Host Services
-
-#### Config Service
-
-Access plugin-specific configuration:
-
-```json
-{
- "permissions": {
- "config": {
- "reason": "To read API keys and service endpoints from plugin configuration"
- }
- }
+if resp.Status() == 200 {
+ data := resp.Body()
+ // Process response...
}
```
-#### Cache Service
+### Scheduler
-Store and retrieve data to improve performance:
+Schedule one-time or recurring tasks. Your plugin must export `nd_scheduler_callback` to receive events.
-```json
-{
- "permissions": {
- "cache": {
- "reason": "To cache API responses and reduce external service calls"
- }
- }
-}
-```
-
-#### Scheduler Service
-
-Schedule recurring or one-time tasks:
+**Manifest permission:**
```json
{
"permissions": {
"scheduler": {
- "reason": "To schedule periodic metadata refresh and cleanup tasks"
+ "reason": "Schedule periodic metadata refresh"
}
}
}
```
-#### WebSocket Service
+**Host functions:**
-Connect to WebSocket endpoints:
+| Function | Parameters | Description |
+|-------------------------------|------------------------------------------|-----------------------------|
+| `scheduler_scheduleonetime` | `delaySeconds, payload, scheduleId?` | Schedule one-time callback |
+| `scheduler_schedulerecurring` | `cronExpression, payload, scheduleId?` | Schedule recurring callback |
+| `scheduler_cancelschedule` | `scheduleId` | Cancel a scheduled task |
+
+**Callback function:**
+
+```go
+type SchedulerCallbackInput struct {
+ ScheduleID string `json:"scheduleId"`
+ Payload string `json:"payload"`
+ IsRecurring bool `json:"isRecurring"`
+}
+
+//go:wasmexport nd_scheduler_callback
+func ndSchedulerCallback() int32 {
+ var input SchedulerCallbackInput
+ pdk.InputJSON(&input)
+
+ // Handle the scheduled task based on payload
+ pdk.Log(pdk.LogInfo, "Task fired: " + input.ScheduleID)
+ return 0
+}
+```
+
+**Scheduling tasks (using generated SDK):**
+
+Add the generated SDK to your `go.mod`:
+
+```
+require github.com/navidrome/navidrome/plugins/pdk/go v0.0.0
+replace github.com/navidrome/navidrome/plugins/pdk/go => ../../pdk/go
+```
+
+Then import and use:
+
+```go
+import "github.com/navidrome/navidrome/plugins/pdk/go/host"
+
+// Schedule one-time task in 60 seconds
+scheduleID, err := host.SchedulerScheduleOneTime(60, "my-payload", "")
+
+// Schedule recurring task with cron expression (every hour)
+scheduleID, err := host.SchedulerScheduleRecurring("0 * * * *", "hourly-task", "")
+
+// Cancel a task
+err := host.SchedulerCancelSchedule(scheduleID)
+```
+
+### Cache
+
+Store and retrieve data in an in-memory TTL-based cache. Each plugin has its own isolated namespace.
+
+**Manifest permission:**
+
+```json
+{
+ "permissions": {
+ "cache": {
+ "reason": "Cache API responses to reduce external requests"
+ }
+ }
+}
+```
+
+**Host functions:**
+
+| Function | Parameters | Description |
+|-------------------|---------------------------|-----------------------|
+| `cache_setstring` | `key, value, ttl_seconds` | Store a string |
+| `cache_getstring` | `key` | Get a string |
+| `cache_setint` | `key, value, ttl_seconds` | Store an integer |
+| `cache_getint` | `key` | Get an integer |
+| `cache_setfloat` | `key, value, ttl_seconds` | Store a float |
+| `cache_getfloat` | `key` | Get a float |
+| `cache_setbytes` | `key, value, ttl_seconds` | Store bytes |
+| `cache_getbytes` | `key` | Get bytes |
+| `cache_has` | `key` | Check if key exists |
+| `cache_remove` | `key` | Delete a cached value |
+
+**TTL:** Pass `0` for the default (24 hours), or specify seconds.
+
+**Usage (with generated SDK):**
+
+Import the Go SDK (see [Scheduler](#scheduler) for `go.mod` setup):
+
+```go
+import "github.com/navidrome/navidrome/plugins/pdk/go/host"
+
+// Cache a value for 1 hour
+host.CacheSetString("api-response", responseData, 3600)
+
+// Retrieve (check Exists before using Value)
+result, err := host.CacheGetString("api-response")
+if result.Exists {
+ data := result.Value
+}
+```
+
+> **Note:** Cache is in-memory only and cleared on server restart.
+
+### KVStore
+
+Persistent key-value storage that survives server restarts. Each plugin has its own isolated SQLite database.
+
+**Manifest permission:**
+
+```json
+{
+ "permissions": {
+ "kvstore": {
+ "reason": "Store OAuth tokens and plugin state",
+ "maxSize": "1MB"
+ }
+ }
+}
+```
+
+**Permission options:**
+- `maxSize`: Maximum storage size (e.g., `"1MB"`, `"500KB"`). Default: 1MB
+
+**Host functions:**
+
+| Function | Parameters | Description |
+|--------------------------|--------------|-----------------------------------|
+| `kvstore_set` | `key, value` | Store a byte value |
+| `kvstore_get` | `key` | Retrieve a byte value |
+| `kvstore_delete` | `key` | Delete a value |
+| `kvstore_has` | `key` | Check if key exists |
+| `kvstore_list` | `prefix` | List keys matching prefix |
+| `kvstore_getstorageused` | - | Get current storage usage (bytes) |
+
+**Key constraints:**
+- Maximum key length: 256 bytes
+- Keys must be valid UTF-8 strings
+
+**Usage (with generated SDK):**
+
+Import the Go SDK (see [Scheduler](#scheduler) for `go.mod` setup):
+
+```go
+import "github.com/navidrome/navidrome/plugins/pdk/go/host"
+
+// Store a value (as raw bytes)
+token := []byte(`{"access_token": "xyz", "refresh_token": "abc"}`)
+_, err := host.KVStoreSet("oauth:spotify", token)
+
+// Retrieve a value
+result, err := host.KVStoreGet("oauth:spotify")
+if result.Exists {
+ var tokenData map[string]string
+ json.Unmarshal(result.Value, &tokenData)
+}
+
+// List all keys with prefix
+keysResult, err := host.KVStoreList("user:")
+for _, key := range keysResult.Keys {
+ // Process each key
+}
+
+// Check storage usage
+usageResult, err := host.KVStoreGetStorageUsed()
+fmt.Printf("Using %d bytes\n", usageResult.Bytes)
+
+// Delete a value
+host.KVStoreDelete("oauth:spotify")
+```
+
+> **Note:** Unlike Cache, KVStore data persists across server restarts. Storage is located at `${DataFolder}/plugins/${pluginID}/kvstore.db`.
+
+### WebSocket
+
+Establish persistent WebSocket connections to external services.
+
+**Manifest permission:**
```json
{
"permissions": {
"websocket": {
- "reason": "To connect to real-time music service APIs for live data",
- "allowedUrls": [
- "wss://api.musicservice.com/ws",
- "wss://realtime.example.com"
- ],
- "allowLocalNetwork": false
+ "reason": "Real-time connection to service",
+ "requiredHosts": ["gateway.example.com", "*.discord.gg"]
}
}
}
```
-#### Artwork Service
+**Host functions:**
-Generate public URLs for artwork:
+| Function | Parameters | Description |
+|------------------------|---------------------------------|-------------------|
+| `websocket_connect` | `url, headers?, connectionId?` | Open a connection |
+| `websocket_sendtext` | `connectionId, message` | Send text message |
+| `websocket_sendbinary` | `connectionId, data` | Send binary data |
+| `websocket_close` | `connectionId, code?, reason?` | Close connection |
+
+**Callback functions (export these to receive events):**
+
+| Function | Input | Description |
+|----------------------------------|---------------------------------|----------------------------------|
+| `nd_websocket_on_text_message` | `{connectionId, message}` | Text message received |
+| `nd_websocket_on_binary_message` | `{connectionId, data}` | Binary message received (base64) |
+| `nd_websocket_on_error` | `{connectionId, error}` | Connection error |
+| `nd_websocket_on_close` | `{connectionId, code, reason}` | Connection closed |
+
+### Library
+
+Access music library metadata and optionally read files from library directories.
+
+**Manifest permission:**
+
+```json
+{
+ "permissions": {
+ "library": {
+ "reason": "Access library metadata for analysis",
+ "filesystem": false
+ }
+ }
+}
+```
+
+- `filesystem` – Set to `true` to enable read-only access to library directories (default: `false`)
+
+**Host functions:**
+
+| Function | Parameters | Returns |
+|----------------------------|------------|---------------------------|
+| `library_getlibrary` | `id` | Library metadata |
+| `library_getalllibraries` | (none) | Array of library metadata |
+
+**Library metadata:**
+
+```json
+{
+ "id": 1,
+ "name": "My Music",
+ "path": "/music/collection",
+ "mountPoint": "/libraries/1",
+ "lastScanAt": 1703270400,
+ "totalSongs": 5000,
+ "totalAlbums": 500,
+ "totalArtists": 200,
+ "totalSize": 50000000000,
+ "totalDuration": 1500000.5
+}
+```
+
+> **Note:** The `path` and `mountPoint` fields are only included when `filesystem: true` is set in the permission.
+
+**Filesystem access:**
+
+When `filesystem: true`, your plugin can read files from library directories via WASI filesystem APIs. Each library is mounted at `/libraries/`:
+
+```go
+import "os"
+
+// Read a file from library 1
+content, err := os.ReadFile("/libraries/1/Artist/Album/track.mp3")
+
+// List directory contents
+entries, err := os.ReadDir("/libraries/1/Artist")
+```
+
+> **Security:** Filesystem access is read-only and restricted to configured library paths only. Plugins cannot access other parts of the host filesystem.
+
+**Usage (with generated SDK):**
+
+Import the Go SDK (see [Scheduler](#scheduler) for `go.mod` setup). The `Library` struct is provided by the SDK:
+
+```go
+import "github.com/navidrome/navidrome/plugins/pdk/go/host"
+
+// Get a specific library
+resp, err := host.LibraryGetLibrary(1)
+if err != nil {
+ // Handle error
+}
+library := resp.Result
+
+// Get all libraries
+resp, err := host.LibraryGetAllLibraries()
+for _, lib := range resp.Result {
+ // lib is of type host.Library
+ fmt.Printf("Library: %s (%d songs)\n", lib.Name, lib.TotalSongs)
+}
+```
+
+### Artwork
+
+Generate public URLs for Navidrome artwork (albums, artists, tracks, playlists).
+
+**Manifest permission:**
```json
{
"permissions": {
"artwork": {
- "reason": "To generate public URLs for album and artist images"
+ "reason": "Get artwork URLs for display"
}
}
}
```
-### Error Handling
+**Host functions:**
-Plugins should use the standard error values (`plugin:not_found`, `plugin:not_implemented`) to indicate resource-not-found and unimplemented-method scenarios. All other errors will be propagated directly to the caller. Ensure your capability methods return errors via the response message `error` fields rather than panicking or relying on transport errors.
+| Function | Parameters | Returns |
+|--------------------------|------------|-------------|
+| `artwork_getartisturl` | `id, size` | Artwork URL |
+| `artwork_getalbumurl` | `id, size` | Artwork URL |
+| `artwork_gettrackurl` | `id, size` | Artwork URL |
+| `artwork_getplaylisturl` | `id, size` | Artwork URL |
-## Plugin Lifecycle and Statelessness
+### SubsonicAPI
-**Important**: Navidrome plugins are stateless. Each method call creates a new plugin instance which is destroyed afterward. This has several important implications:
+Call Navidrome's Subsonic API internally (no network round-trip).
-1. **No in-memory persistence**: Plugins cannot store state between method calls in memory
-2. **Each call is isolated**: Variables, configurations, and runtime state don't persist between calls
-3. **No shared resources**: Each plugin instance has its own memory space
+**Manifest permission:**
-This stateless design is crucial for security and stability:
-
-- Memory leaks in one call won't affect subsequent operations
-- A crashed plugin instance won't bring down the entire system
-- Resource usage is more predictable and contained
-
-When developing plugins, keep these guidelines in mind:
-
-- Don't try to cache data in memory between calls
-- Don't store authentication tokens or session data in variables
-- If persistence is needed, use external storage or the host's HTTP interface
-- Performance optimizations should focus on efficient per-call execution
-
-### Using Plugin Configuration
-
-Since plugins are stateless, you can use the `LifecycleManagement` interface to read configuration when your plugin is loaded and perform any necessary setup:
-
-```go
-func (p *myPlugin) OnInit(ctx context.Context, req *api.InitRequest) (*api.InitResponse, error) {
- // Access plugin configuration
- apiKey := req.Config["api_key"]
- if apiKey == "" {
- return &api.InitResponse{Error: "Missing API key in configuration"}, nil
+```json
+{
+ "permissions": {
+ "subsonicapi": {
+ "reason": "Access library data"
+ },
+ "users": {
+ "reason": "Access user information for SubsonicAPI authorization"
}
-
- // Validate configuration
- serverURL := req.Config["server_url"]
- if serverURL == "" {
- serverURL = "https://default-api.example.com" // Use default if not specified
- }
-
- // Perform initialization tasks (e.g., validate API key)
- httpClient := &http.HttpServiceClient{}
- resp, err := httpClient.Get(ctx, &http.HttpRequest{
- Url: serverURL + "/validate?key=" + apiKey,
- })
- if err != nil {
- return &api.InitResponse{Error: "Failed to validate API key: " + err.Error()}, nil
- }
-
- if resp.StatusCode != 200 {
- return &api.InitResponse{Error: "Invalid API key"}, nil
- }
-
- return &api.InitResponse{}, nil
+ }
}
```
-Remember, the `OnInit` method is called only once when the plugin is loaded. It cannot store any state that needs to persist between method calls. It's primarily useful for:
+> **Important:** The `subsonicapi` permission requires the `users` permission. User access is controlled through the plugin's database configuration, not the manifest. Configure which users can use the plugin through the Navidrome UI or API.
-1. Validating required configuration
-2. Checking API credentials
-3. Verifying connectivity to external services
-4. Initializing any external resources
+**Host function:**
-## Caching
+| Function | Parameters | Returns |
+|--------------------|------------|---------------|
+| `subsonicapi_call` | `uri` | JSON response |
-The plugin system implements a compilation cache to improve performance:
+**Usage:**
-1. Compiled WASM modules are cached in `[CacheFolder]/plugins`
-2. This reduces startup time for plugins that have already been compiled
-3. The cache has a automatic cleanup mechanism to remove old modules.
- - when the cache folder exceeds `Plugins.CacheSize` (default 100MB),
- the oldest modules are removed
+```go
+// The URI must include the 'u' parameter with the username
+response, err := SubsonicAPICall("getAlbumList2?type=random&size=10&u=username")
+```
-### WASM Loading Optimization
+### Config
-To improve performance during plugin instance creation, the system implements an optimization that avoids repeated file reads and compilation:
+Access plugin configuration values programmatically. Unlike `pdk.GetConfig()` which only retrieves individual values, this service can list all available configuration keys—useful for discovering dynamic configuration (e.g., user-to-token mappings).
-1. **Precompilation**: During plugin discovery, WASM files are read and compiled in the background, with both the MD5 hash of the file bytes and compiled modules cached in memory.
+> **Note:** This service is always available and does not require a manifest permission.
-2. **Optimized Runtime**: After precompilation completes, plugins use an `optimizedRuntime` wrapper that overrides `CompileModule` to detect when the same WASM bytes are being compiled by comparing MD5 hashes.
+**Host functions:**
-3. **Cache Hit**: When the generated plugin code calls `os.ReadFile()` and `CompileModule()`, the optimization calculates the MD5 hash of the incoming bytes and compares it with the cached hash. If they match, it returns the pre-compiled module directly.
+| Function | Parameters | Returns |
+|-----------------|------------|-----------------------------|
+| `config_get` | `key` | `value, exists` |
+| `config_getint` | `key` | `value, exists` |
+| `config_keys` | `prefix` | Array of matching key names |
-4. **Performance Benefit**: This eliminates repeated compilation while using minimal memory (16 bytes per plugin for the MD5 hash vs potentially MB of WASM bytes), significantly improving plugin instance creation speed while maintaining full compatibility with the generated API code.
+**Usage (with generated SDK):**
-5. **Memory Efficiency**: By storing only MD5 hashes instead of full WASM bytes, the optimization scales efficiently regardless of plugin size or count.
+```go
+import "github.com/navidrome/navidrome/plugins/pdk/go/host"
-The optimization is transparent to plugin developers and automatically activates when plugins are successfully precompiled.
+// Get a string configuration value
+value, exists := host.ConfigGet("api_key")
+if exists {
+ // Use the value
+}
-## Best Practices
+// Get an integer configuration value
+count, exists := host.ConfigGetInt("max_retries")
-1. **Resource Management**:
+// List all keys with a prefix (useful for user-specific config)
+keys := host.ConfigKeys("user:")
+for _, key := range keys {
+ // key might be "user:john", "user:jane", etc.
+}
- - The host handles HTTP response cleanup, so no need to close response objects
- - Keep plugin instances lightweight as they are created and destroyed frequently
+// List all configuration keys
+allKeys := host.ConfigKeys("")
+```
-2. **Error Handling**:
+### Users
- - Use the standard error types when appropriate
- - Return descriptive error messages for debugging
- - Custom errors are supported and will be propagated to the caller
+Access user information for the users that the plugin has been granted access to. This is useful for plugins that need to associate data with specific users or display user information.
-3. **Performance**:
+**Manifest permission:**
- - Remember plugins are stateless, so don't rely on local variables for caching. Use the CacheService for caching data.
- - Use efficient algorithms that work well in single-call scenarios
+```json
+{
+ "permissions": {
+ "users": {
+ "reason": "Display user information in status updates"
+ }
+ }
+}
+```
-4. **Security**:
- - Only request permissions you actually need (see [Plugin Permission System](#plugin-permission-system))
- - Validate inputs to prevent injection attacks
- - Don't store sensitive credentials in the plugin code
- - Use configuration for API keys and sensitive data
+**Important:** Before enabling a plugin that requires the `users` permission, an administrator must configure which users the plugin can access. This can be done in two ways:
-## Limitations
+1. **Allow all users** – Enable the "Allow all users" toggle in the plugin settings
+2. **Select specific users** – Choose individual users from the user list
-1. WASM plugins have limited access to system resources
-2. Plugin compilation has an initial overhead on first load, as it needs to be compiled to WebAssembly
- - Subsequent calls are faster due to caching
-3. New plugin capabilities types require changes to the core codebase
-4. Stateless nature prevents certain optimizations
+If neither option is configured, the plugin cannot be enabled.
-## Troubleshooting
+**Host functions:**
-1. **Plugin not detected**:
+| Function | Parameters | Returns |
+|------------------|------------|-----------------------|
+| `users_getusers` | – | Array of User objects |
- - Ensure `plugin.wasm` and `manifest.json` exist in the plugin directory
- - Check that the manifest contains valid capabilities names
- - Verify the manifest schema is valid (see [Plugin Permission System](#plugin-permission-system))
+**User object fields:**
-2. **Permission errors**:
+| Field | Type | Description |
+|------------|---------|--------------------------------|
+| `userName` | string | The user's unique username |
+| `name` | string | The user's display name |
+| `isAdmin` | boolean | Whether the user is an admin |
- - **"function not exported in module env"**: Plugin trying to use a service without proper permission
- - Check that required permissions are declared in `manifest.json`
- - See [Troubleshooting Permissions](#troubleshooting-permissions) for detailed guidance
+> **Security:** Sensitive fields like passwords, email addresses, and internal IDs are never exposed to plugins.
-3. **Compilation errors**:
+**Usage (with generated SDK):**
- - Check logs for WASM compilation errors
- - Verify the plugin is compatible with the current API version
+```go
+import "github.com/navidrome/navidrome/plugins/pdk/go/host"
-4. **Runtime errors**:
- - Look for error messages in the Navidrome logs
- - Add debug logging to your plugin
- - Check if the error is permission-related before debugging plugin logic
+// Get all users the plugin has access to
+users, err := host.UsersGetUsers()
+if err != nil {
+ pdk.Log(pdk.LogError, "Failed to get users: " + err.Error())
+ return
+}
+
+for _, user := range users {
+ pdk.Log(pdk.LogInfo, "User: " + user.UserName + " (" + user.Name + ")")
+ if user.IsAdmin {
+ pdk.Log(pdk.LogInfo, " - Administrator")
+ }
+}
+```
+
+**Rust example:**
+
+```rust
+use nd_pdk_host::users::get_users;
+
+let users = get_users()?;
+for user in users {
+ println!("User: {} ({})", user.user_name, user.name);
+}
+```
+
+**Python example:**
+
+```python
+from host.nd_host_users import users_get_users
+
+users = users_get_users()
+for user in users:
+ print(f"User: {user['userName']} ({user['name']})")
+```
+
+---
+
+## Configuration
+
+### Server Configuration
+
+Enable plugins in `navidrome.toml`:
+
+```toml
+[Plugins]
+Enabled = true
+Folder = "/path/to/plugins" # Default: DataFolder/plugins
+AutoReload = true # Auto-reload on file changes (dev mode)
+LogLevel = "debug" # Plugin-specific log level
+CacheSize = "200MB" # Compilation cache size limit
+```
+
+### Plugin Configuration
+
+Plugin configuration is managed through the Navidrome web UI. Navigate to the Plugins page, select a plugin, and edit its configuration as key-value pairs.
+
+Access configuration values in your plugin:
+
+```go
+apiKey, ok := pdk.GetConfig("api_key")
+if !ok {
+ pdk.SetErrorString("api_key configuration is required")
+ return 1
+}
+```
+
+---
+
+## Building Plugins
+
+### Supported Languages
+
+Plugins can be written in any language that Extism supports. Each language has its own PDK (Plugin Development Kit) that provides the APIs for I/O, logging, configuration, and HTTP requests. See the [Extism PDK documentation](https://extism.org/docs/concepts/pdk) for details.
+
+We recommend:
+
+- **Go** – Best experience with [TinyGo](https://tinygo.org/) and the [Go PDK](https://github.com/extism/go-pdk)
+- **Rust** – Excellent performance with the [Rust PDK](https://github.com/extism/rust-pdk)
+- **Python** – Experimental support via [extism-py](https://github.com/extism/python-pdk)
+- **TypeScript** – Experimental support via [extism-js](https://github.com/extism/js-pdk)
+
+### Go with TinyGo (Recommended)
+
+```bash
+# Install TinyGo: https://tinygo.org/getting-started/install/
+
+# Build WebAssembly module
+tinygo build -o plugin.wasm -target wasip1 -buildmode=c-shared .
+
+# Package as .ndp
+zip -j my-plugin.ndp manifest.json plugin.wasm
+```
+
+#### Using Go PDK Packages
+
+Navidrome provides type-safe Go packages for each capability in `plugins/pdk/go/`. Instead of manually exporting functions with `//go:wasmexport`, use the `Register()` pattern:
+
+```go
+package main
+
+import (
+ "github.com/navidrome/navidrome/plugins/pdk/go/metadata"
+)
+
+type myPlugin struct{}
+
+func (p *myPlugin) GetArtistBiography(input metadata.ArtistRequest) (*metadata.ArtistBiographyResponse, error) {
+ return &metadata.ArtistBiographyResponse{Biography: "Biography text..."}, nil
+}
+
+func init() {
+ metadata.Register(&myPlugin{})
+}
+
+func main() {}
+```
+
+Add to your `go.mod`:
+
+```
+require github.com/navidrome/navidrome v0.0.0
+replace github.com/navidrome/navidrome => ../../..
+```
+
+Available capability packages:
+
+| Package | Import Path | Description |
+|-------------|----------------------------|--------------------------------------|
+| `metadata` | `plugins/pdk/go/metadata` | Artist/album metadata providers |
+| `scrobbler` | `plugins/pdk/go/scrobbler` | Scrobbling services |
+| `lifecycle` | `plugins/pdk/go/lifecycle` | Plugin initialization |
+| `scheduler` | `plugins/pdk/go/scheduler` | Scheduled task callbacks |
+| `websocket` | `plugins/pdk/go/websocket` | WebSocket event handlers |
+| `host` | `plugins/pdk/go/host` | Host service SDK (HTTP, cache, etc.) |
+
+See the example plugins in [examples/](examples/) for complete usage patterns.
+
+### Rust
+
+```bash
+# Build WebAssembly module
+cargo build --release --target wasm32-wasip1
+
+# Package as .ndp
+zip -j my-plugin.ndp manifest.json target/wasm32-wasip1/release/plugin.wasm
+```
+
+#### Using Rust PDK
+
+The Rust PDK provides generated type-safe wrappers for both capabilities and host services:
+
+```toml
+# Cargo.toml
+[dependencies]
+nd-pdk = { path = "../../pdk/rust/nd-pdk" }
+extism-pdk = "1.2"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+```
+
+**Implementing capabilities with traits and macros:**
+
+```rust
+use nd_pdk::scrobbler::{Scrobbler, IsAuthorizedRequest, Error};
+use nd_pdk::register_scrobbler;
+
+#[derive(Default)]
+struct MyPlugin;
+
+impl Scrobbler for MyPlugin {
+ fn is_authorized(&self, req: IsAuthorizedRequest) -> Result {
+ Ok(true)
+ }
+ fn now_playing(&self, req: NowPlayingRequest) -> Result<(), Error> { Ok(()) }
+ fn scrobble(&self, req: ScrobbleRequest) -> Result<(), Error> { Ok(()) }
+}
+
+register_scrobbler!(MyPlugin); // Generates all WASM exports
+```
+
+**Using host services:**
+
+```rust
+use nd_pdk::host::{cache, scheduler, library};
+
+// Cache a value for 1 hour
+cache::set_string("my_key", "my_value", 3600)?;
+
+// Schedule a recurring task
+scheduler::schedule_recurring("@every 5m", "payload", "task_id")?;
+
+// Access library metadata
+let libs = library::get_all_libraries()?;
+```
+
+See [pdk/rust/README.md](pdk/rust/README.md) for detailed documentation and examples.
+
+### Python (with extism-py)
+
+```bash
+# Build WebAssembly module (requires extism-py installed)
+extism-py plugin.wasm -o plugin.wasm *.py
+
+# Package as .ndp
+zip -j my-plugin.ndp manifest.json plugin.wasm
+```
+
+### Using XTP CLI (Scaffolding)
+
+Bootstrap a new plugin from a schema:
+
+```bash
+# Install XTP CLI: https://docs.xtp.dylibso.com/docs/cli
+
+# Create a metadata agent plugin
+xtp plugin init \
+ --schema-file plugins/capabilities/metadata_agent.yaml \
+ --template go \
+ --path ./my-agent \
+ --name my-agent
+
+# Build and package
+cd my-agent && xtp plugin build
+zip -j my-agent.ndp manifest.json dist/plugin.wasm
+```
+
+See [capabilities/README.md](capabilities/README.md) for available schemas and scaffolding examples.
+
+### Using Host Service SDKs
+
+Generated SDKs for calling host services are in `plugins/pdk/go/`, `plugins/pdk/python/` and `plugins/pdk/rust`.
+
+**For Go plugins:** Import the SDK as a Go module:
+
+```go
+import "github.com/navidrome/navidrome/plugins/pdk/go/host"
+```
+
+Add to your `go.mod`:
+
+```
+require github.com/navidrome/navidrome/plugins/pdk/go v0.0.0
+replace github.com/navidrome/navidrome/plugins/pdk/go => ../../pdk/go
+```
+
+See [pdk/go/README.md](pdk/go/README.md) for detailed documentation.
+
+**For Python plugins:** Copy functions from `nd_host_*.py` into your `__init__.py` (see comments in those files for extism-py limitations).
+
+**Recommendations:**
+
+- **Go:** Best overall experience with excellent stdlib support and familiar syntax for most developers. Recommended if you're already in the Go ecosystem.
+- **Rust:** Best for performance-critical plugins or when leveraging Rust's ecosystem. Produces smallest binaries with excellent type safety.
+- **Python:** Best for rapid prototyping or simple plugins. Note that extism-py has limitations compared to compiled languages.
+
+---
+
+## Examples
+
+See [examples/](examples/) for complete working plugins:
+
+| Plugin | Language | Capabilities | Host Services | Description |
+|----------------------------------------------------------------|----------|---------------|--------------------------------------------|--------------------------------|
+| [minimal](examples/minimal/) | Go | MetadataAgent | – | Basic structure example |
+| [wikimedia](examples/wikimedia/) | Go | MetadataAgent | HTTP | Wikidata/Wikipedia integration |
+| [coverartarchive-py](examples/coverartarchive-py/) | Python | MetadataAgent | HTTP | Cover Art Archive |
+| [webhook-rs](examples/webhook-rs/) | Rust | Scrobbler | HTTP | HTTP webhooks |
+| [nowplaying-py](examples/nowplaying-py/) | Python | Lifecycle | Scheduler, SubsonicAPI | Periodic now-playing logger |
+| [library-inspector](examples/library-inspector-rs/) | Rust | Lifecycle | Library, Scheduler | Periodic library stats logging |
+| [crypto-ticker](examples/crypto-ticker/) | Go | Lifecycle | WebSocket, Scheduler | Real-time crypto prices demo |
+| [discord-rich-presence-rs](examples/discord-rich-presence-rs/) | Rust | Scrobbler | HTTP, WebSocket, Cache, Scheduler, Artwork | Discord integration (Rust) |
+
+---
+
+
+## Security
+
+Plugins run in a secure WebAssembly sandbox provided by [Extism](https://extism.org/) and the [Wazero](https://wazero.io/) runtime:
+
+1. **Host Allowlisting** – Only explicitly allowed hosts are accessible via HTTP/WebSocket
+2. **Limited File System** – Plugins can only access library directories when explicitly granted the `library.filesystem` permission, and access is read-only
+3. **No Network Listeners** – Plugins cannot bind ports
+4. **Config Isolation** – Plugins only receive their own config section
+5. **Memory Limits** – Controlled by the WebAssembly runtime
+6. **User-Scoped Authorization** – Plugins with `subsonicapi` or `scrobbler` capabilities can only access/receive events for users assigned to them through Navidrome's configuration. The `users` permission is required for these features.
+7. **Users Permission** – Plugins requesting user access must be explicitly configured with allowed users; sensitive data (passwords, emails) is never exposed
+
+
+---
+
+## Runtime Management
+
+### Auto-Reload
+
+With `AutoReload = true`, Navidrome watches the plugins folder and automatically detects when `.ndp` files are added, modified, or removed. When a plugin file changes, the plugin is disabled and its metadata is re-read from the archive.
+
+If the `AutoReload` setting is disabled, Navidrome needs to be restarted to pick up plugin changes.
+
+### Enabling/Disabling Plugins
+
+Plugins can be enabled/disabled via the Navidrome UI. The plugin state is persisted in the database.
+
+### Important Notes
+
+- **In-flight requests** – When reloading, existing requests complete before the new version takes over
+- **Config changes** – Changes to the plugin configuration in the UI are applied immediately
+- **Cache persistence** – The in-memory cache is cleared when a plugin is unloaded
diff --git a/plugins/adapter_media_agent.go b/plugins/adapter_media_agent.go
deleted file mode 100644
index eca891275..000000000
--- a/plugins/adapter_media_agent.go
+++ /dev/null
@@ -1,166 +0,0 @@
-package plugins
-
-import (
- "context"
-
- "github.com/navidrome/navidrome/core/agents"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/plugins/api"
- "github.com/tetratelabs/wazero"
-)
-
-// NewWasmMediaAgent creates a new adapter for a MetadataAgent plugin
-func newWasmMediaAgent(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
- loader, err := api.NewMetadataAgentPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
- if err != nil {
- log.Error("Error creating media metadata service plugin", "plugin", pluginID, "path", wasmPath, err)
- return nil
- }
- return &wasmMediaAgent{
- baseCapability: newBaseCapability[api.MetadataAgent, *api.MetadataAgentPlugin](
- wasmPath,
- pluginID,
- CapabilityMetadataAgent,
- m.metrics,
- loader,
- func(ctx context.Context, l *api.MetadataAgentPlugin, path string) (api.MetadataAgent, error) {
- return l.Load(ctx, path)
- },
- ),
- }
-}
-
-// wasmMediaAgent adapts a MetadataAgent plugin to implement the agents.Interface
-type wasmMediaAgent struct {
- *baseCapability[api.MetadataAgent, *api.MetadataAgentPlugin]
-}
-
-func (w *wasmMediaAgent) AgentName() string {
- return w.id
-}
-
-func (w *wasmMediaAgent) mapError(err error) error {
- if err != nil && (err.Error() == api.ErrNotFound.Error() || err.Error() == api.ErrNotImplemented.Error()) {
- return agents.ErrNotFound
- }
- return err
-}
-
-// Album-related methods
-
-func (w *wasmMediaAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid string) (*agents.AlbumInfo, error) {
- res, err := callMethod(ctx, w, "GetAlbumInfo", func(inst api.MetadataAgent) (*api.AlbumInfoResponse, error) {
- return inst.GetAlbumInfo(ctx, &api.AlbumInfoRequest{Name: name, Artist: artist, Mbid: mbid})
- })
- if err != nil {
- return nil, w.mapError(err)
- }
- if res == nil || res.Info == nil {
- return nil, agents.ErrNotFound
- }
- info := res.Info
- return &agents.AlbumInfo{
- Name: info.Name,
- MBID: info.Mbid,
- Description: info.Description,
- URL: info.Url,
- }, nil
-}
-
-func (w *wasmMediaAgent) GetAlbumImages(ctx context.Context, name, artist, mbid string) ([]agents.ExternalImage, error) {
- res, err := callMethod(ctx, w, "GetAlbumImages", func(inst api.MetadataAgent) (*api.AlbumImagesResponse, error) {
- return inst.GetAlbumImages(ctx, &api.AlbumImagesRequest{Name: name, Artist: artist, Mbid: mbid})
- })
- if err != nil {
- return nil, w.mapError(err)
- }
- return convertExternalImages(res.Images), nil
-}
-
-// Artist-related methods
-
-func (w *wasmMediaAgent) GetArtistMBID(ctx context.Context, id string, name string) (string, error) {
- res, err := callMethod(ctx, w, "GetArtistMBID", func(inst api.MetadataAgent) (*api.ArtistMBIDResponse, error) {
- return inst.GetArtistMBID(ctx, &api.ArtistMBIDRequest{Id: id, Name: name})
- })
- if err != nil {
- return "", w.mapError(err)
- }
- return res.GetMbid(), nil
-}
-
-func (w *wasmMediaAgent) GetArtistURL(ctx context.Context, id, name, mbid string) (string, error) {
- res, err := callMethod(ctx, w, "GetArtistURL", func(inst api.MetadataAgent) (*api.ArtistURLResponse, error) {
- return inst.GetArtistURL(ctx, &api.ArtistURLRequest{Id: id, Name: name, Mbid: mbid})
- })
- if err != nil {
- return "", w.mapError(err)
- }
- return res.GetUrl(), nil
-}
-
-func (w *wasmMediaAgent) GetArtistBiography(ctx context.Context, id, name, mbid string) (string, error) {
- res, err := callMethod(ctx, w, "GetArtistBiography", func(inst api.MetadataAgent) (*api.ArtistBiographyResponse, error) {
- return inst.GetArtistBiography(ctx, &api.ArtistBiographyRequest{Id: id, Name: name, Mbid: mbid})
- })
- if err != nil {
- return "", w.mapError(err)
- }
- return res.GetBiography(), nil
-}
-
-func (w *wasmMediaAgent) GetSimilarArtists(ctx context.Context, id, name, mbid string, limit int) ([]agents.Artist, error) {
- resp, err := callMethod(ctx, w, "GetSimilarArtists", func(inst api.MetadataAgent) (*api.ArtistSimilarResponse, error) {
- return inst.GetSimilarArtists(ctx, &api.ArtistSimilarRequest{Id: id, Name: name, Mbid: mbid, Limit: int32(limit)})
- })
- if err != nil {
- return nil, w.mapError(err)
- }
- artists := make([]agents.Artist, 0, len(resp.GetArtists()))
- for _, a := range resp.GetArtists() {
- artists = append(artists, agents.Artist{
- Name: a.GetName(),
- MBID: a.GetMbid(),
- })
- }
- return artists, nil
-}
-
-func (w *wasmMediaAgent) GetArtistImages(ctx context.Context, id, name, mbid string) ([]agents.ExternalImage, error) {
- resp, err := callMethod(ctx, w, "GetArtistImages", func(inst api.MetadataAgent) (*api.ArtistImageResponse, error) {
- return inst.GetArtistImages(ctx, &api.ArtistImageRequest{Id: id, Name: name, Mbid: mbid})
- })
- if err != nil {
- return nil, w.mapError(err)
- }
- return convertExternalImages(resp.Images), nil
-}
-
-func (w *wasmMediaAgent) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]agents.Song, error) {
- resp, err := callMethod(ctx, w, "GetArtistTopSongs", func(inst api.MetadataAgent) (*api.ArtistTopSongsResponse, error) {
- return inst.GetArtistTopSongs(ctx, &api.ArtistTopSongsRequest{Id: id, ArtistName: artistName, Mbid: mbid, Count: int32(count)})
- })
- if err != nil {
- return nil, w.mapError(err)
- }
- songs := make([]agents.Song, 0, len(resp.GetSongs()))
- for _, s := range resp.GetSongs() {
- songs = append(songs, agents.Song{
- Name: s.GetName(),
- MBID: s.GetMbid(),
- })
- }
- return songs, nil
-}
-
-// Helper function to convert ExternalImage objects from the API to the agents package
-func convertExternalImages(images []*api.ExternalImage) []agents.ExternalImage {
- result := make([]agents.ExternalImage, 0, len(images))
- for _, img := range images {
- result = append(result, agents.ExternalImage{
- URL: img.GetUrl(),
- Size: int(img.GetSize()),
- })
- }
- return result
-}
diff --git a/plugins/adapter_media_agent_test.go b/plugins/adapter_media_agent_test.go
deleted file mode 100644
index 70b5d275a..000000000
--- a/plugins/adapter_media_agent_test.go
+++ /dev/null
@@ -1,227 +0,0 @@
-package plugins
-
-import (
- "context"
- "errors"
-
- "github.com/navidrome/navidrome/conf"
- "github.com/navidrome/navidrome/conf/configtest"
- "github.com/navidrome/navidrome/core/agents"
- "github.com/navidrome/navidrome/core/metrics"
- "github.com/navidrome/navidrome/plugins/api"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Adapter Media Agent", func() {
- var ctx context.Context
- var mgr *managerImpl
-
- BeforeEach(func() {
- ctx = GinkgoT().Context()
-
- // Ensure plugins folder is set to testdata
- DeferCleanup(configtest.SetupConfig())
- conf.Server.Plugins.Folder = testDataDir
-
- mgr = createManager(nil, metrics.NewNoopInstance())
- mgr.ScanPlugins()
-
- // Wait for all plugins to compile to avoid race conditions
- err := mgr.EnsureCompiled("multi_plugin")
- Expect(err).NotTo(HaveOccurred(), "multi_plugin should compile successfully")
- err = mgr.EnsureCompiled("fake_album_agent")
- Expect(err).NotTo(HaveOccurred(), "fake_album_agent should compile successfully")
- })
-
- Describe("AgentName and PluginName", func() {
- It("should return the plugin name", func() {
- agent := mgr.LoadPlugin("multi_plugin", "MetadataAgent")
- Expect(agent).NotTo(BeNil(), "multi_plugin should be loaded")
- Expect(agent.PluginID()).To(Equal("multi_plugin"))
- })
- It("should return the agent name", func() {
- agent, ok := mgr.LoadMediaAgent("multi_plugin")
- Expect(ok).To(BeTrue(), "multi_plugin should be loaded as media agent")
- Expect(agent.AgentName()).To(Equal("multi_plugin"))
- })
- })
-
- Describe("Album methods", func() {
- var agent *wasmMediaAgent
-
- BeforeEach(func() {
- a, ok := mgr.LoadMediaAgent("fake_album_agent")
- Expect(ok).To(BeTrue(), "fake_album_agent should be loaded")
- agent = a.(*wasmMediaAgent)
- })
-
- Context("GetAlbumInfo", func() {
- It("should return album information", func() {
- info, err := agent.GetAlbumInfo(ctx, "Test Album", "Test Artist", "mbid")
-
- Expect(err).NotTo(HaveOccurred())
- Expect(info).NotTo(BeNil())
- Expect(info.Name).To(Equal("Test Album"))
- Expect(info.MBID).To(Equal("album-mbid-123"))
- Expect(info.Description).To(Equal("This is a test album description"))
- Expect(info.URL).To(Equal("https://example.com/album"))
- })
-
- It("should return ErrNotFound when plugin returns not found", func() {
- _, err := agent.GetAlbumInfo(ctx, "Test Album", "", "mbid")
-
- Expect(err).To(Equal(agents.ErrNotFound))
- })
-
- It("should return ErrNotFound when plugin returns nil response", func() {
- _, err := agent.GetAlbumInfo(ctx, "", "", "")
-
- Expect(err).To(Equal(agents.ErrNotFound))
- })
- })
-
- Context("GetAlbumImages", func() {
- It("should return album images", func() {
- images, err := agent.GetAlbumImages(ctx, "Test Album", "Test Artist", "mbid")
-
- Expect(err).NotTo(HaveOccurred())
- Expect(images).To(Equal([]agents.ExternalImage{
- {URL: "https://example.com/album1.jpg", Size: 300},
- {URL: "https://example.com/album2.jpg", Size: 400},
- }))
- })
- })
- })
-
- Describe("Artist methods", func() {
- var agent *wasmMediaAgent
-
- BeforeEach(func() {
- a, ok := mgr.LoadMediaAgent("fake_artist_agent")
- Expect(ok).To(BeTrue(), "fake_artist_agent should be loaded")
- agent = a.(*wasmMediaAgent)
- })
-
- Context("GetArtistMBID", func() {
- It("should return artist MBID", func() {
- mbid, err := agent.GetArtistMBID(ctx, "artist-id", "Test Artist")
-
- Expect(err).NotTo(HaveOccurred())
- Expect(mbid).To(Equal("1234567890"))
- })
-
- It("should return ErrNotFound when plugin returns not found", func() {
- _, err := agent.GetArtistMBID(ctx, "artist-id", "")
-
- Expect(err).To(Equal(agents.ErrNotFound))
- })
- })
-
- Context("GetArtistURL", func() {
- It("should return artist URL", func() {
- url, err := agent.GetArtistURL(ctx, "artist-id", "Test Artist", "mbid")
-
- Expect(err).NotTo(HaveOccurred())
- Expect(url).To(Equal("https://example.com"))
- })
- })
-
- Context("GetArtistBiography", func() {
- It("should return artist biography", func() {
- bio, err := agent.GetArtistBiography(ctx, "artist-id", "Test Artist", "mbid")
-
- Expect(err).NotTo(HaveOccurred())
- Expect(bio).To(Equal("This is a test biography"))
- })
- })
-
- Context("GetSimilarArtists", func() {
- It("should return similar artists", func() {
- artists, err := agent.GetSimilarArtists(ctx, "artist-id", "Test Artist", "mbid", 10)
-
- Expect(err).NotTo(HaveOccurred())
- Expect(artists).To(Equal([]agents.Artist{
- {Name: "Similar Artist 1", MBID: "mbid1"},
- {Name: "Similar Artist 2", MBID: "mbid2"},
- }))
- })
- })
-
- Context("GetArtistImages", func() {
- It("should return artist images", func() {
- images, err := agent.GetArtistImages(ctx, "artist-id", "Test Artist", "mbid")
-
- Expect(err).NotTo(HaveOccurred())
- Expect(images).To(Equal([]agents.ExternalImage{
- {URL: "https://example.com/image1.jpg", Size: 100},
- {URL: "https://example.com/image2.jpg", Size: 200},
- }))
- })
- })
-
- Context("GetArtistTopSongs", func() {
- It("should return artist top songs", func() {
- songs, err := agent.GetArtistTopSongs(ctx, "artist-id", "Test Artist", "mbid", 10)
-
- Expect(err).NotTo(HaveOccurred())
- Expect(songs).To(Equal([]agents.Song{
- {Name: "Song 1", MBID: "mbid1"},
- {Name: "Song 2", MBID: "mbid2"},
- }))
- })
- })
- })
-
- Describe("Helper functions", func() {
- It("convertExternalImages should convert API image objects to agent image objects", func() {
- apiImages := []*api.ExternalImage{
- {Url: "https://example.com/image1.jpg", Size: 100},
- {Url: "https://example.com/image2.jpg", Size: 200},
- }
-
- agentImages := convertExternalImages(apiImages)
- Expect(agentImages).To(HaveLen(2))
-
- for i, img := range agentImages {
- Expect(img.URL).To(Equal(apiImages[i].Url))
- Expect(img.Size).To(Equal(int(apiImages[i].Size)))
- }
- })
-
- It("convertExternalImages should handle empty slice", func() {
- agentImages := convertExternalImages([]*api.ExternalImage{})
- Expect(agentImages).To(BeEmpty())
- })
-
- It("convertExternalImages should handle nil", func() {
- agentImages := convertExternalImages(nil)
- Expect(agentImages).To(BeEmpty())
- })
- })
-
- Describe("Error mapping", func() {
- var agent wasmMediaAgent
-
- It("should map API ErrNotFound to agents.ErrNotFound", func() {
- err := agent.mapError(api.ErrNotFound)
- Expect(err).To(Equal(agents.ErrNotFound))
- })
-
- It("should map API ErrNotImplemented to agents.ErrNotFound", func() {
- err := agent.mapError(api.ErrNotImplemented)
- Expect(err).To(Equal(agents.ErrNotFound))
- })
-
- It("should pass through other errors", func() {
- testErr := errors.New("test error")
- err := agent.mapError(testErr)
- Expect(err).To(Equal(testErr))
- })
-
- It("should handle nil error", func() {
- err := agent.mapError(nil)
- Expect(err).To(BeNil())
- })
- })
-})
diff --git a/plugins/adapter_scheduler_callback.go b/plugins/adapter_scheduler_callback.go
deleted file mode 100644
index 64b7eefff..000000000
--- a/plugins/adapter_scheduler_callback.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package plugins
-
-import (
- "context"
-
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/plugins/api"
- "github.com/tetratelabs/wazero"
-)
-
-// newWasmSchedulerCallback creates a new adapter for a SchedulerCallback plugin
-func newWasmSchedulerCallback(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
- loader, err := api.NewSchedulerCallbackPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
- if err != nil {
- log.Error("Error creating scheduler callback plugin", "plugin", pluginID, "path", wasmPath, err)
- return nil
- }
- return &wasmSchedulerCallback{
- baseCapability: newBaseCapability[api.SchedulerCallback, *api.SchedulerCallbackPlugin](
- wasmPath,
- pluginID,
- CapabilitySchedulerCallback,
- m.metrics,
- loader,
- func(ctx context.Context, l *api.SchedulerCallbackPlugin, path string) (api.SchedulerCallback, error) {
- return l.Load(ctx, path)
- },
- ),
- }
-}
-
-// wasmSchedulerCallback adapts a SchedulerCallback plugin
-type wasmSchedulerCallback struct {
- *baseCapability[api.SchedulerCallback, *api.SchedulerCallbackPlugin]
-}
-
-func (w *wasmSchedulerCallback) OnSchedulerCallback(ctx context.Context, scheduleID string, payload []byte, isRecurring bool) error {
- _, err := callMethod(ctx, w, "OnSchedulerCallback", func(inst api.SchedulerCallback) (*api.SchedulerCallbackResponse, error) {
- return inst.OnSchedulerCallback(ctx, &api.SchedulerCallbackRequest{
- ScheduleId: scheduleID,
- Payload: payload,
- IsRecurring: isRecurring,
- })
- })
- return err
-}
diff --git a/plugins/adapter_scrobbler.go b/plugins/adapter_scrobbler.go
deleted file mode 100644
index 54c6af127..000000000
--- a/plugins/adapter_scrobbler.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package plugins
-
-import (
- "context"
- "time"
-
- "github.com/navidrome/navidrome/core/scrobbler"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/model"
- "github.com/navidrome/navidrome/model/request"
- "github.com/navidrome/navidrome/plugins/api"
- "github.com/tetratelabs/wazero"
-)
-
-func newWasmScrobblerPlugin(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
- loader, err := api.NewScrobblerPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
- if err != nil {
- log.Error("Error creating scrobbler service plugin", "plugin", pluginID, "path", wasmPath, err)
- return nil
- }
- return &wasmScrobblerPlugin{
- baseCapability: newBaseCapability[api.Scrobbler, *api.ScrobblerPlugin](
- wasmPath,
- pluginID,
- CapabilityScrobbler,
- m.metrics,
- loader,
- func(ctx context.Context, l *api.ScrobblerPlugin, path string) (api.Scrobbler, error) {
- return l.Load(ctx, path)
- },
- ),
- }
-}
-
-type wasmScrobblerPlugin struct {
- *baseCapability[api.Scrobbler, *api.ScrobblerPlugin]
-}
-
-func (w *wasmScrobblerPlugin) IsAuthorized(ctx context.Context, userId string) bool {
- username, _ := request.UsernameFrom(ctx)
- if username == "" {
- u, ok := request.UserFrom(ctx)
- if ok {
- username = u.UserName
- }
- }
- resp, err := callMethod(ctx, w, "IsAuthorized", func(inst api.Scrobbler) (*api.ScrobblerIsAuthorizedResponse, error) {
- return inst.IsAuthorized(ctx, &api.ScrobblerIsAuthorizedRequest{
- UserId: userId,
- Username: username,
- })
- })
- if err != nil {
- log.Warn("Error calling IsAuthorized", "userId", userId, "pluginID", w.id, err)
- }
- return err == nil && resp.Authorized
-}
-
-func (w *wasmScrobblerPlugin) NowPlaying(ctx context.Context, userId string, track *model.MediaFile, position int) error {
- username, _ := request.UsernameFrom(ctx)
- if username == "" {
- u, ok := request.UserFrom(ctx)
- if ok {
- username = u.UserName
- }
- }
-
- trackInfo := w.toTrackInfo(track, position)
- _, err := callMethod(ctx, w, "NowPlaying", func(inst api.Scrobbler) (struct{}, error) {
- resp, err := inst.NowPlaying(ctx, &api.ScrobblerNowPlayingRequest{
- UserId: userId,
- Username: username,
- Track: trackInfo,
- Timestamp: time.Now().Unix(),
- })
- if err != nil {
- return struct{}{}, err
- }
- if resp.Error != "" {
- return struct{}{}, nil
- }
- return struct{}{}, nil
- })
- return err
-}
-
-func (w *wasmScrobblerPlugin) Scrobble(ctx context.Context, userId string, s scrobbler.Scrobble) error {
- username, _ := request.UsernameFrom(ctx)
- if username == "" {
- u, ok := request.UserFrom(ctx)
- if ok {
- username = u.UserName
- }
- }
- trackInfo := w.toTrackInfo(&s.MediaFile, 0)
- _, err := callMethod(ctx, w, "Scrobble", func(inst api.Scrobbler) (struct{}, error) {
- resp, err := inst.Scrobble(ctx, &api.ScrobblerScrobbleRequest{
- UserId: userId,
- Username: username,
- Track: trackInfo,
- Timestamp: s.TimeStamp.Unix(),
- })
- if err != nil {
- return struct{}{}, err
- }
- if resp.Error != "" {
- return struct{}{}, nil
- }
- return struct{}{}, nil
- })
- return err
-}
-
-func (w *wasmScrobblerPlugin) toTrackInfo(track *model.MediaFile, position int) *api.TrackInfo {
- artists := make([]*api.Artist, 0, len(track.Participants[model.RoleArtist]))
-
- for _, a := range track.Participants[model.RoleArtist] {
- artists = append(artists, &api.Artist{Name: a.Name, Mbid: a.MbzArtistID})
- }
- albumArtists := make([]*api.Artist, 0, len(track.Participants[model.RoleAlbumArtist]))
- for _, a := range track.Participants[model.RoleAlbumArtist] {
- albumArtists = append(albumArtists, &api.Artist{Name: a.Name, Mbid: a.MbzArtistID})
- }
- trackInfo := &api.TrackInfo{
- Id: track.ID,
- Mbid: track.MbzRecordingID,
- Name: track.Title,
- Album: track.Album,
- AlbumMbid: track.MbzAlbumID,
- Artists: artists,
- AlbumArtists: albumArtists,
- Length: int32(track.Duration),
- Position: int32(position),
- }
- return trackInfo
-}
diff --git a/plugins/adapter_websocket_callback.go b/plugins/adapter_websocket_callback.go
deleted file mode 100644
index 83b8dd567..000000000
--- a/plugins/adapter_websocket_callback.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package plugins
-
-import (
- "context"
-
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/plugins/api"
- "github.com/tetratelabs/wazero"
-)
-
-// newWasmWebSocketCallback creates a new adapter for a WebSocketCallback plugin
-func newWasmWebSocketCallback(wasmPath, pluginID string, m *managerImpl, runtime api.WazeroNewRuntime, mc wazero.ModuleConfig) WasmPlugin {
- loader, err := api.NewWebSocketCallbackPlugin(context.Background(), api.WazeroRuntime(runtime), api.WazeroModuleConfig(mc))
- if err != nil {
- log.Error("Error creating WebSocket callback plugin", "plugin", pluginID, "path", wasmPath, err)
- return nil
- }
- return &wasmWebSocketCallback{
- baseCapability: newBaseCapability[api.WebSocketCallback, *api.WebSocketCallbackPlugin](
- wasmPath,
- pluginID,
- CapabilityWebSocketCallback,
- m.metrics,
- loader,
- func(ctx context.Context, l *api.WebSocketCallbackPlugin, path string) (api.WebSocketCallback, error) {
- return l.Load(ctx, path)
- },
- ),
- }
-}
-
-// wasmWebSocketCallback adapts a WebSocketCallback plugin
-type wasmWebSocketCallback struct {
- *baseCapability[api.WebSocketCallback, *api.WebSocketCallbackPlugin]
-}
diff --git a/plugins/api/api.pb.go b/plugins/api/api.pb.go
deleted file mode 100644
index b570d5c61..000000000
--- a/plugins/api/api.pb.go
+++ /dev/null
@@ -1,1136 +0,0 @@
-// Code generated by protoc-gen-go-plugin. DO NOT EDIT.
-// versions:
-// protoc-gen-go-plugin v0.1.0
-// protoc v5.29.3
-// source: api/api.proto
-
-package api
-
-import (
- context "context"
- protoreflect "google.golang.org/protobuf/reflect/protoreflect"
- protoimpl "google.golang.org/protobuf/runtime/protoimpl"
-)
-
-const (
- // Verify that this generated code is sufficiently up-to-date.
- _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
- // Verify that runtime/protoimpl is sufficiently up-to-date.
- _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
-)
-
-type ArtistMBIDRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
- Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
-}
-
-func (x *ArtistMBIDRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistMBIDRequest) GetId() string {
- if x != nil {
- return x.Id
- }
- return ""
-}
-
-func (x *ArtistMBIDRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-type ArtistMBIDResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Mbid string `protobuf:"bytes,1,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *ArtistMBIDResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistMBIDResponse) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type ArtistURLRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
- Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
- Mbid string `protobuf:"bytes,3,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *ArtistURLRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistURLRequest) GetId() string {
- if x != nil {
- return x.Id
- }
- return ""
-}
-
-func (x *ArtistURLRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *ArtistURLRequest) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type ArtistURLResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
-}
-
-func (x *ArtistURLResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistURLResponse) GetUrl() string {
- if x != nil {
- return x.Url
- }
- return ""
-}
-
-type ArtistBiographyRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
- Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
- Mbid string `protobuf:"bytes,3,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *ArtistBiographyRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistBiographyRequest) GetId() string {
- if x != nil {
- return x.Id
- }
- return ""
-}
-
-func (x *ArtistBiographyRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *ArtistBiographyRequest) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type ArtistBiographyResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Biography string `protobuf:"bytes,1,opt,name=biography,proto3" json:"biography,omitempty"`
-}
-
-func (x *ArtistBiographyResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistBiographyResponse) GetBiography() string {
- if x != nil {
- return x.Biography
- }
- return ""
-}
-
-type ArtistSimilarRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
- Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
- Mbid string `protobuf:"bytes,3,opt,name=mbid,proto3" json:"mbid,omitempty"`
- Limit int32 `protobuf:"varint,4,opt,name=limit,proto3" json:"limit,omitempty"`
-}
-
-func (x *ArtistSimilarRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistSimilarRequest) GetId() string {
- if x != nil {
- return x.Id
- }
- return ""
-}
-
-func (x *ArtistSimilarRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *ArtistSimilarRequest) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-func (x *ArtistSimilarRequest) GetLimit() int32 {
- if x != nil {
- return x.Limit
- }
- return 0
-}
-
-type Artist struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- Mbid string `protobuf:"bytes,2,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *Artist) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *Artist) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *Artist) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type ArtistSimilarResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Artists []*Artist `protobuf:"bytes,1,rep,name=artists,proto3" json:"artists,omitempty"`
-}
-
-func (x *ArtistSimilarResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistSimilarResponse) GetArtists() []*Artist {
- if x != nil {
- return x.Artists
- }
- return nil
-}
-
-type ArtistImageRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
- Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
- Mbid string `protobuf:"bytes,3,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *ArtistImageRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistImageRequest) GetId() string {
- if x != nil {
- return x.Id
- }
- return ""
-}
-
-func (x *ArtistImageRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *ArtistImageRequest) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type ExternalImage struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
- Size int32 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"`
-}
-
-func (x *ExternalImage) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ExternalImage) GetUrl() string {
- if x != nil {
- return x.Url
- }
- return ""
-}
-
-func (x *ExternalImage) GetSize() int32 {
- if x != nil {
- return x.Size
- }
- return 0
-}
-
-type ArtistImageResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Images []*ExternalImage `protobuf:"bytes,1,rep,name=images,proto3" json:"images,omitempty"`
-}
-
-func (x *ArtistImageResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistImageResponse) GetImages() []*ExternalImage {
- if x != nil {
- return x.Images
- }
- return nil
-}
-
-type ArtistTopSongsRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
- ArtistName string `protobuf:"bytes,2,opt,name=artistName,proto3" json:"artistName,omitempty"`
- Mbid string `protobuf:"bytes,3,opt,name=mbid,proto3" json:"mbid,omitempty"`
- Count int32 `protobuf:"varint,4,opt,name=count,proto3" json:"count,omitempty"`
-}
-
-func (x *ArtistTopSongsRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistTopSongsRequest) GetId() string {
- if x != nil {
- return x.Id
- }
- return ""
-}
-
-func (x *ArtistTopSongsRequest) GetArtistName() string {
- if x != nil {
- return x.ArtistName
- }
- return ""
-}
-
-func (x *ArtistTopSongsRequest) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-func (x *ArtistTopSongsRequest) GetCount() int32 {
- if x != nil {
- return x.Count
- }
- return 0
-}
-
-type Song struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- Mbid string `protobuf:"bytes,2,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *Song) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *Song) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *Song) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type ArtistTopSongsResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Songs []*Song `protobuf:"bytes,1,rep,name=songs,proto3" json:"songs,omitempty"`
-}
-
-func (x *ArtistTopSongsResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ArtistTopSongsResponse) GetSongs() []*Song {
- if x != nil {
- return x.Songs
- }
- return nil
-}
-
-type AlbumInfoRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- Artist string `protobuf:"bytes,2,opt,name=artist,proto3" json:"artist,omitempty"`
- Mbid string `protobuf:"bytes,3,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *AlbumInfoRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *AlbumInfoRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *AlbumInfoRequest) GetArtist() string {
- if x != nil {
- return x.Artist
- }
- return ""
-}
-
-func (x *AlbumInfoRequest) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type AlbumInfo struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- Mbid string `protobuf:"bytes,2,opt,name=mbid,proto3" json:"mbid,omitempty"`
- Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
- Url string `protobuf:"bytes,4,opt,name=url,proto3" json:"url,omitempty"`
-}
-
-func (x *AlbumInfo) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *AlbumInfo) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *AlbumInfo) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-func (x *AlbumInfo) GetDescription() string {
- if x != nil {
- return x.Description
- }
- return ""
-}
-
-func (x *AlbumInfo) GetUrl() string {
- if x != nil {
- return x.Url
- }
- return ""
-}
-
-type AlbumInfoResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Info *AlbumInfo `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"`
-}
-
-func (x *AlbumInfoResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *AlbumInfoResponse) GetInfo() *AlbumInfo {
- if x != nil {
- return x.Info
- }
- return nil
-}
-
-type AlbumImagesRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- Artist string `protobuf:"bytes,2,opt,name=artist,proto3" json:"artist,omitempty"`
- Mbid string `protobuf:"bytes,3,opt,name=mbid,proto3" json:"mbid,omitempty"`
-}
-
-func (x *AlbumImagesRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *AlbumImagesRequest) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *AlbumImagesRequest) GetArtist() string {
- if x != nil {
- return x.Artist
- }
- return ""
-}
-
-func (x *AlbumImagesRequest) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-type AlbumImagesResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Images []*ExternalImage `protobuf:"bytes,1,rep,name=images,proto3" json:"images,omitempty"`
-}
-
-func (x *AlbumImagesResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *AlbumImagesResponse) GetImages() []*ExternalImage {
- if x != nil {
- return x.Images
- }
- return nil
-}
-
-type ScrobblerIsAuthorizedRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
- Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"`
-}
-
-func (x *ScrobblerIsAuthorizedRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ScrobblerIsAuthorizedRequest) GetUserId() string {
- if x != nil {
- return x.UserId
- }
- return ""
-}
-
-func (x *ScrobblerIsAuthorizedRequest) GetUsername() string {
- if x != nil {
- return x.Username
- }
- return ""
-}
-
-type ScrobblerIsAuthorizedResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Authorized bool `protobuf:"varint,1,opt,name=authorized,proto3" json:"authorized,omitempty"`
- Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"`
-}
-
-func (x *ScrobblerIsAuthorizedResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ScrobblerIsAuthorizedResponse) GetAuthorized() bool {
- if x != nil {
- return x.Authorized
- }
- return false
-}
-
-func (x *ScrobblerIsAuthorizedResponse) GetError() string {
- if x != nil {
- return x.Error
- }
- return ""
-}
-
-type TrackInfo struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
- Mbid string `protobuf:"bytes,2,opt,name=mbid,proto3" json:"mbid,omitempty"`
- Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"`
- Album string `protobuf:"bytes,4,opt,name=album,proto3" json:"album,omitempty"`
- AlbumMbid string `protobuf:"bytes,5,opt,name=album_mbid,json=albumMbid,proto3" json:"album_mbid,omitempty"`
- Artists []*Artist `protobuf:"bytes,6,rep,name=artists,proto3" json:"artists,omitempty"`
- AlbumArtists []*Artist `protobuf:"bytes,7,rep,name=album_artists,json=albumArtists,proto3" json:"album_artists,omitempty"`
- Length int32 `protobuf:"varint,8,opt,name=length,proto3" json:"length,omitempty"` // seconds
- Position int32 `protobuf:"varint,9,opt,name=position,proto3" json:"position,omitempty"` // seconds
-}
-
-func (x *TrackInfo) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *TrackInfo) GetId() string {
- if x != nil {
- return x.Id
- }
- return ""
-}
-
-func (x *TrackInfo) GetMbid() string {
- if x != nil {
- return x.Mbid
- }
- return ""
-}
-
-func (x *TrackInfo) GetName() string {
- if x != nil {
- return x.Name
- }
- return ""
-}
-
-func (x *TrackInfo) GetAlbum() string {
- if x != nil {
- return x.Album
- }
- return ""
-}
-
-func (x *TrackInfo) GetAlbumMbid() string {
- if x != nil {
- return x.AlbumMbid
- }
- return ""
-}
-
-func (x *TrackInfo) GetArtists() []*Artist {
- if x != nil {
- return x.Artists
- }
- return nil
-}
-
-func (x *TrackInfo) GetAlbumArtists() []*Artist {
- if x != nil {
- return x.AlbumArtists
- }
- return nil
-}
-
-func (x *TrackInfo) GetLength() int32 {
- if x != nil {
- return x.Length
- }
- return 0
-}
-
-func (x *TrackInfo) GetPosition() int32 {
- if x != nil {
- return x.Position
- }
- return 0
-}
-
-type ScrobblerNowPlayingRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
- Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"`
- Track *TrackInfo `protobuf:"bytes,3,opt,name=track,proto3" json:"track,omitempty"`
- Timestamp int64 `protobuf:"varint,4,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
-}
-
-func (x *ScrobblerNowPlayingRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ScrobblerNowPlayingRequest) GetUserId() string {
- if x != nil {
- return x.UserId
- }
- return ""
-}
-
-func (x *ScrobblerNowPlayingRequest) GetUsername() string {
- if x != nil {
- return x.Username
- }
- return ""
-}
-
-func (x *ScrobblerNowPlayingRequest) GetTrack() *TrackInfo {
- if x != nil {
- return x.Track
- }
- return nil
-}
-
-func (x *ScrobblerNowPlayingRequest) GetTimestamp() int64 {
- if x != nil {
- return x.Timestamp
- }
- return 0
-}
-
-type ScrobblerNowPlayingResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"`
-}
-
-func (x *ScrobblerNowPlayingResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ScrobblerNowPlayingResponse) GetError() string {
- if x != nil {
- return x.Error
- }
- return ""
-}
-
-type ScrobblerScrobbleRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
- Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"`
- Track *TrackInfo `protobuf:"bytes,3,opt,name=track,proto3" json:"track,omitempty"`
- Timestamp int64 `protobuf:"varint,4,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
-}
-
-func (x *ScrobblerScrobbleRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ScrobblerScrobbleRequest) GetUserId() string {
- if x != nil {
- return x.UserId
- }
- return ""
-}
-
-func (x *ScrobblerScrobbleRequest) GetUsername() string {
- if x != nil {
- return x.Username
- }
- return ""
-}
-
-func (x *ScrobblerScrobbleRequest) GetTrack() *TrackInfo {
- if x != nil {
- return x.Track
- }
- return nil
-}
-
-func (x *ScrobblerScrobbleRequest) GetTimestamp() int64 {
- if x != nil {
- return x.Timestamp
- }
- return 0
-}
-
-type ScrobblerScrobbleResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"`
-}
-
-func (x *ScrobblerScrobbleResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *ScrobblerScrobbleResponse) GetError() string {
- if x != nil {
- return x.Error
- }
- return ""
-}
-
-type SchedulerCallbackRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- ScheduleId string `protobuf:"bytes,1,opt,name=schedule_id,json=scheduleId,proto3" json:"schedule_id,omitempty"` // ID of the scheduled job that triggered this callback
- Payload []byte `protobuf:"bytes,2,opt,name=payload,proto3" json:"payload,omitempty"` // The data passed when the job was scheduled
- IsRecurring bool `protobuf:"varint,3,opt,name=is_recurring,json=isRecurring,proto3" json:"is_recurring,omitempty"` // Whether this is from a recurring schedule (cron job)
-}
-
-func (x *SchedulerCallbackRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *SchedulerCallbackRequest) GetScheduleId() string {
- if x != nil {
- return x.ScheduleId
- }
- return ""
-}
-
-func (x *SchedulerCallbackRequest) GetPayload() []byte {
- if x != nil {
- return x.Payload
- }
- return nil
-}
-
-func (x *SchedulerCallbackRequest) GetIsRecurring() bool {
- if x != nil {
- return x.IsRecurring
- }
- return false
-}
-
-type SchedulerCallbackResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` // Error message if the callback failed
-}
-
-func (x *SchedulerCallbackResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *SchedulerCallbackResponse) GetError() string {
- if x != nil {
- return x.Error
- }
- return ""
-}
-
-type InitRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Config map[string]string `protobuf:"bytes,1,rep,name=config,proto3" json:"config,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Configuration specific to this plugin
-}
-
-func (x *InitRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *InitRequest) GetConfig() map[string]string {
- if x != nil {
- return x.Config
- }
- return nil
-}
-
-type InitResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` // Error message if initialization failed
-}
-
-func (x *InitResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *InitResponse) GetError() string {
- if x != nil {
- return x.Error
- }
- return ""
-}
-
-type OnTextMessageRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- ConnectionId string `protobuf:"bytes,1,opt,name=connection_id,json=connectionId,proto3" json:"connection_id,omitempty"`
- Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
-}
-
-func (x *OnTextMessageRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *OnTextMessageRequest) GetConnectionId() string {
- if x != nil {
- return x.ConnectionId
- }
- return ""
-}
-
-func (x *OnTextMessageRequest) GetMessage() string {
- if x != nil {
- return x.Message
- }
- return ""
-}
-
-type OnTextMessageResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-}
-
-func (x *OnTextMessageResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-type OnBinaryMessageRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- ConnectionId string `protobuf:"bytes,1,opt,name=connection_id,json=connectionId,proto3" json:"connection_id,omitempty"`
- Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
-}
-
-func (x *OnBinaryMessageRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *OnBinaryMessageRequest) GetConnectionId() string {
- if x != nil {
- return x.ConnectionId
- }
- return ""
-}
-
-func (x *OnBinaryMessageRequest) GetData() []byte {
- if x != nil {
- return x.Data
- }
- return nil
-}
-
-type OnBinaryMessageResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-}
-
-func (x *OnBinaryMessageResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-type OnErrorRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- ConnectionId string `protobuf:"bytes,1,opt,name=connection_id,json=connectionId,proto3" json:"connection_id,omitempty"`
- Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"`
-}
-
-func (x *OnErrorRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *OnErrorRequest) GetConnectionId() string {
- if x != nil {
- return x.ConnectionId
- }
- return ""
-}
-
-func (x *OnErrorRequest) GetError() string {
- if x != nil {
- return x.Error
- }
- return ""
-}
-
-type OnErrorResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-}
-
-func (x *OnErrorResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-type OnCloseRequest struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-
- ConnectionId string `protobuf:"bytes,1,opt,name=connection_id,json=connectionId,proto3" json:"connection_id,omitempty"`
- Code int32 `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"`
- Reason string `protobuf:"bytes,3,opt,name=reason,proto3" json:"reason,omitempty"`
-}
-
-func (x *OnCloseRequest) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-func (x *OnCloseRequest) GetConnectionId() string {
- if x != nil {
- return x.ConnectionId
- }
- return ""
-}
-
-func (x *OnCloseRequest) GetCode() int32 {
- if x != nil {
- return x.Code
- }
- return 0
-}
-
-func (x *OnCloseRequest) GetReason() string {
- if x != nil {
- return x.Reason
- }
- return ""
-}
-
-type OnCloseResponse struct {
- state protoimpl.MessageState
- sizeCache protoimpl.SizeCache
- unknownFields protoimpl.UnknownFields
-}
-
-func (x *OnCloseResponse) ProtoReflect() protoreflect.Message {
- panic(`not implemented`)
-}
-
-// go:plugin type=plugin version=1
-type MetadataAgent interface {
- // Artist metadata methods
- GetArtistMBID(context.Context, *ArtistMBIDRequest) (*ArtistMBIDResponse, error)
- GetArtistURL(context.Context, *ArtistURLRequest) (*ArtistURLResponse, error)
- GetArtistBiography(context.Context, *ArtistBiographyRequest) (*ArtistBiographyResponse, error)
- GetSimilarArtists(context.Context, *ArtistSimilarRequest) (*ArtistSimilarResponse, error)
- GetArtistImages(context.Context, *ArtistImageRequest) (*ArtistImageResponse, error)
- GetArtistTopSongs(context.Context, *ArtistTopSongsRequest) (*ArtistTopSongsResponse, error)
- // Album metadata methods
- GetAlbumInfo(context.Context, *AlbumInfoRequest) (*AlbumInfoResponse, error)
- GetAlbumImages(context.Context, *AlbumImagesRequest) (*AlbumImagesResponse, error)
-}
-
-// go:plugin type=plugin version=1
-type Scrobbler interface {
- IsAuthorized(context.Context, *ScrobblerIsAuthorizedRequest) (*ScrobblerIsAuthorizedResponse, error)
- NowPlaying(context.Context, *ScrobblerNowPlayingRequest) (*ScrobblerNowPlayingResponse, error)
- Scrobble(context.Context, *ScrobblerScrobbleRequest) (*ScrobblerScrobbleResponse, error)
-}
-
-// go:plugin type=plugin version=1
-type SchedulerCallback interface {
- OnSchedulerCallback(context.Context, *SchedulerCallbackRequest) (*SchedulerCallbackResponse, error)
-}
-
-// go:plugin type=plugin version=1
-type LifecycleManagement interface {
- OnInit(context.Context, *InitRequest) (*InitResponse, error)
-}
-
-// go:plugin type=plugin version=1
-type WebSocketCallback interface {
- // Called when a text message is received
- OnTextMessage(context.Context, *OnTextMessageRequest) (*OnTextMessageResponse, error)
- // Called when a binary message is received
- OnBinaryMessage(context.Context, *OnBinaryMessageRequest) (*OnBinaryMessageResponse, error)
- // Called when an error occurs
- OnError(context.Context, *OnErrorRequest) (*OnErrorResponse, error)
- // Called when the connection is closed
- OnClose(context.Context, *OnCloseRequest) (*OnCloseResponse, error)
-}
diff --git a/plugins/api/api.proto b/plugins/api/api.proto
deleted file mode 100644
index 7929ff9e6..000000000
--- a/plugins/api/api.proto
+++ /dev/null
@@ -1,246 +0,0 @@
-syntax = "proto3";
-
-package api;
-
-option go_package = "github.com/navidrome/navidrome/plugins/api;api";
-
-// go:plugin type=plugin version=1
-service MetadataAgent {
- // Artist metadata methods
- rpc GetArtistMBID(ArtistMBIDRequest) returns (ArtistMBIDResponse);
- rpc GetArtistURL(ArtistURLRequest) returns (ArtistURLResponse);
- rpc GetArtistBiography(ArtistBiographyRequest) returns (ArtistBiographyResponse);
- rpc GetSimilarArtists(ArtistSimilarRequest) returns (ArtistSimilarResponse);
- rpc GetArtistImages(ArtistImageRequest) returns (ArtistImageResponse);
- rpc GetArtistTopSongs(ArtistTopSongsRequest) returns (ArtistTopSongsResponse);
-
- // Album metadata methods
- rpc GetAlbumInfo(AlbumInfoRequest) returns (AlbumInfoResponse);
- rpc GetAlbumImages(AlbumImagesRequest) returns (AlbumImagesResponse);
-}
-
-message ArtistMBIDRequest {
- string id = 1;
- string name = 2;
-}
-
-message ArtistMBIDResponse {
- string mbid = 1;
-}
-
-message ArtistURLRequest {
- string id = 1;
- string name = 2;
- string mbid = 3;
-}
-
-message ArtistURLResponse {
- string url = 1;
-}
-
-message ArtistBiographyRequest {
- string id = 1;
- string name = 2;
- string mbid = 3;
-}
-
-message ArtistBiographyResponse {
- string biography = 1;
-}
-
-message ArtistSimilarRequest {
- string id = 1;
- string name = 2;
- string mbid = 3;
- int32 limit = 4;
-}
-
-message Artist {
- string name = 1;
- string mbid = 2;
-}
-
-message ArtistSimilarResponse {
- repeated Artist artists = 1;
-}
-
-message ArtistImageRequest {
- string id = 1;
- string name = 2;
- string mbid = 3;
-}
-
-message ExternalImage {
- string url = 1;
- int32 size = 2;
-}
-
-message ArtistImageResponse {
- repeated ExternalImage images = 1;
-}
-
-message ArtistTopSongsRequest {
- string id = 1;
- string artistName = 2;
- string mbid = 3;
- int32 count = 4;
-}
-
-message Song {
- string name = 1;
- string mbid = 2;
-}
-
-message ArtistTopSongsResponse {
- repeated Song songs = 1;
-}
-
-message AlbumInfoRequest {
- string name = 1;
- string artist = 2;
- string mbid = 3;
-}
-
-message AlbumInfo {
- string name = 1;
- string mbid = 2;
- string description = 3;
- string url = 4;
-}
-
-message AlbumInfoResponse {
- AlbumInfo info = 1;
-}
-
-message AlbumImagesRequest {
- string name = 1;
- string artist = 2;
- string mbid = 3;
-}
-
-message AlbumImagesResponse {
- repeated ExternalImage images = 1;
-}
-
-// go:plugin type=plugin version=1
-service Scrobbler {
- rpc IsAuthorized(ScrobblerIsAuthorizedRequest) returns (ScrobblerIsAuthorizedResponse);
- rpc NowPlaying(ScrobblerNowPlayingRequest) returns (ScrobblerNowPlayingResponse);
- rpc Scrobble(ScrobblerScrobbleRequest) returns (ScrobblerScrobbleResponse);
-}
-
-message ScrobblerIsAuthorizedRequest {
- string user_id = 1;
- string username = 2;
-}
-
-message ScrobblerIsAuthorizedResponse {
- bool authorized = 1;
- string error = 2;
-}
-
-message TrackInfo {
- string id = 1;
- string mbid = 2;
- string name = 3;
- string album = 4;
- string album_mbid = 5;
- repeated Artist artists = 6;
- repeated Artist album_artists = 7;
- int32 length = 8; // seconds
- int32 position = 9; // seconds
-}
-
-message ScrobblerNowPlayingRequest {
- string user_id = 1;
- string username = 2;
- TrackInfo track = 3;
- int64 timestamp = 4;
-}
-
-message ScrobblerNowPlayingResponse {
- string error = 1;
-}
-
-message ScrobblerScrobbleRequest {
- string user_id = 1;
- string username = 2;
- TrackInfo track = 3;
- int64 timestamp = 4;
-}
-
-message ScrobblerScrobbleResponse {
- string error = 1;
-}
-
-// go:plugin type=plugin version=1
-service SchedulerCallback {
- rpc OnSchedulerCallback(SchedulerCallbackRequest) returns (SchedulerCallbackResponse);
-}
-
-message SchedulerCallbackRequest {
- string schedule_id = 1; // ID of the scheduled job that triggered this callback
- bytes payload = 2; // The data passed when the job was scheduled
- bool is_recurring = 3; // Whether this is from a recurring schedule (cron job)
-}
-
-message SchedulerCallbackResponse {
- string error = 1; // Error message if the callback failed
-}
-
-// go:plugin type=plugin version=1
-service LifecycleManagement {
- rpc OnInit(InitRequest) returns (InitResponse);
-}
-
-message InitRequest {
- map config = 1; // Configuration specific to this plugin
-}
-
-message InitResponse {
- string error = 1; // Error message if initialization failed
-}
-
-// go:plugin type=plugin version=1
-service WebSocketCallback {
- // Called when a text message is received
- rpc OnTextMessage(OnTextMessageRequest) returns (OnTextMessageResponse);
-
- // Called when a binary message is received
- rpc OnBinaryMessage(OnBinaryMessageRequest) returns (OnBinaryMessageResponse);
-
- // Called when an error occurs
- rpc OnError(OnErrorRequest) returns (OnErrorResponse);
-
- // Called when the connection is closed
- rpc OnClose(OnCloseRequest) returns (OnCloseResponse);
-}
-
-message OnTextMessageRequest {
- string connection_id = 1;
- string message = 2;
-}
-
-message OnTextMessageResponse {}
-
-message OnBinaryMessageRequest {
- string connection_id = 1;
- bytes data = 2;
-}
-
-message OnBinaryMessageResponse {}
-
-message OnErrorRequest {
- string connection_id = 1;
- string error = 2;
-}
-
-message OnErrorResponse {}
-
-message OnCloseRequest {
- string connection_id = 1;
- int32 code = 2;
- string reason = 3;
-}
-
-message OnCloseResponse {}
\ No newline at end of file
diff --git a/plugins/api/api_host.pb.go b/plugins/api/api_host.pb.go
deleted file mode 100644
index 55e648c6c..000000000
--- a/plugins/api/api_host.pb.go
+++ /dev/null
@@ -1,1688 +0,0 @@
-//go:build !wasip1
-
-// Code generated by protoc-gen-go-plugin. DO NOT EDIT.
-// versions:
-// protoc-gen-go-plugin v0.1.0
-// protoc v5.29.3
-// source: api/api.proto
-
-package api
-
-import (
- context "context"
- errors "errors"
- fmt "fmt"
- wazero "github.com/tetratelabs/wazero"
- api "github.com/tetratelabs/wazero/api"
- sys "github.com/tetratelabs/wazero/sys"
- os "os"
-)
-
-const MetadataAgentPluginAPIVersion = 1
-
-type MetadataAgentPlugin struct {
- newRuntime func(context.Context) (wazero.Runtime, error)
- moduleConfig wazero.ModuleConfig
-}
-
-func NewMetadataAgentPlugin(ctx context.Context, opts ...wazeroConfigOption) (*MetadataAgentPlugin, error) {
- o := &WazeroConfig{
- newRuntime: DefaultWazeroRuntime(),
- moduleConfig: wazero.NewModuleConfig().WithStartFunctions("_initialize"),
- }
-
- for _, opt := range opts {
- opt(o)
- }
-
- return &MetadataAgentPlugin{
- newRuntime: o.newRuntime,
- moduleConfig: o.moduleConfig,
- }, nil
-}
-
-type metadataAgent interface {
- Close(ctx context.Context) error
- MetadataAgent
-}
-
-func (p *MetadataAgentPlugin) Load(ctx context.Context, pluginPath string) (metadataAgent, error) {
- b, err := os.ReadFile(pluginPath)
- if err != nil {
- return nil, err
- }
-
- // Create a new runtime so that multiple modules will not conflict
- r, err := p.newRuntime(ctx)
- if err != nil {
- return nil, err
- }
-
- // Compile the WebAssembly module using the default configuration.
- code, err := r.CompileModule(ctx, b)
- if err != nil {
- return nil, err
- }
-
- // InstantiateModule runs the "_start" function, WASI's "main".
- module, err := r.InstantiateModule(ctx, code, p.moduleConfig)
- if err != nil {
- // Note: Most compilers do not exit the module after running "_start",
- // unless there was an Error. This allows you to call exported functions.
- if exitErr, ok := err.(*sys.ExitError); ok && exitErr.ExitCode() != 0 {
- return nil, fmt.Errorf("unexpected exit_code: %d", exitErr.ExitCode())
- } else if !ok {
- return nil, err
- }
- }
-
- // Compare API versions with the loading plugin
- apiVersion := module.ExportedFunction("metadata_agent_api_version")
- if apiVersion == nil {
- return nil, errors.New("metadata_agent_api_version is not exported")
- }
- results, err := apiVersion.Call(ctx)
- if err != nil {
- return nil, err
- } else if len(results) != 1 {
- return nil, errors.New("invalid metadata_agent_api_version signature")
- }
- if results[0] != MetadataAgentPluginAPIVersion {
- return nil, fmt.Errorf("API version mismatch, host: %d, plugin: %d", MetadataAgentPluginAPIVersion, results[0])
- }
-
- getartistmbid := module.ExportedFunction("metadata_agent_get_artist_mbid")
- if getartistmbid == nil {
- return nil, errors.New("metadata_agent_get_artist_mbid is not exported")
- }
- getartisturl := module.ExportedFunction("metadata_agent_get_artist_url")
- if getartisturl == nil {
- return nil, errors.New("metadata_agent_get_artist_url is not exported")
- }
- getartistbiography := module.ExportedFunction("metadata_agent_get_artist_biography")
- if getartistbiography == nil {
- return nil, errors.New("metadata_agent_get_artist_biography is not exported")
- }
- getsimilarartists := module.ExportedFunction("metadata_agent_get_similar_artists")
- if getsimilarartists == nil {
- return nil, errors.New("metadata_agent_get_similar_artists is not exported")
- }
- getartistimages := module.ExportedFunction("metadata_agent_get_artist_images")
- if getartistimages == nil {
- return nil, errors.New("metadata_agent_get_artist_images is not exported")
- }
- getartisttopsongs := module.ExportedFunction("metadata_agent_get_artist_top_songs")
- if getartisttopsongs == nil {
- return nil, errors.New("metadata_agent_get_artist_top_songs is not exported")
- }
- getalbuminfo := module.ExportedFunction("metadata_agent_get_album_info")
- if getalbuminfo == nil {
- return nil, errors.New("metadata_agent_get_album_info is not exported")
- }
- getalbumimages := module.ExportedFunction("metadata_agent_get_album_images")
- if getalbumimages == nil {
- return nil, errors.New("metadata_agent_get_album_images is not exported")
- }
-
- malloc := module.ExportedFunction("malloc")
- if malloc == nil {
- return nil, errors.New("malloc is not exported")
- }
-
- free := module.ExportedFunction("free")
- if free == nil {
- return nil, errors.New("free is not exported")
- }
- return &metadataAgentPlugin{
- runtime: r,
- module: module,
- malloc: malloc,
- free: free,
- getartistmbid: getartistmbid,
- getartisturl: getartisturl,
- getartistbiography: getartistbiography,
- getsimilarartists: getsimilarartists,
- getartistimages: getartistimages,
- getartisttopsongs: getartisttopsongs,
- getalbuminfo: getalbuminfo,
- getalbumimages: getalbumimages,
- }, nil
-}
-
-func (p *metadataAgentPlugin) Close(ctx context.Context) (err error) {
- if r := p.runtime; r != nil {
- r.Close(ctx)
- }
- return
-}
-
-type metadataAgentPlugin struct {
- runtime wazero.Runtime
- module api.Module
- malloc api.Function
- free api.Function
- getartistmbid api.Function
- getartisturl api.Function
- getartistbiography api.Function
- getsimilarartists api.Function
- getartistimages api.Function
- getartisttopsongs api.Function
- getalbuminfo api.Function
- getalbumimages api.Function
-}
-
-func (p *metadataAgentPlugin) GetArtistMBID(ctx context.Context, request *ArtistMBIDRequest) (*ArtistMBIDResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getartistmbid.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ArtistMBIDResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *metadataAgentPlugin) GetArtistURL(ctx context.Context, request *ArtistURLRequest) (*ArtistURLResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getartisturl.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ArtistURLResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *metadataAgentPlugin) GetArtistBiography(ctx context.Context, request *ArtistBiographyRequest) (*ArtistBiographyResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getartistbiography.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ArtistBiographyResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *metadataAgentPlugin) GetSimilarArtists(ctx context.Context, request *ArtistSimilarRequest) (*ArtistSimilarResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getsimilarartists.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ArtistSimilarResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *metadataAgentPlugin) GetArtistImages(ctx context.Context, request *ArtistImageRequest) (*ArtistImageResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getartistimages.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ArtistImageResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *metadataAgentPlugin) GetArtistTopSongs(ctx context.Context, request *ArtistTopSongsRequest) (*ArtistTopSongsResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getartisttopsongs.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ArtistTopSongsResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *metadataAgentPlugin) GetAlbumInfo(ctx context.Context, request *AlbumInfoRequest) (*AlbumInfoResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getalbuminfo.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(AlbumInfoResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *metadataAgentPlugin) GetAlbumImages(ctx context.Context, request *AlbumImagesRequest) (*AlbumImagesResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.getalbumimages.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(AlbumImagesResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-
-const ScrobblerPluginAPIVersion = 1
-
-type ScrobblerPlugin struct {
- newRuntime func(context.Context) (wazero.Runtime, error)
- moduleConfig wazero.ModuleConfig
-}
-
-func NewScrobblerPlugin(ctx context.Context, opts ...wazeroConfigOption) (*ScrobblerPlugin, error) {
- o := &WazeroConfig{
- newRuntime: DefaultWazeroRuntime(),
- moduleConfig: wazero.NewModuleConfig().WithStartFunctions("_initialize"),
- }
-
- for _, opt := range opts {
- opt(o)
- }
-
- return &ScrobblerPlugin{
- newRuntime: o.newRuntime,
- moduleConfig: o.moduleConfig,
- }, nil
-}
-
-type scrobbler interface {
- Close(ctx context.Context) error
- Scrobbler
-}
-
-func (p *ScrobblerPlugin) Load(ctx context.Context, pluginPath string) (scrobbler, error) {
- b, err := os.ReadFile(pluginPath)
- if err != nil {
- return nil, err
- }
-
- // Create a new runtime so that multiple modules will not conflict
- r, err := p.newRuntime(ctx)
- if err != nil {
- return nil, err
- }
-
- // Compile the WebAssembly module using the default configuration.
- code, err := r.CompileModule(ctx, b)
- if err != nil {
- return nil, err
- }
-
- // InstantiateModule runs the "_start" function, WASI's "main".
- module, err := r.InstantiateModule(ctx, code, p.moduleConfig)
- if err != nil {
- // Note: Most compilers do not exit the module after running "_start",
- // unless there was an Error. This allows you to call exported functions.
- if exitErr, ok := err.(*sys.ExitError); ok && exitErr.ExitCode() != 0 {
- return nil, fmt.Errorf("unexpected exit_code: %d", exitErr.ExitCode())
- } else if !ok {
- return nil, err
- }
- }
-
- // Compare API versions with the loading plugin
- apiVersion := module.ExportedFunction("scrobbler_api_version")
- if apiVersion == nil {
- return nil, errors.New("scrobbler_api_version is not exported")
- }
- results, err := apiVersion.Call(ctx)
- if err != nil {
- return nil, err
- } else if len(results) != 1 {
- return nil, errors.New("invalid scrobbler_api_version signature")
- }
- if results[0] != ScrobblerPluginAPIVersion {
- return nil, fmt.Errorf("API version mismatch, host: %d, plugin: %d", ScrobblerPluginAPIVersion, results[0])
- }
-
- isauthorized := module.ExportedFunction("scrobbler_is_authorized")
- if isauthorized == nil {
- return nil, errors.New("scrobbler_is_authorized is not exported")
- }
- nowplaying := module.ExportedFunction("scrobbler_now_playing")
- if nowplaying == nil {
- return nil, errors.New("scrobbler_now_playing is not exported")
- }
- scrobble := module.ExportedFunction("scrobbler_scrobble")
- if scrobble == nil {
- return nil, errors.New("scrobbler_scrobble is not exported")
- }
-
- malloc := module.ExportedFunction("malloc")
- if malloc == nil {
- return nil, errors.New("malloc is not exported")
- }
-
- free := module.ExportedFunction("free")
- if free == nil {
- return nil, errors.New("free is not exported")
- }
- return &scrobblerPlugin{
- runtime: r,
- module: module,
- malloc: malloc,
- free: free,
- isauthorized: isauthorized,
- nowplaying: nowplaying,
- scrobble: scrobble,
- }, nil
-}
-
-func (p *scrobblerPlugin) Close(ctx context.Context) (err error) {
- if r := p.runtime; r != nil {
- r.Close(ctx)
- }
- return
-}
-
-type scrobblerPlugin struct {
- runtime wazero.Runtime
- module api.Module
- malloc api.Function
- free api.Function
- isauthorized api.Function
- nowplaying api.Function
- scrobble api.Function
-}
-
-func (p *scrobblerPlugin) IsAuthorized(ctx context.Context, request *ScrobblerIsAuthorizedRequest) (*ScrobblerIsAuthorizedResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.isauthorized.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ScrobblerIsAuthorizedResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *scrobblerPlugin) NowPlaying(ctx context.Context, request *ScrobblerNowPlayingRequest) (*ScrobblerNowPlayingResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.nowplaying.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ScrobblerNowPlayingResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *scrobblerPlugin) Scrobble(ctx context.Context, request *ScrobblerScrobbleRequest) (*ScrobblerScrobbleResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.scrobble.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(ScrobblerScrobbleResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-
-const SchedulerCallbackPluginAPIVersion = 1
-
-type SchedulerCallbackPlugin struct {
- newRuntime func(context.Context) (wazero.Runtime, error)
- moduleConfig wazero.ModuleConfig
-}
-
-func NewSchedulerCallbackPlugin(ctx context.Context, opts ...wazeroConfigOption) (*SchedulerCallbackPlugin, error) {
- o := &WazeroConfig{
- newRuntime: DefaultWazeroRuntime(),
- moduleConfig: wazero.NewModuleConfig().WithStartFunctions("_initialize"),
- }
-
- for _, opt := range opts {
- opt(o)
- }
-
- return &SchedulerCallbackPlugin{
- newRuntime: o.newRuntime,
- moduleConfig: o.moduleConfig,
- }, nil
-}
-
-type schedulerCallback interface {
- Close(ctx context.Context) error
- SchedulerCallback
-}
-
-func (p *SchedulerCallbackPlugin) Load(ctx context.Context, pluginPath string) (schedulerCallback, error) {
- b, err := os.ReadFile(pluginPath)
- if err != nil {
- return nil, err
- }
-
- // Create a new runtime so that multiple modules will not conflict
- r, err := p.newRuntime(ctx)
- if err != nil {
- return nil, err
- }
-
- // Compile the WebAssembly module using the default configuration.
- code, err := r.CompileModule(ctx, b)
- if err != nil {
- return nil, err
- }
-
- // InstantiateModule runs the "_start" function, WASI's "main".
- module, err := r.InstantiateModule(ctx, code, p.moduleConfig)
- if err != nil {
- // Note: Most compilers do not exit the module after running "_start",
- // unless there was an Error. This allows you to call exported functions.
- if exitErr, ok := err.(*sys.ExitError); ok && exitErr.ExitCode() != 0 {
- return nil, fmt.Errorf("unexpected exit_code: %d", exitErr.ExitCode())
- } else if !ok {
- return nil, err
- }
- }
-
- // Compare API versions with the loading plugin
- apiVersion := module.ExportedFunction("scheduler_callback_api_version")
- if apiVersion == nil {
- return nil, errors.New("scheduler_callback_api_version is not exported")
- }
- results, err := apiVersion.Call(ctx)
- if err != nil {
- return nil, err
- } else if len(results) != 1 {
- return nil, errors.New("invalid scheduler_callback_api_version signature")
- }
- if results[0] != SchedulerCallbackPluginAPIVersion {
- return nil, fmt.Errorf("API version mismatch, host: %d, plugin: %d", SchedulerCallbackPluginAPIVersion, results[0])
- }
-
- onschedulercallback := module.ExportedFunction("scheduler_callback_on_scheduler_callback")
- if onschedulercallback == nil {
- return nil, errors.New("scheduler_callback_on_scheduler_callback is not exported")
- }
-
- malloc := module.ExportedFunction("malloc")
- if malloc == nil {
- return nil, errors.New("malloc is not exported")
- }
-
- free := module.ExportedFunction("free")
- if free == nil {
- return nil, errors.New("free is not exported")
- }
- return &schedulerCallbackPlugin{
- runtime: r,
- module: module,
- malloc: malloc,
- free: free,
- onschedulercallback: onschedulercallback,
- }, nil
-}
-
-func (p *schedulerCallbackPlugin) Close(ctx context.Context) (err error) {
- if r := p.runtime; r != nil {
- r.Close(ctx)
- }
- return
-}
-
-type schedulerCallbackPlugin struct {
- runtime wazero.Runtime
- module api.Module
- malloc api.Function
- free api.Function
- onschedulercallback api.Function
-}
-
-func (p *schedulerCallbackPlugin) OnSchedulerCallback(ctx context.Context, request *SchedulerCallbackRequest) (*SchedulerCallbackResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.onschedulercallback.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(SchedulerCallbackResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-
-const LifecycleManagementPluginAPIVersion = 1
-
-type LifecycleManagementPlugin struct {
- newRuntime func(context.Context) (wazero.Runtime, error)
- moduleConfig wazero.ModuleConfig
-}
-
-func NewLifecycleManagementPlugin(ctx context.Context, opts ...wazeroConfigOption) (*LifecycleManagementPlugin, error) {
- o := &WazeroConfig{
- newRuntime: DefaultWazeroRuntime(),
- moduleConfig: wazero.NewModuleConfig().WithStartFunctions("_initialize"),
- }
-
- for _, opt := range opts {
- opt(o)
- }
-
- return &LifecycleManagementPlugin{
- newRuntime: o.newRuntime,
- moduleConfig: o.moduleConfig,
- }, nil
-}
-
-type lifecycleManagement interface {
- Close(ctx context.Context) error
- LifecycleManagement
-}
-
-func (p *LifecycleManagementPlugin) Load(ctx context.Context, pluginPath string) (lifecycleManagement, error) {
- b, err := os.ReadFile(pluginPath)
- if err != nil {
- return nil, err
- }
-
- // Create a new runtime so that multiple modules will not conflict
- r, err := p.newRuntime(ctx)
- if err != nil {
- return nil, err
- }
-
- // Compile the WebAssembly module using the default configuration.
- code, err := r.CompileModule(ctx, b)
- if err != nil {
- return nil, err
- }
-
- // InstantiateModule runs the "_start" function, WASI's "main".
- module, err := r.InstantiateModule(ctx, code, p.moduleConfig)
- if err != nil {
- // Note: Most compilers do not exit the module after running "_start",
- // unless there was an Error. This allows you to call exported functions.
- if exitErr, ok := err.(*sys.ExitError); ok && exitErr.ExitCode() != 0 {
- return nil, fmt.Errorf("unexpected exit_code: %d", exitErr.ExitCode())
- } else if !ok {
- return nil, err
- }
- }
-
- // Compare API versions with the loading plugin
- apiVersion := module.ExportedFunction("lifecycle_management_api_version")
- if apiVersion == nil {
- return nil, errors.New("lifecycle_management_api_version is not exported")
- }
- results, err := apiVersion.Call(ctx)
- if err != nil {
- return nil, err
- } else if len(results) != 1 {
- return nil, errors.New("invalid lifecycle_management_api_version signature")
- }
- if results[0] != LifecycleManagementPluginAPIVersion {
- return nil, fmt.Errorf("API version mismatch, host: %d, plugin: %d", LifecycleManagementPluginAPIVersion, results[0])
- }
-
- oninit := module.ExportedFunction("lifecycle_management_on_init")
- if oninit == nil {
- return nil, errors.New("lifecycle_management_on_init is not exported")
- }
-
- malloc := module.ExportedFunction("malloc")
- if malloc == nil {
- return nil, errors.New("malloc is not exported")
- }
-
- free := module.ExportedFunction("free")
- if free == nil {
- return nil, errors.New("free is not exported")
- }
- return &lifecycleManagementPlugin{
- runtime: r,
- module: module,
- malloc: malloc,
- free: free,
- oninit: oninit,
- }, nil
-}
-
-func (p *lifecycleManagementPlugin) Close(ctx context.Context) (err error) {
- if r := p.runtime; r != nil {
- r.Close(ctx)
- }
- return
-}
-
-type lifecycleManagementPlugin struct {
- runtime wazero.Runtime
- module api.Module
- malloc api.Function
- free api.Function
- oninit api.Function
-}
-
-func (p *lifecycleManagementPlugin) OnInit(ctx context.Context, request *InitRequest) (*InitResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.oninit.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(InitResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-
-const WebSocketCallbackPluginAPIVersion = 1
-
-type WebSocketCallbackPlugin struct {
- newRuntime func(context.Context) (wazero.Runtime, error)
- moduleConfig wazero.ModuleConfig
-}
-
-func NewWebSocketCallbackPlugin(ctx context.Context, opts ...wazeroConfigOption) (*WebSocketCallbackPlugin, error) {
- o := &WazeroConfig{
- newRuntime: DefaultWazeroRuntime(),
- moduleConfig: wazero.NewModuleConfig().WithStartFunctions("_initialize"),
- }
-
- for _, opt := range opts {
- opt(o)
- }
-
- return &WebSocketCallbackPlugin{
- newRuntime: o.newRuntime,
- moduleConfig: o.moduleConfig,
- }, nil
-}
-
-type webSocketCallback interface {
- Close(ctx context.Context) error
- WebSocketCallback
-}
-
-func (p *WebSocketCallbackPlugin) Load(ctx context.Context, pluginPath string) (webSocketCallback, error) {
- b, err := os.ReadFile(pluginPath)
- if err != nil {
- return nil, err
- }
-
- // Create a new runtime so that multiple modules will not conflict
- r, err := p.newRuntime(ctx)
- if err != nil {
- return nil, err
- }
-
- // Compile the WebAssembly module using the default configuration.
- code, err := r.CompileModule(ctx, b)
- if err != nil {
- return nil, err
- }
-
- // InstantiateModule runs the "_start" function, WASI's "main".
- module, err := r.InstantiateModule(ctx, code, p.moduleConfig)
- if err != nil {
- // Note: Most compilers do not exit the module after running "_start",
- // unless there was an Error. This allows you to call exported functions.
- if exitErr, ok := err.(*sys.ExitError); ok && exitErr.ExitCode() != 0 {
- return nil, fmt.Errorf("unexpected exit_code: %d", exitErr.ExitCode())
- } else if !ok {
- return nil, err
- }
- }
-
- // Compare API versions with the loading plugin
- apiVersion := module.ExportedFunction("web_socket_callback_api_version")
- if apiVersion == nil {
- return nil, errors.New("web_socket_callback_api_version is not exported")
- }
- results, err := apiVersion.Call(ctx)
- if err != nil {
- return nil, err
- } else if len(results) != 1 {
- return nil, errors.New("invalid web_socket_callback_api_version signature")
- }
- if results[0] != WebSocketCallbackPluginAPIVersion {
- return nil, fmt.Errorf("API version mismatch, host: %d, plugin: %d", WebSocketCallbackPluginAPIVersion, results[0])
- }
-
- ontextmessage := module.ExportedFunction("web_socket_callback_on_text_message")
- if ontextmessage == nil {
- return nil, errors.New("web_socket_callback_on_text_message is not exported")
- }
- onbinarymessage := module.ExportedFunction("web_socket_callback_on_binary_message")
- if onbinarymessage == nil {
- return nil, errors.New("web_socket_callback_on_binary_message is not exported")
- }
- onerror := module.ExportedFunction("web_socket_callback_on_error")
- if onerror == nil {
- return nil, errors.New("web_socket_callback_on_error is not exported")
- }
- onclose := module.ExportedFunction("web_socket_callback_on_close")
- if onclose == nil {
- return nil, errors.New("web_socket_callback_on_close is not exported")
- }
-
- malloc := module.ExportedFunction("malloc")
- if malloc == nil {
- return nil, errors.New("malloc is not exported")
- }
-
- free := module.ExportedFunction("free")
- if free == nil {
- return nil, errors.New("free is not exported")
- }
- return &webSocketCallbackPlugin{
- runtime: r,
- module: module,
- malloc: malloc,
- free: free,
- ontextmessage: ontextmessage,
- onbinarymessage: onbinarymessage,
- onerror: onerror,
- onclose: onclose,
- }, nil
-}
-
-func (p *webSocketCallbackPlugin) Close(ctx context.Context) (err error) {
- if r := p.runtime; r != nil {
- r.Close(ctx)
- }
- return
-}
-
-type webSocketCallbackPlugin struct {
- runtime wazero.Runtime
- module api.Module
- malloc api.Function
- free api.Function
- ontextmessage api.Function
- onbinarymessage api.Function
- onerror api.Function
- onclose api.Function
-}
-
-func (p *webSocketCallbackPlugin) OnTextMessage(ctx context.Context, request *OnTextMessageRequest) (*OnTextMessageResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.ontextmessage.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(OnTextMessageResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *webSocketCallbackPlugin) OnBinaryMessage(ctx context.Context, request *OnBinaryMessageRequest) (*OnBinaryMessageResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.onbinarymessage.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(OnBinaryMessageResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *webSocketCallbackPlugin) OnError(ctx context.Context, request *OnErrorRequest) (*OnErrorResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.onerror.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(OnErrorResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
-func (p *webSocketCallbackPlugin) OnClose(ctx context.Context, request *OnCloseRequest) (*OnCloseResponse, error) {
- data, err := request.MarshalVT()
- if err != nil {
- return nil, err
- }
- dataSize := uint64(len(data))
-
- var dataPtr uint64
- // If the input data is not empty, we must allocate the in-Wasm memory to store it, and pass to the plugin.
- if dataSize != 0 {
- results, err := p.malloc.Call(ctx, dataSize)
- if err != nil {
- return nil, err
- }
- dataPtr = results[0]
- // This pointer is managed by the Wasm module, which is unaware of external usage.
- // So, we have to free it when finished
- defer p.free.Call(ctx, dataPtr)
-
- // The pointer is a linear memory offset, which is where we write the name.
- if !p.module.Memory().Write(uint32(dataPtr), data) {
- return nil, fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d", dataPtr, dataSize, p.module.Memory().Size())
- }
- }
-
- ptrSize, err := p.onclose.Call(ctx, dataPtr, dataSize)
- if err != nil {
- return nil, err
- }
-
- resPtr := uint32(ptrSize[0] >> 32)
- resSize := uint32(ptrSize[0])
- var isErrResponse bool
- if (resSize & (1 << 31)) > 0 {
- isErrResponse = true
- resSize &^= (1 << 31)
- }
-
- // We don't need the memory after deserialization: make sure it is freed.
- if resPtr != 0 {
- defer p.free.Call(ctx, uint64(resPtr))
- }
-
- // The pointer is a linear memory offset, which is where we write the name.
- bytes, ok := p.module.Memory().Read(resPtr, resSize)
- if !ok {
- return nil, fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
- resPtr, resSize, p.module.Memory().Size())
- }
-
- if isErrResponse {
- return nil, errors.New(string(bytes))
- }
-
- response := new(OnCloseResponse)
- if err = response.UnmarshalVT(bytes); err != nil {
- return nil, err
- }
-
- return response, nil
-}
diff --git a/plugins/api/api_options.pb.go b/plugins/api/api_options.pb.go
deleted file mode 100644
index 430bf0a5c..000000000
--- a/plugins/api/api_options.pb.go
+++ /dev/null
@@ -1,47 +0,0 @@
-//go:build !wasip1
-
-// Code generated by protoc-gen-go-plugin. DO NOT EDIT.
-// versions:
-// protoc-gen-go-plugin v0.1.0
-// protoc v5.29.3
-// source: api/api.proto
-
-package api
-
-import (
- context "context"
- wazero "github.com/tetratelabs/wazero"
- wasi_snapshot_preview1 "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
-)
-
-type wazeroConfigOption func(plugin *WazeroConfig)
-
-type WazeroNewRuntime func(context.Context) (wazero.Runtime, error)
-
-type WazeroConfig struct {
- newRuntime func(context.Context) (wazero.Runtime, error)
- moduleConfig wazero.ModuleConfig
-}
-
-func WazeroRuntime(newRuntime WazeroNewRuntime) wazeroConfigOption {
- return func(h *WazeroConfig) {
- h.newRuntime = newRuntime
- }
-}
-
-func DefaultWazeroRuntime() WazeroNewRuntime {
- return func(ctx context.Context) (wazero.Runtime, error) {
- r := wazero.NewRuntime(ctx)
- if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil {
- return nil, err
- }
-
- return r, nil
- }
-}
-
-func WazeroModuleConfig(moduleConfig wazero.ModuleConfig) wazeroConfigOption {
- return func(h *WazeroConfig) {
- h.moduleConfig = moduleConfig
- }
-}
diff --git a/plugins/api/api_plugin.pb.go b/plugins/api/api_plugin.pb.go
deleted file mode 100644
index 0a022be9b..000000000
--- a/plugins/api/api_plugin.pb.go
+++ /dev/null
@@ -1,487 +0,0 @@
-//go:build wasip1
-
-// Code generated by protoc-gen-go-plugin. DO NOT EDIT.
-// versions:
-// protoc-gen-go-plugin v0.1.0
-// protoc v5.29.3
-// source: api/api.proto
-
-package api
-
-import (
- context "context"
- wasm "github.com/knqyf263/go-plugin/wasm"
-)
-
-const MetadataAgentPluginAPIVersion = 1
-
-//go:wasmexport metadata_agent_api_version
-func _metadata_agent_api_version() uint64 {
- return MetadataAgentPluginAPIVersion
-}
-
-var metadataAgent MetadataAgent
-
-func RegisterMetadataAgent(p MetadataAgent) {
- metadataAgent = p
-}
-
-//go:wasmexport metadata_agent_get_artist_mbid
-func _metadata_agent_get_artist_mbid(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ArtistMBIDRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetArtistMBID(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport metadata_agent_get_artist_url
-func _metadata_agent_get_artist_url(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ArtistURLRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetArtistURL(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport metadata_agent_get_artist_biography
-func _metadata_agent_get_artist_biography(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ArtistBiographyRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetArtistBiography(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport metadata_agent_get_similar_artists
-func _metadata_agent_get_similar_artists(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ArtistSimilarRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetSimilarArtists(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport metadata_agent_get_artist_images
-func _metadata_agent_get_artist_images(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ArtistImageRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetArtistImages(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport metadata_agent_get_artist_top_songs
-func _metadata_agent_get_artist_top_songs(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ArtistTopSongsRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetArtistTopSongs(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport metadata_agent_get_album_info
-func _metadata_agent_get_album_info(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(AlbumInfoRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetAlbumInfo(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport metadata_agent_get_album_images
-func _metadata_agent_get_album_images(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(AlbumImagesRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := metadataAgent.GetAlbumImages(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-const ScrobblerPluginAPIVersion = 1
-
-//go:wasmexport scrobbler_api_version
-func _scrobbler_api_version() uint64 {
- return ScrobblerPluginAPIVersion
-}
-
-var scrobbler Scrobbler
-
-func RegisterScrobbler(p Scrobbler) {
- scrobbler = p
-}
-
-//go:wasmexport scrobbler_is_authorized
-func _scrobbler_is_authorized(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ScrobblerIsAuthorizedRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := scrobbler.IsAuthorized(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport scrobbler_now_playing
-func _scrobbler_now_playing(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ScrobblerNowPlayingRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := scrobbler.NowPlaying(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport scrobbler_scrobble
-func _scrobbler_scrobble(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(ScrobblerScrobbleRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := scrobbler.Scrobble(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-const SchedulerCallbackPluginAPIVersion = 1
-
-//go:wasmexport scheduler_callback_api_version
-func _scheduler_callback_api_version() uint64 {
- return SchedulerCallbackPluginAPIVersion
-}
-
-var schedulerCallback SchedulerCallback
-
-func RegisterSchedulerCallback(p SchedulerCallback) {
- schedulerCallback = p
-}
-
-//go:wasmexport scheduler_callback_on_scheduler_callback
-func _scheduler_callback_on_scheduler_callback(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(SchedulerCallbackRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := schedulerCallback.OnSchedulerCallback(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-const LifecycleManagementPluginAPIVersion = 1
-
-//go:wasmexport lifecycle_management_api_version
-func _lifecycle_management_api_version() uint64 {
- return LifecycleManagementPluginAPIVersion
-}
-
-var lifecycleManagement LifecycleManagement
-
-func RegisterLifecycleManagement(p LifecycleManagement) {
- lifecycleManagement = p
-}
-
-//go:wasmexport lifecycle_management_on_init
-func _lifecycle_management_on_init(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(InitRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := lifecycleManagement.OnInit(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-const WebSocketCallbackPluginAPIVersion = 1
-
-//go:wasmexport web_socket_callback_api_version
-func _web_socket_callback_api_version() uint64 {
- return WebSocketCallbackPluginAPIVersion
-}
-
-var webSocketCallback WebSocketCallback
-
-func RegisterWebSocketCallback(p WebSocketCallback) {
- webSocketCallback = p
-}
-
-//go:wasmexport web_socket_callback_on_text_message
-func _web_socket_callback_on_text_message(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(OnTextMessageRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := webSocketCallback.OnTextMessage(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport web_socket_callback_on_binary_message
-func _web_socket_callback_on_binary_message(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(OnBinaryMessageRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := webSocketCallback.OnBinaryMessage(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport web_socket_callback_on_error
-func _web_socket_callback_on_error(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(OnErrorRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := webSocketCallback.OnError(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
-
-//go:wasmexport web_socket_callback_on_close
-func _web_socket_callback_on_close(ptr, size uint32) uint64 {
- b := wasm.PtrToByte(ptr, size)
- req := new(OnCloseRequest)
- if err := req.UnmarshalVT(b); err != nil {
- return 0
- }
- response, err := webSocketCallback.OnClose(context.Background(), req)
- if err != nil {
- ptr, size = wasm.ByteToPtr([]byte(err.Error()))
- return (uint64(ptr) << uint64(32)) | uint64(size) |
- // Indicate that this is the error string by setting the 32-th bit, assuming that
- // no data exceeds 31-bit size (2 GiB).
- (1 << 31)
- }
-
- b, err = response.MarshalVT()
- if err != nil {
- return 0
- }
- ptr, size = wasm.ByteToPtr(b)
- return (uint64(ptr) << uint64(32)) | uint64(size)
-}
diff --git a/plugins/api/api_plugin_dev.go b/plugins/api/api_plugin_dev.go
deleted file mode 100644
index ed5a064b2..000000000
--- a/plugins/api/api_plugin_dev.go
+++ /dev/null
@@ -1,34 +0,0 @@
-//go:build !wasip1
-
-package api
-
-import "github.com/navidrome/navidrome/plugins/host/scheduler"
-
-// This file exists to provide stubs for the plugin registration functions when building for non-WASM targets.
-// This is useful for testing and development purposes, as it allows you to build and run your plugin code
-// without having to compile it to WASM.
-// In a real-world scenario, you would compile your plugin to WASM and use the generated registration functions.
-
-func RegisterMetadataAgent(MetadataAgent) {
- panic("not implemented")
-}
-
-func RegisterScrobbler(Scrobbler) {
- panic("not implemented")
-}
-
-func RegisterSchedulerCallback(SchedulerCallback) {
- panic("not implemented")
-}
-
-func RegisterLifecycleManagement(LifecycleManagement) {
- panic("not implemented")
-}
-
-func RegisterWebSocketCallback(WebSocketCallback) {
- panic("not implemented")
-}
-
-func RegisterNamedSchedulerCallback(name string, cb SchedulerCallback) scheduler.SchedulerService {
- panic("not implemented")
-}
diff --git a/plugins/api/api_plugin_dev_named_registry.go b/plugins/api/api_plugin_dev_named_registry.go
deleted file mode 100644
index 2ddb68779..000000000
--- a/plugins/api/api_plugin_dev_named_registry.go
+++ /dev/null
@@ -1,94 +0,0 @@
-//go:build wasip1
-
-package api
-
-import (
- "context"
- "strings"
-
- "github.com/navidrome/navidrome/plugins/host/scheduler"
-)
-
-var callbacks = make(namedCallbacks)
-
-// RegisterNamedSchedulerCallback registers a named scheduler callback. Named callbacks allow multiple callbacks to be registered
-// within the same plugin, and for the schedules to be scoped to the named callback. If you only need a single callback, you can use
-// the default (unnamed) callback registration function, RegisterSchedulerCallback.
-// It returns a scheduler.SchedulerService that can be used to schedule jobs for the named callback.
-//
-// Notes:
-//
-// - You can't mix named and unnamed callbacks within the same plugin.
-// - The name should be unique within the plugin, and it's recommended to use a short, descriptive name.
-// - The name is case-sensitive.
-func RegisterNamedSchedulerCallback(name string, cb SchedulerCallback) scheduler.SchedulerService {
- callbacks[name] = cb
- RegisterSchedulerCallback(&callbacks)
- return &namedSchedulerService{name: name, svc: scheduler.NewSchedulerService()}
-}
-
-const zwsp = string('\u200b')
-
-// namedCallbacks is a map of named scheduler callbacks. The key is the name of the callback, and the value is the callback itself.
-type namedCallbacks map[string]SchedulerCallback
-
-func parseKey(key string) (string, string) {
- parts := strings.SplitN(key, zwsp, 2)
- if len(parts) != 2 {
- return "", ""
- }
- return parts[0], parts[1]
-}
-
-func (n *namedCallbacks) OnSchedulerCallback(ctx context.Context, req *SchedulerCallbackRequest) (*SchedulerCallbackResponse, error) {
- name, scheduleId := parseKey(req.ScheduleId)
- cb, exists := callbacks[name]
- if !exists {
- return nil, nil
- }
- req.ScheduleId = scheduleId
- return cb.OnSchedulerCallback(ctx, req)
-}
-
-// namedSchedulerService is a wrapper around the host scheduler service that prefixes the schedule IDs with the
-// callback name. It is returned by RegisterNamedSchedulerCallback, and should be used by the plugin to schedule
-// jobs for the named callback.
-type namedSchedulerService struct {
- name string
- cb SchedulerCallback
- svc scheduler.SchedulerService
-}
-
-func (n *namedSchedulerService) makeKey(id string) string {
- return n.name + zwsp + id
-}
-
-func (n *namedSchedulerService) mapResponse(resp *scheduler.ScheduleResponse, err error) (*scheduler.ScheduleResponse, error) {
- if err != nil {
- return nil, err
- }
- _, resp.ScheduleId = parseKey(resp.ScheduleId)
- return resp, nil
-}
-
-func (n *namedSchedulerService) ScheduleOneTime(ctx context.Context, request *scheduler.ScheduleOneTimeRequest) (*scheduler.ScheduleResponse, error) {
- key := n.makeKey(request.ScheduleId)
- request.ScheduleId = key
- return n.mapResponse(n.svc.ScheduleOneTime(ctx, request))
-}
-
-func (n *namedSchedulerService) ScheduleRecurring(ctx context.Context, request *scheduler.ScheduleRecurringRequest) (*scheduler.ScheduleResponse, error) {
- key := n.makeKey(request.ScheduleId)
- request.ScheduleId = key
- return n.mapResponse(n.svc.ScheduleRecurring(ctx, request))
-}
-
-func (n *namedSchedulerService) CancelSchedule(ctx context.Context, request *scheduler.CancelRequest) (*scheduler.CancelResponse, error) {
- key := n.makeKey(request.ScheduleId)
- request.ScheduleId = key
- return n.svc.CancelSchedule(ctx, request)
-}
-
-func (n *namedSchedulerService) TimeNow(ctx context.Context, request *scheduler.TimeNowRequest) (*scheduler.TimeNowResponse, error) {
- return n.svc.TimeNow(ctx, request)
-}
diff --git a/plugins/api/api_vtproto.pb.go b/plugins/api/api_vtproto.pb.go
deleted file mode 100644
index 11caa1946..000000000
--- a/plugins/api/api_vtproto.pb.go
+++ /dev/null
@@ -1,7315 +0,0 @@
-// Code generated by protoc-gen-go-plugin. DO NOT EDIT.
-// versions:
-// protoc-gen-go-plugin v0.1.0
-// protoc v5.29.3
-// source: api/api.proto
-
-package api
-
-import (
- fmt "fmt"
- protoimpl "google.golang.org/protobuf/runtime/protoimpl"
- io "io"
- bits "math/bits"
-)
-
-const (
- // Verify that this generated code is sufficiently up-to-date.
- _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
- // Verify that runtime/protoimpl is sufficiently up-to-date.
- _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
-)
-
-func (m *ArtistMBIDRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistMBIDRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistMBIDRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Id) > 0 {
- i -= len(m.Id)
- copy(dAtA[i:], m.Id)
- i = encodeVarint(dAtA, i, uint64(len(m.Id)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistMBIDResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistMBIDResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistMBIDResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistURLRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistURLRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistURLRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Id) > 0 {
- i -= len(m.Id)
- copy(dAtA[i:], m.Id)
- i = encodeVarint(dAtA, i, uint64(len(m.Id)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistURLResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistURLResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistURLResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Url) > 0 {
- i -= len(m.Url)
- copy(dAtA[i:], m.Url)
- i = encodeVarint(dAtA, i, uint64(len(m.Url)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistBiographyRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistBiographyRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistBiographyRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Id) > 0 {
- i -= len(m.Id)
- copy(dAtA[i:], m.Id)
- i = encodeVarint(dAtA, i, uint64(len(m.Id)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistBiographyResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistBiographyResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistBiographyResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Biography) > 0 {
- i -= len(m.Biography)
- copy(dAtA[i:], m.Biography)
- i = encodeVarint(dAtA, i, uint64(len(m.Biography)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistSimilarRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistSimilarRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistSimilarRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.Limit != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Limit))
- i--
- dAtA[i] = 0x20
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Id) > 0 {
- i -= len(m.Id)
- copy(dAtA[i:], m.Id)
- i = encodeVarint(dAtA, i, uint64(len(m.Id)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *Artist) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *Artist) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *Artist) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistSimilarResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistSimilarResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistSimilarResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Artists) > 0 {
- for iNdEx := len(m.Artists) - 1; iNdEx >= 0; iNdEx-- {
- size, err := m.Artists[iNdEx].MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0xa
- }
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistImageRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistImageRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistImageRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Id) > 0 {
- i -= len(m.Id)
- copy(dAtA[i:], m.Id)
- i = encodeVarint(dAtA, i, uint64(len(m.Id)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ExternalImage) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ExternalImage) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ExternalImage) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.Size != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Size))
- i--
- dAtA[i] = 0x10
- }
- if len(m.Url) > 0 {
- i -= len(m.Url)
- copy(dAtA[i:], m.Url)
- i = encodeVarint(dAtA, i, uint64(len(m.Url)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistImageResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistImageResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistImageResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Images) > 0 {
- for iNdEx := len(m.Images) - 1; iNdEx >= 0; iNdEx-- {
- size, err := m.Images[iNdEx].MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0xa
- }
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistTopSongsRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistTopSongsRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistTopSongsRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.Count != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Count))
- i--
- dAtA[i] = 0x20
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.ArtistName) > 0 {
- i -= len(m.ArtistName)
- copy(dAtA[i:], m.ArtistName)
- i = encodeVarint(dAtA, i, uint64(len(m.ArtistName)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Id) > 0 {
- i -= len(m.Id)
- copy(dAtA[i:], m.Id)
- i = encodeVarint(dAtA, i, uint64(len(m.Id)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *Song) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *Song) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *Song) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ArtistTopSongsResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ArtistTopSongsResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ArtistTopSongsResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Songs) > 0 {
- for iNdEx := len(m.Songs) - 1; iNdEx >= 0; iNdEx-- {
- size, err := m.Songs[iNdEx].MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0xa
- }
- }
- return len(dAtA) - i, nil
-}
-
-func (m *AlbumInfoRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *AlbumInfoRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *AlbumInfoRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Artist) > 0 {
- i -= len(m.Artist)
- copy(dAtA[i:], m.Artist)
- i = encodeVarint(dAtA, i, uint64(len(m.Artist)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *AlbumInfo) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *AlbumInfo) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *AlbumInfo) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Url) > 0 {
- i -= len(m.Url)
- copy(dAtA[i:], m.Url)
- i = encodeVarint(dAtA, i, uint64(len(m.Url)))
- i--
- dAtA[i] = 0x22
- }
- if len(m.Description) > 0 {
- i -= len(m.Description)
- copy(dAtA[i:], m.Description)
- i = encodeVarint(dAtA, i, uint64(len(m.Description)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *AlbumInfoResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *AlbumInfoResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *AlbumInfoResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.Info != nil {
- size, err := m.Info.MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *AlbumImagesRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *AlbumImagesRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *AlbumImagesRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Artist) > 0 {
- i -= len(m.Artist)
- copy(dAtA[i:], m.Artist)
- i = encodeVarint(dAtA, i, uint64(len(m.Artist)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *AlbumImagesResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *AlbumImagesResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *AlbumImagesResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Images) > 0 {
- for iNdEx := len(m.Images) - 1; iNdEx >= 0; iNdEx-- {
- size, err := m.Images[iNdEx].MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0xa
- }
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ScrobblerIsAuthorizedRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ScrobblerIsAuthorizedRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ScrobblerIsAuthorizedRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Username) > 0 {
- i -= len(m.Username)
- copy(dAtA[i:], m.Username)
- i = encodeVarint(dAtA, i, uint64(len(m.Username)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.UserId) > 0 {
- i -= len(m.UserId)
- copy(dAtA[i:], m.UserId)
- i = encodeVarint(dAtA, i, uint64(len(m.UserId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ScrobblerIsAuthorizedResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ScrobblerIsAuthorizedResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ScrobblerIsAuthorizedResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Error) > 0 {
- i -= len(m.Error)
- copy(dAtA[i:], m.Error)
- i = encodeVarint(dAtA, i, uint64(len(m.Error)))
- i--
- dAtA[i] = 0x12
- }
- if m.Authorized {
- i--
- if m.Authorized {
- dAtA[i] = 1
- } else {
- dAtA[i] = 0
- }
- i--
- dAtA[i] = 0x8
- }
- return len(dAtA) - i, nil
-}
-
-func (m *TrackInfo) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *TrackInfo) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *TrackInfo) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.Position != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Position))
- i--
- dAtA[i] = 0x48
- }
- if m.Length != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Length))
- i--
- dAtA[i] = 0x40
- }
- if len(m.AlbumArtists) > 0 {
- for iNdEx := len(m.AlbumArtists) - 1; iNdEx >= 0; iNdEx-- {
- size, err := m.AlbumArtists[iNdEx].MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0x3a
- }
- }
- if len(m.Artists) > 0 {
- for iNdEx := len(m.Artists) - 1; iNdEx >= 0; iNdEx-- {
- size, err := m.Artists[iNdEx].MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0x32
- }
- }
- if len(m.AlbumMbid) > 0 {
- i -= len(m.AlbumMbid)
- copy(dAtA[i:], m.AlbumMbid)
- i = encodeVarint(dAtA, i, uint64(len(m.AlbumMbid)))
- i--
- dAtA[i] = 0x2a
- }
- if len(m.Album) > 0 {
- i -= len(m.Album)
- copy(dAtA[i:], m.Album)
- i = encodeVarint(dAtA, i, uint64(len(m.Album)))
- i--
- dAtA[i] = 0x22
- }
- if len(m.Name) > 0 {
- i -= len(m.Name)
- copy(dAtA[i:], m.Name)
- i = encodeVarint(dAtA, i, uint64(len(m.Name)))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Mbid) > 0 {
- i -= len(m.Mbid)
- copy(dAtA[i:], m.Mbid)
- i = encodeVarint(dAtA, i, uint64(len(m.Mbid)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.Id) > 0 {
- i -= len(m.Id)
- copy(dAtA[i:], m.Id)
- i = encodeVarint(dAtA, i, uint64(len(m.Id)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ScrobblerNowPlayingRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ScrobblerNowPlayingRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ScrobblerNowPlayingRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.Timestamp != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Timestamp))
- i--
- dAtA[i] = 0x20
- }
- if m.Track != nil {
- size, err := m.Track.MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Username) > 0 {
- i -= len(m.Username)
- copy(dAtA[i:], m.Username)
- i = encodeVarint(dAtA, i, uint64(len(m.Username)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.UserId) > 0 {
- i -= len(m.UserId)
- copy(dAtA[i:], m.UserId)
- i = encodeVarint(dAtA, i, uint64(len(m.UserId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ScrobblerNowPlayingResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ScrobblerNowPlayingResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ScrobblerNowPlayingResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Error) > 0 {
- i -= len(m.Error)
- copy(dAtA[i:], m.Error)
- i = encodeVarint(dAtA, i, uint64(len(m.Error)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ScrobblerScrobbleRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ScrobblerScrobbleRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ScrobblerScrobbleRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.Timestamp != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Timestamp))
- i--
- dAtA[i] = 0x20
- }
- if m.Track != nil {
- size, err := m.Track.MarshalToSizedBufferVT(dAtA[:i])
- if err != nil {
- return 0, err
- }
- i -= size
- i = encodeVarint(dAtA, i, uint64(size))
- i--
- dAtA[i] = 0x1a
- }
- if len(m.Username) > 0 {
- i -= len(m.Username)
- copy(dAtA[i:], m.Username)
- i = encodeVarint(dAtA, i, uint64(len(m.Username)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.UserId) > 0 {
- i -= len(m.UserId)
- copy(dAtA[i:], m.UserId)
- i = encodeVarint(dAtA, i, uint64(len(m.UserId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *ScrobblerScrobbleResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *ScrobblerScrobbleResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *ScrobblerScrobbleResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Error) > 0 {
- i -= len(m.Error)
- copy(dAtA[i:], m.Error)
- i = encodeVarint(dAtA, i, uint64(len(m.Error)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *SchedulerCallbackRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *SchedulerCallbackRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *SchedulerCallbackRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if m.IsRecurring {
- i--
- if m.IsRecurring {
- dAtA[i] = 1
- } else {
- dAtA[i] = 0
- }
- i--
- dAtA[i] = 0x18
- }
- if len(m.Payload) > 0 {
- i -= len(m.Payload)
- copy(dAtA[i:], m.Payload)
- i = encodeVarint(dAtA, i, uint64(len(m.Payload)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.ScheduleId) > 0 {
- i -= len(m.ScheduleId)
- copy(dAtA[i:], m.ScheduleId)
- i = encodeVarint(dAtA, i, uint64(len(m.ScheduleId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *SchedulerCallbackResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *SchedulerCallbackResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *SchedulerCallbackResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Error) > 0 {
- i -= len(m.Error)
- copy(dAtA[i:], m.Error)
- i = encodeVarint(dAtA, i, uint64(len(m.Error)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *InitRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *InitRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *InitRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Config) > 0 {
- for k := range m.Config {
- v := m.Config[k]
- baseI := i
- i -= len(v)
- copy(dAtA[i:], v)
- i = encodeVarint(dAtA, i, uint64(len(v)))
- i--
- dAtA[i] = 0x12
- i -= len(k)
- copy(dAtA[i:], k)
- i = encodeVarint(dAtA, i, uint64(len(k)))
- i--
- dAtA[i] = 0xa
- i = encodeVarint(dAtA, i, uint64(baseI-i))
- i--
- dAtA[i] = 0xa
- }
- }
- return len(dAtA) - i, nil
-}
-
-func (m *InitResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *InitResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *InitResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Error) > 0 {
- i -= len(m.Error)
- copy(dAtA[i:], m.Error)
- i = encodeVarint(dAtA, i, uint64(len(m.Error)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnTextMessageRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnTextMessageRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnTextMessageRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Message) > 0 {
- i -= len(m.Message)
- copy(dAtA[i:], m.Message)
- i = encodeVarint(dAtA, i, uint64(len(m.Message)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.ConnectionId) > 0 {
- i -= len(m.ConnectionId)
- copy(dAtA[i:], m.ConnectionId)
- i = encodeVarint(dAtA, i, uint64(len(m.ConnectionId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnTextMessageResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnTextMessageResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnTextMessageResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnBinaryMessageRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnBinaryMessageRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnBinaryMessageRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Data) > 0 {
- i -= len(m.Data)
- copy(dAtA[i:], m.Data)
- i = encodeVarint(dAtA, i, uint64(len(m.Data)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.ConnectionId) > 0 {
- i -= len(m.ConnectionId)
- copy(dAtA[i:], m.ConnectionId)
- i = encodeVarint(dAtA, i, uint64(len(m.ConnectionId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnBinaryMessageResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnBinaryMessageResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnBinaryMessageResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnErrorRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnErrorRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnErrorRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Error) > 0 {
- i -= len(m.Error)
- copy(dAtA[i:], m.Error)
- i = encodeVarint(dAtA, i, uint64(len(m.Error)))
- i--
- dAtA[i] = 0x12
- }
- if len(m.ConnectionId) > 0 {
- i -= len(m.ConnectionId)
- copy(dAtA[i:], m.ConnectionId)
- i = encodeVarint(dAtA, i, uint64(len(m.ConnectionId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnErrorResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnErrorResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnErrorResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnCloseRequest) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnCloseRequest) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnCloseRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- if len(m.Reason) > 0 {
- i -= len(m.Reason)
- copy(dAtA[i:], m.Reason)
- i = encodeVarint(dAtA, i, uint64(len(m.Reason)))
- i--
- dAtA[i] = 0x1a
- }
- if m.Code != 0 {
- i = encodeVarint(dAtA, i, uint64(m.Code))
- i--
- dAtA[i] = 0x10
- }
- if len(m.ConnectionId) > 0 {
- i -= len(m.ConnectionId)
- copy(dAtA[i:], m.ConnectionId)
- i = encodeVarint(dAtA, i, uint64(len(m.ConnectionId)))
- i--
- dAtA[i] = 0xa
- }
- return len(dAtA) - i, nil
-}
-
-func (m *OnCloseResponse) MarshalVT() (dAtA []byte, err error) {
- if m == nil {
- return nil, nil
- }
- size := m.SizeVT()
- dAtA = make([]byte, size)
- n, err := m.MarshalToSizedBufferVT(dAtA[:size])
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *OnCloseResponse) MarshalToVT(dAtA []byte) (int, error) {
- size := m.SizeVT()
- return m.MarshalToSizedBufferVT(dAtA[:size])
-}
-
-func (m *OnCloseResponse) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
- if m == nil {
- return 0, nil
- }
- i := len(dAtA)
- _ = i
- var l int
- _ = l
- if m.unknownFields != nil {
- i -= len(m.unknownFields)
- copy(dAtA[i:], m.unknownFields)
- }
- return len(dAtA) - i, nil
-}
-
-func encodeVarint(dAtA []byte, offset int, v uint64) int {
- offset -= sov(v)
- base := offset
- for v >= 1<<7 {
- dAtA[offset] = uint8(v&0x7f | 0x80)
- v >>= 7
- offset++
- }
- dAtA[offset] = uint8(v)
- return base
-}
-func (m *ArtistMBIDRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Id)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistMBIDResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistURLRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Id)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistURLResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Url)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistBiographyRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Id)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistBiographyResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Biography)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistSimilarRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Id)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if m.Limit != 0 {
- n += 1 + sov(uint64(m.Limit))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *Artist) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistSimilarResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- if len(m.Artists) > 0 {
- for _, e := range m.Artists {
- l = e.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistImageRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Id)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ExternalImage) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Url)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if m.Size != 0 {
- n += 1 + sov(uint64(m.Size))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistImageResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- if len(m.Images) > 0 {
- for _, e := range m.Images {
- l = e.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistTopSongsRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Id)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.ArtistName)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if m.Count != 0 {
- n += 1 + sov(uint64(m.Count))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *Song) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ArtistTopSongsResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- if len(m.Songs) > 0 {
- for _, e := range m.Songs {
- l = e.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *AlbumInfoRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Artist)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *AlbumInfo) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Description)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Url)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *AlbumInfoResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- if m.Info != nil {
- l = m.Info.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *AlbumImagesRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Artist)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *AlbumImagesResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- if len(m.Images) > 0 {
- for _, e := range m.Images {
- l = e.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ScrobblerIsAuthorizedRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.UserId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Username)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ScrobblerIsAuthorizedResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- if m.Authorized {
- n += 2
- }
- l = len(m.Error)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *TrackInfo) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Id)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Mbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Name)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Album)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.AlbumMbid)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if len(m.Artists) > 0 {
- for _, e := range m.Artists {
- l = e.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- }
- if len(m.AlbumArtists) > 0 {
- for _, e := range m.AlbumArtists {
- l = e.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- }
- if m.Length != 0 {
- n += 1 + sov(uint64(m.Length))
- }
- if m.Position != 0 {
- n += 1 + sov(uint64(m.Position))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ScrobblerNowPlayingRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.UserId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Username)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if m.Track != nil {
- l = m.Track.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- if m.Timestamp != 0 {
- n += 1 + sov(uint64(m.Timestamp))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ScrobblerNowPlayingResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Error)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ScrobblerScrobbleRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.UserId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Username)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if m.Track != nil {
- l = m.Track.SizeVT()
- n += 1 + l + sov(uint64(l))
- }
- if m.Timestamp != 0 {
- n += 1 + sov(uint64(m.Timestamp))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *ScrobblerScrobbleResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Error)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *SchedulerCallbackRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.ScheduleId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Payload)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if m.IsRecurring {
- n += 2
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *SchedulerCallbackResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Error)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *InitRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- if len(m.Config) > 0 {
- for k, v := range m.Config {
- _ = k
- _ = v
- mapEntrySize := 1 + len(k) + sov(uint64(len(k))) + 1 + len(v) + sov(uint64(len(v)))
- n += mapEntrySize + 1 + sov(uint64(mapEntrySize))
- }
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *InitResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.Error)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnTextMessageRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.ConnectionId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Message)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnTextMessageResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnBinaryMessageRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.ConnectionId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Data)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnBinaryMessageResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnErrorRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.ConnectionId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- l = len(m.Error)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnErrorResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnCloseRequest) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- l = len(m.ConnectionId)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- if m.Code != 0 {
- n += 1 + sov(uint64(m.Code))
- }
- l = len(m.Reason)
- if l > 0 {
- n += 1 + l + sov(uint64(l))
- }
- n += len(m.unknownFields)
- return n
-}
-
-func (m *OnCloseResponse) SizeVT() (n int) {
- if m == nil {
- return 0
- }
- var l int
- _ = l
- n += len(m.unknownFields)
- return n
-}
-
-func sov(x uint64) (n int) {
- return (bits.Len64(x|1) + 6) / 7
-}
-func soz(x uint64) (n int) {
- return sov(uint64((x << 1) ^ uint64((int64(x) >> 63))))
-}
-func (m *ArtistMBIDRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistMBIDRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistMBIDRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Id = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistMBIDResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistMBIDResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistMBIDResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistURLRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistURLRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistURLRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Id = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistURLResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistURLResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistURLResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Url", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Url = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistBiographyRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistBiographyRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistBiographyRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Id = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistBiographyResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistBiographyResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistBiographyResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Biography", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Biography = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistSimilarRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistSimilarRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistSimilarRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Id = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 4:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
- }
- m.Limit = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Limit |= int32(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *Artist) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: Artist: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: Artist: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistSimilarResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistSimilarResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistSimilarResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Artists", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Artists = append(m.Artists, &Artist{})
- if err := m.Artists[len(m.Artists)-1].UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistImageRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistImageRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistImageRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Id = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ExternalImage) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ExternalImage: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ExternalImage: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Url", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Url = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Size", wireType)
- }
- m.Size = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Size |= int32(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistImageResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistImageResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistImageResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Images", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Images = append(m.Images, &ExternalImage{})
- if err := m.Images[len(m.Images)-1].UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistTopSongsRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistTopSongsRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistTopSongsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Id = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field ArtistName", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.ArtistName = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 4:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType)
- }
- m.Count = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Count |= int32(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *Song) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: Song: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: Song: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ArtistTopSongsResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ArtistTopSongsResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ArtistTopSongsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Songs", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Songs = append(m.Songs, &Song{})
- if err := m.Songs[len(m.Songs)-1].UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *AlbumInfoRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: AlbumInfoRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: AlbumInfoRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Artist", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Artist = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *AlbumInfo) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: AlbumInfo: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: AlbumInfo: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Description = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 4:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Url", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Url = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *AlbumInfoResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: AlbumInfoResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: AlbumInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- if m.Info == nil {
- m.Info = &AlbumInfo{}
- }
- if err := m.Info.UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *AlbumImagesRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: AlbumImagesRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: AlbumImagesRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Artist", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Artist = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *AlbumImagesResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: AlbumImagesResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: AlbumImagesResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Images", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Images = append(m.Images, &ExternalImage{})
- if err := m.Images[len(m.Images)-1].UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ScrobblerIsAuthorizedRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ScrobblerIsAuthorizedRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ScrobblerIsAuthorizedRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field UserId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.UserId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Username = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ScrobblerIsAuthorizedResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ScrobblerIsAuthorizedResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ScrobblerIsAuthorizedResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Authorized", wireType)
- }
- var v int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- v |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- m.Authorized = bool(v != 0)
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Error = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *TrackInfo) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: TrackInfo: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: TrackInfo: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Id = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Mbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Mbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Name = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 4:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Album", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Album = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 5:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field AlbumMbid", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.AlbumMbid = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 6:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Artists", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Artists = append(m.Artists, &Artist{})
- if err := m.Artists[len(m.Artists)-1].UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- case 7:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field AlbumArtists", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.AlbumArtists = append(m.AlbumArtists, &Artist{})
- if err := m.AlbumArtists[len(m.AlbumArtists)-1].UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- case 8:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Length", wireType)
- }
- m.Length = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Length |= int32(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- case 9:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType)
- }
- m.Position = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Position |= int32(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ScrobblerNowPlayingRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ScrobblerNowPlayingRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ScrobblerNowPlayingRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field UserId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.UserId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Username = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Track", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- if m.Track == nil {
- m.Track = &TrackInfo{}
- }
- if err := m.Track.UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- case 4:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
- }
- m.Timestamp = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Timestamp |= int64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ScrobblerNowPlayingResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ScrobblerNowPlayingResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ScrobblerNowPlayingResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Error = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ScrobblerScrobbleRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ScrobblerScrobbleRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ScrobblerScrobbleRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field UserId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.UserId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Username = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Track", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- if m.Track == nil {
- m.Track = &TrackInfo{}
- }
- if err := m.Track.UnmarshalVT(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- case 4:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
- }
- m.Timestamp = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Timestamp |= int64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *ScrobblerScrobbleResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: ScrobblerScrobbleResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: ScrobblerScrobbleResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Error = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *SchedulerCallbackRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: SchedulerCallbackRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: SchedulerCallbackRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field ScheduleId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.ScheduleId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType)
- }
- var byteLen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- byteLen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if byteLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + byteLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Payload = append(m.Payload[:0], dAtA[iNdEx:postIndex]...)
- if m.Payload == nil {
- m.Payload = []byte{}
- }
- iNdEx = postIndex
- case 3:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field IsRecurring", wireType)
- }
- var v int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- v |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- m.IsRecurring = bool(v != 0)
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *SchedulerCallbackResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: SchedulerCallbackResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: SchedulerCallbackResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Error = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *InitRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: InitRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: InitRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + msglen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- if m.Config == nil {
- m.Config = make(map[string]string)
- }
- var mapkey string
- var mapvalue string
- for iNdEx < postIndex {
- entryPreIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- if fieldNum == 1 {
- var stringLenmapkey uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLenmapkey |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLenmapkey := int(stringLenmapkey)
- if intStringLenmapkey < 0 {
- return ErrInvalidLength
- }
- postStringIndexmapkey := iNdEx + intStringLenmapkey
- if postStringIndexmapkey < 0 {
- return ErrInvalidLength
- }
- if postStringIndexmapkey > l {
- return io.ErrUnexpectedEOF
- }
- mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
- iNdEx = postStringIndexmapkey
- } else if fieldNum == 2 {
- var stringLenmapvalue uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLenmapvalue |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLenmapvalue := int(stringLenmapvalue)
- if intStringLenmapvalue < 0 {
- return ErrInvalidLength
- }
- postStringIndexmapvalue := iNdEx + intStringLenmapvalue
- if postStringIndexmapvalue < 0 {
- return ErrInvalidLength
- }
- if postStringIndexmapvalue > l {
- return io.ErrUnexpectedEOF
- }
- mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue])
- iNdEx = postStringIndexmapvalue
- } else {
- iNdEx = entryPreIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > postIndex {
- return io.ErrUnexpectedEOF
- }
- iNdEx += skippy
- }
- }
- m.Config[mapkey] = mapvalue
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *InitResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: InitResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: InitResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Error = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnTextMessageRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnTextMessageRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnTextMessageRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field ConnectionId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.ConnectionId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Message = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnTextMessageResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnTextMessageResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnTextMessageResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnBinaryMessageRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnBinaryMessageRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnBinaryMessageRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field ConnectionId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.ConnectionId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
- }
- var byteLen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- byteLen |= int(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if byteLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + byteLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
- if m.Data == nil {
- m.Data = []byte{}
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnBinaryMessageResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnBinaryMessageResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnBinaryMessageResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnErrorRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnErrorRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnErrorRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field ConnectionId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.ConnectionId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Error = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnErrorResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnErrorResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnErrorResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnCloseRequest) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnCloseRequest: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnCloseRequest: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field ConnectionId", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.ConnectionId = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- case 2:
- if wireType != 0 {
- return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType)
- }
- m.Code = 0
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- m.Code |= int32(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- case 3:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLength
- }
- postIndex := iNdEx + intStringLen
- if postIndex < 0 {
- return ErrInvalidLength
- }
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Reason = string(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *OnCloseResponse) UnmarshalVT(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflow
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= uint64(b&0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: OnCloseResponse: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: OnCloseResponse: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- default:
- iNdEx = preIndex
- skippy, err := skip(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if (skippy < 0) || (iNdEx+skippy) < 0 {
- return ErrInvalidLength
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- m.unknownFields = append(m.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-
-func skip(dAtA []byte) (n int, err error) {
- l := len(dAtA)
- iNdEx := 0
- depth := 0
- for iNdEx < l {
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return 0, ErrIntOverflow
- }
- if iNdEx >= l {
- return 0, io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- wireType := int(wire & 0x7)
- switch wireType {
- case 0:
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return 0, ErrIntOverflow
- }
- if iNdEx >= l {
- return 0, io.ErrUnexpectedEOF
- }
- iNdEx++
- if dAtA[iNdEx-1] < 0x80 {
- break
- }
- }
- case 1:
- iNdEx += 8
- case 2:
- var length int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return 0, ErrIntOverflow
- }
- if iNdEx >= l {
- return 0, io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- length |= (int(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if length < 0 {
- return 0, ErrInvalidLength
- }
- iNdEx += length
- case 3:
- depth++
- case 4:
- if depth == 0 {
- return 0, ErrUnexpectedEndOfGroup
- }
- depth--
- case 5:
- iNdEx += 4
- default:
- return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
- }
- if iNdEx < 0 {
- return 0, ErrInvalidLength
- }
- if depth == 0 {
- return iNdEx, nil
- }
- }
- return 0, io.ErrUnexpectedEOF
-}
-
-var (
- ErrInvalidLength = fmt.Errorf("proto: negative length found during unmarshaling")
- ErrIntOverflow = fmt.Errorf("proto: integer overflow")
- ErrUnexpectedEndOfGroup = fmt.Errorf("proto: unexpected end of group")
-)
diff --git a/plugins/api/errors.go b/plugins/api/errors.go
deleted file mode 100644
index 796774b15..000000000
--- a/plugins/api/errors.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package api
-
-import "errors"
-
-var (
- // ErrNotImplemented indicates that the plugin does not implement the requested method.
- // No logic should be executed by the plugin.
- ErrNotImplemented = errors.New("plugin:not_implemented")
-
- // ErrNotFound indicates that the requested resource was not found by the plugin.
- ErrNotFound = errors.New("plugin:not_found")
-)
diff --git a/plugins/base_capability.go b/plugins/base_capability.go
deleted file mode 100644
index 6572a25ec..000000000
--- a/plugins/base_capability.go
+++ /dev/null
@@ -1,159 +0,0 @@
-package plugins
-
-import (
- "context"
- "errors"
- "fmt"
- "time"
-
- "github.com/navidrome/navidrome/core/metrics"
- "github.com/navidrome/navidrome/log"
- "github.com/navidrome/navidrome/model/id"
- "github.com/navidrome/navidrome/plugins/api"
-)
-
-// newBaseCapability creates a new instance of baseCapability with the required parameters.
-func newBaseCapability[S any, P any](wasmPath, id, capability string, m metrics.Metrics, loader P, loadFunc loaderFunc[S, P]) *baseCapability[S, P] {
- return &baseCapability[S, P]{
- wasmPath: wasmPath,
- id: id,
- capability: capability,
- loader: loader,
- loadFunc: loadFunc,
- metrics: m,
- }
-}
-
-// LoaderFunc is a generic function type that loads a plugin instance.
-type loaderFunc[S any, P any] func(ctx context.Context, loader P, path string) (S, error)
-
-// baseCapability is a generic base implementation for WASM plugins.
-// S is the capability interface type and P is the plugin loader type.
-type baseCapability[S any, P any] struct {
- wasmPath string
- id string
- capability string
- loader P
- loadFunc loaderFunc[S, P]
- metrics metrics.Metrics
-}
-
-func (w *baseCapability[S, P]) PluginID() string {
- return w.id
-}
-
-func (w *baseCapability[S, P]) serviceName() string {
- return w.id + "_" + w.capability
-}
-
-func (w *baseCapability[S, P]) getMetrics() metrics.Metrics {
- return w.metrics
-}
-
-// getInstance loads a new plugin instance and returns a cleanup function.
-func (w *baseCapability[S, P]) getInstance(ctx context.Context, methodName string) (S, func(), error) {
- start := time.Now()
- // Add context metadata for tracing
- ctx = log.NewContext(ctx, "capability", w.serviceName(), "method", methodName)
-
- inst, err := w.loadFunc(ctx, w.loader, w.wasmPath)
- if err != nil {
- var zero S
- return zero, func() {}, fmt.Errorf("baseCapability: failed to load instance for %s: %w", w.serviceName(), err)
- }
- // Add context metadata for tracing
- ctx = log.NewContext(ctx, "instanceID", getInstanceID(inst))
- log.Trace(ctx, "baseCapability: loaded instance", "elapsed", time.Since(start))
- return inst, func() {
- log.Trace(ctx, "baseCapability: finished using instance", "elapsed", time.Since(start))
- if closer, ok := any(inst).(interface{ Close(context.Context) error }); ok {
- _ = closer.Close(ctx)
- }
- }, nil
-}
-
-type wasmPlugin[S any] interface {
- PluginID() string
- getInstance(ctx context.Context, methodName string) (S, func(), error)
- getMetrics() metrics.Metrics
-}
-
-func callMethod[S any, R any](ctx context.Context, wp WasmPlugin, methodName string, fn func(inst S) (R, error)) (R, error) {
- // Add a unique call ID to the context for tracing
- ctx = log.NewContext(ctx, "callID", id.NewRandom())
- var r R
-
- p, ok := wp.(wasmPlugin[S])
- if !ok {
- log.Error(ctx, "callMethod: not a wasm plugin", "method", methodName, "pluginID", wp.PluginID())
- return r, fmt.Errorf("wasm plugin: not a wasm plugin: %s", wp.PluginID())
- }
-
- inst, done, err := p.getInstance(ctx, methodName)
- if err != nil {
- return r, err
- }
- start := time.Now()
- defer done()
- r, err = checkErr(fn(inst))
- elapsed := time.Since(start)
-
- if !errors.Is(err, api.ErrNotImplemented) {
- id := p.PluginID()
- isOk := err == nil
- metrics := p.getMetrics()
- if metrics != nil {
- metrics.RecordPluginRequest(ctx, id, methodName, isOk, elapsed.Milliseconds())
- log.Trace(ctx, "callMethod: sending metrics", "plugin", id, "method", methodName, "ok", isOk, "elapsed", elapsed)
- }
- }
-
- return r, err
-}
-
-// errorResponse is an interface that defines a method to retrieve an error message.
-// It is automatically implemented (generated) by all plugin responses that have an Error field
-type errorResponse interface {
- GetError() string
-}
-
-// checkErr returns an updated error if the response implements errorResponse and contains an error message.
-// If the response is nil, it returns the original error. Otherwise, it wraps or creates an error as needed.
-// It also maps error strings to their corresponding api.Err* constants.
-func checkErr[T any](resp T, err error) (T, error) {
- if any(resp) == nil {
- return resp, mapAPIError(err)
- }
- respErr, ok := any(resp).(errorResponse)
- if ok && respErr.GetError() != "" {
- respErrMsg := respErr.GetError()
- respErrErr := errors.New(respErrMsg)
- mappedErr := mapAPIError(respErrErr)
- // Check if the error was mapped to an API error (different from the temp error)
- if errors.Is(mappedErr, api.ErrNotImplemented) || errors.Is(mappedErr, api.ErrNotFound) {
- // Return the mapped API error instead of wrapping
- return resp, mappedErr
- }
- // For non-API errors, use wrap the original error if it is not nil
- return resp, errors.Join(respErrErr, err)
- }
- return resp, mapAPIError(err)
-}
-
-// mapAPIError maps error strings to their corresponding api.Err* constants.
-// This is needed as errors from plugins may not be of type api.Error, due to serialization/deserialization.
-func mapAPIError(err error) error {
- if err == nil {
- return nil
- }
-
- errStr := err.Error()
- switch errStr {
- case api.ErrNotImplemented.Error():
- return api.ErrNotImplemented
- case api.ErrNotFound.Error():
- return api.ErrNotFound
- default:
- return err
- }
-}
diff --git a/plugins/base_capability_test.go b/plugins/base_capability_test.go
deleted file mode 100644
index 3bece8dcd..000000000
--- a/plugins/base_capability_test.go
+++ /dev/null
@@ -1,285 +0,0 @@
-package plugins
-
-import (
- "context"
- "errors"
-
- "github.com/navidrome/navidrome/plugins/api"
- . "github.com/onsi/ginkgo/v2"
- . "github.com/onsi/gomega"
-)
-
-type nilInstance struct{}
-
-var _ = Describe("baseCapability", func() {
- var ctx = context.Background()
-
- It("should load instance using loadFunc", func() {
- called := false
- plugin := &baseCapability[*nilInstance, any]{
- wasmPath: "",
- id: "test",
- capability: "test",
- loadFunc: func(ctx context.Context, _ any, path string) (*nilInstance, error) {
- called = true
- return &nilInstance{}, nil
- },
- }
- inst, done, err := plugin.getInstance(ctx, "test")
- defer done()
- Expect(err).To(BeNil())
- Expect(inst).ToNot(BeNil())
- Expect(called).To(BeTrue())
- })
-})
-
-var _ = Describe("checkErr", func() {
- Context("when resp is nil", func() {
- It("should return nil error when both resp and err are nil", func() {
- var resp *testErrorResponse
-
- result, err := checkErr(resp, nil)
-
- Expect(result).To(BeNil())
- Expect(err).To(BeNil())
- })
-
- It("should return original error unchanged for non-API errors", func() {
- var resp *testErrorResponse
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(BeNil())
- Expect(err).To(Equal(originalErr))
- })
-
- It("should return mapped API error for ErrNotImplemented", func() {
- var resp *testErrorResponse
- err := errors.New("plugin:not_implemented")
-
- result, mappedErr := checkErr(resp, err)
-
- Expect(result).To(BeNil())
- Expect(mappedErr).To(Equal(api.ErrNotImplemented))
- })
-
- It("should return mapped API error for ErrNotFound", func() {
- var resp *testErrorResponse
- err := errors.New("plugin:not_found")
-
- result, mappedErr := checkErr(resp, err)
-
- Expect(result).To(BeNil())
- Expect(mappedErr).To(Equal(api.ErrNotFound))
- })
- })
-
- Context("when resp is a typed nil that implements errorResponse", func() {
- It("should not panic and return original error", func() {
- var resp *testErrorResponse // typed nil
- originalErr := errors.New("original error")
-
- // This should not panic
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(BeNil())
- Expect(err).To(Equal(originalErr))
- })
-
- It("should handle typed nil with nil error gracefully", func() {
- var resp *testErrorResponse // typed nil
-
- // This should not panic
- result, err := checkErr(resp, nil)
-
- Expect(result).To(BeNil())
- Expect(err).To(BeNil())
- })
- })
-
- Context("when resp implements errorResponse with non-empty error", func() {
- It("should create new error when original error is nil", func() {
- resp := &testErrorResponse{errorMsg: "plugin error"}
-
- result, err := checkErr(resp, nil)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError("plugin error"))
- })
-
- It("should wrap original error when both exist", func() {
- resp := &testErrorResponse{errorMsg: "plugin error"}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(HaveOccurred())
- // Check that both error messages are present in the joined error
- errStr := err.Error()
- Expect(errStr).To(ContainSubstring("plugin error"))
- Expect(errStr).To(ContainSubstring("original error"))
- })
-
- It("should return mapped API error for ErrNotImplemented when no original error", func() {
- resp := &testErrorResponse{errorMsg: "plugin:not_implemented"}
-
- result, err := checkErr(resp, nil)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(api.ErrNotImplemented))
- })
-
- It("should return mapped API error for ErrNotFound when no original error", func() {
- resp := &testErrorResponse{errorMsg: "plugin:not_found"}
-
- result, err := checkErr(resp, nil)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(api.ErrNotFound))
- })
-
- It("should return mapped API error for ErrNotImplemented even with original error", func() {
- resp := &testErrorResponse{errorMsg: "plugin:not_implemented"}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(api.ErrNotImplemented))
- })
-
- It("should return mapped API error for ErrNotFound even with original error", func() {
- resp := &testErrorResponse{errorMsg: "plugin:not_found"}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(api.ErrNotFound))
- })
- })
-
- Context("when resp implements errorResponse with empty error", func() {
- It("should return original error unchanged", func() {
- resp := &testErrorResponse{errorMsg: ""}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(originalErr))
- })
-
- It("should return nil error when both are empty/nil", func() {
- resp := &testErrorResponse{errorMsg: ""}
-
- result, err := checkErr(resp, nil)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(BeNil())
- })
-
- It("should map original API error when response error is empty", func() {
- resp := &testErrorResponse{errorMsg: ""}
- originalErr := errors.New("plugin:not_implemented")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(api.ErrNotImplemented))
- })
- })
-
- Context("when resp does not implement errorResponse", func() {
- It("should return original error unchanged", func() {
- resp := &testNonErrorResponse{data: "some data"}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(Equal(originalErr))
- })
-
- It("should return nil error when original error is nil", func() {
- resp := &testNonErrorResponse{data: "some data"}
-
- result, err := checkErr(resp, nil)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(BeNil())
- })
-
- It("should map original API error when response doesn't implement errorResponse", func() {
- resp := &testNonErrorResponse{data: "some data"}
- originalErr := errors.New("plugin:not_found")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(api.ErrNotFound))
- })
- })
-
- Context("when resp is a value type (not pointer)", func() {
- It("should handle value types that implement errorResponse", func() {
- resp := testValueErrorResponse{errorMsg: "value error"}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(HaveOccurred())
- // Check that both error messages are present in the joined error
- errStr := err.Error()
- Expect(errStr).To(ContainSubstring("value error"))
- Expect(errStr).To(ContainSubstring("original error"))
- })
-
- It("should handle value types with empty error", func() {
- resp := testValueErrorResponse{errorMsg: ""}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(originalErr))
- })
-
- It("should handle value types with API error", func() {
- resp := testValueErrorResponse{errorMsg: "plugin:not_implemented"}
- originalErr := errors.New("original error")
-
- result, err := checkErr(resp, originalErr)
-
- Expect(result).To(Equal(resp))
- Expect(err).To(MatchError(api.ErrNotImplemented))
- })
- })
-})
-
-// Test helper types
-type testErrorResponse struct {
- errorMsg string
-}
-
-func (t *testErrorResponse) GetError() string {
- if t == nil {
- return "" // This is what would typically happen with a typed nil
- }
- return t.errorMsg
-}
-
-type testNonErrorResponse struct {
- data string
-}
-
-type testValueErrorResponse struct {
- errorMsg string
-}
-
-func (t testValueErrorResponse) GetError() string {
- return t.errorMsg
-}
diff --git a/plugins/capabilities.go b/plugins/capabilities.go
new file mode 100644
index 000000000..81e683b6b
--- /dev/null
+++ b/plugins/capabilities.go
@@ -0,0 +1,41 @@
+package plugins
+
+import "slices"
+
+// Capability represents a plugin capability type.
+// Capabilities are detected by checking which functions a plugin exports.
+type Capability string
+
+// capabilityFunctions maps each capability to its required/optional functions.
+// A plugin has a capability if it exports at least one of these functions.
+var capabilityFunctions = map[Capability][]string{}
+
+// registerCapability registers a capability with its associated functions.
+func registerCapability(cap Capability, functions ...string) {
+ capabilityFunctions[cap] = functions
+}
+
+// functionExistsChecker is an interface for checking if a function exists in a plugin.
+// This allows for testing without a real plugin instance.
+type functionExistsChecker interface {
+ FunctionExists(name string) bool
+}
+
+// detectCapabilities detects which capabilities a plugin has by checking
+// which functions it exports.
+func detectCapabilities(plugin functionExistsChecker) []Capability {
+ var capabilities []Capability
+
+ for cap, functions := range capabilityFunctions {
+ if slices.ContainsFunc(functions, plugin.FunctionExists) {
+ capabilities = append(capabilities, cap) // Found at least one function, plugin has this capability
+ }
+ }
+
+ return capabilities
+}
+
+// hasCapability checks if the given capabilities slice contains a specific capability.
+func hasCapability(capabilities []Capability, cap Capability) bool {
+ return slices.Contains(capabilities, cap)
+}
diff --git a/plugins/capabilities/README.md b/plugins/capabilities/README.md
new file mode 100644
index 000000000..fca3cbd31
--- /dev/null
+++ b/plugins/capabilities/README.md
@@ -0,0 +1,87 @@
+# Navidrome Plugin Capabilities
+
+This directory contains the Go interface definitions for Navidrome plugin capabilities. These interfaces are the **source of truth** for plugin development and are used to generate:
+
+1. **Go PDK packages** (`pdk/go/*/`) - Type-safe wrappers for Go plugin developers
+2. **Rust PDK crates** (`pdk/rust/*/`) - Type-safe wrappers for Rust plugin developers
+3. **XTP YAML schemas** (`*.yaml`) - Schema files for other [Extism plugin languages](https://extism.org/docs/concepts/pdk/) (TypeScript, Python, C#, Zig, C++, ...)
+
+## For Go Plugin Developers
+
+Go developers should use the generated PDK packages in `plugins/pdk/go/`. See the example Go plugins in `plugins/examples/` for usage patterns.
+
+## For Rust Plugin Developers
+
+Rust developers should use the generated PDK crate in `plugins/pdk/rust/nd-pdk`. See the example Rust plugins in `plugins/examples` for usage patterns.
+
+## For Non-Go Plugin Developers
+
+If you're developing plugins in other languages (TypeScript, Rust, Python, C#, Zig, C++), you can use the XTP CLI to generate type-safe bindings from the YAML schema files in this directory.
+
+### Prerequisites
+
+Install the XTP CLI:
+
+```bash
+# macOS
+brew install dylibso/tap/xtp
+
+# Other platforms - see https://docs.xtp.dylibso.com/docs/cli
+curl https://static.dylibso.com/cli/install.sh | bash
+```
+
+### Generating Plugin Scaffolding
+
+Use the XTP CLI to generate plugin boilerplate from any capability schema:
+
+```bash
+# TypeScript
+xtp plugin init --schema-file plugins/capabilities/metadata_agent.yaml \
+ --template typescript --path my-plugin
+
+# Rust
+xtp plugin init --schema-file plugins/capabilities/scrobbler.yaml \
+ --template rust --path my-plugin
+
+# Python
+xtp plugin init --schema-file plugins/capabilities/lifecycle.yaml \
+ --template python --path my-plugin
+
+# C#
+xtp plugin init --schema-file plugins/capabilities/scheduler_callback.yaml \
+ --template csharp --path my-plugin
+
+# Go (alternative to using the PDK packages)
+xtp plugin init --schema-file plugins/capabilities/websocket_callback.yaml \
+ --template go --path my-plugin
+```
+
+### Available Capabilities
+
+| Capability | Schema File | Description |
+|--------------------|---------------------------|-------------------------------------------------------------|
+| Metadata Agent | `metadata_agent.yaml` | Fetch artist biographies, album images, and similar artists |
+| Scrobbler | `scrobbler.yaml` | Report listening activity to external services |
+| Lifecycle | `lifecycle.yaml` | Plugin initialization callbacks |
+| Scheduler Callback | `scheduler_callback.yaml` | Scheduled task execution |
+| WebSocket Callback | `websocket_callback.yaml` | Real-time WebSocket message handling |
+
+### Building Your Plugin
+
+After generating the scaffolding, implement the required functions and build your plugin as a WebAssembly module. The exact build process depends on your chosen language - see the [Extism PDK documentation](https://extism.org/docs/concepts/pdk) for language-specific guides.
+
+## XTP Schema Generation
+
+The YAML schemas in this package are automatically generated from the capability Go interfaces using `ndpgen`.
+To regenerate the schemas after modifying the interfaces, run:
+
+```bash
+cd plugins/cmd/ndpgen && go run . -schemas -input=./plugins/capabilities
+```
+
+## Resources
+
+- [XTP Documentation](https://docs.xtp.dylibso.com/)
+- [XTP Bindgen Repository](https://github.com/dylibso/xtp-bindgen)
+- [Extism Plugin Development Kit](https://extism.org/docs/concepts/pdk)
+- [XTP Schema Definition](https://raw.githubusercontent.com/dylibso/xtp-bindgen/5090518dd86ba5e734dc225a33066ecc0ed2e12d/plugin/schema.json)
diff --git a/plugins/capabilities/doc.go b/plugins/capabilities/doc.go
new file mode 100644
index 000000000..fa9b7eb5d
--- /dev/null
+++ b/plugins/capabilities/doc.go
@@ -0,0 +1,56 @@
+// Package capabilities defines Go interfaces for Navidrome plugin capabilities.
+//
+// These interfaces serve as the source of truth for capability definitions.
+// The ndpgen tool generates:
+// - Go export wrappers in plugins/pdk/go// for Go plugins
+// - XTP YAML schemas for non-Go plugins (Rust, TypeScript, etc.)
+//
+// Each capability is defined as an annotated interface:
+//
+// //nd:capability name=metadata
+// type MetadataAgent interface {
+// //nd:export name=nd_get_artist_biography
+// GetArtistBiography(ArtistRequest) (*ArtistBiographyResponse, error)
+// }
+//
+// Annotation Reference:
+//
+// //nd:capability name= [required=true]
+// - Marks an interface as a capability
+// - name: Generated package name (e.g., name=metadata → pdk/go/metadata/)
+// - required: If true, all methods must be implemented (default: false)
+//
+// //nd:export name=
+// - Marks a method as an exported WASM function
+// - name: The export name (e.g., nd_get_artist_biography)
+//
+// Generated Code Structure:
+//
+// For a capability like MetadataAgent with required=false:
+//
+// package metadata
+//
+// // Agent is the marker interface
+// type Agent interface{}
+//
+// // Optional provider interfaces
+// type ArtistBiographyProvider interface {
+// GetArtistBiography(ArtistRequest) (*ArtistBiographyResponse, error)
+// }
+//
+// // Registration function
+// func Register(impl Agent) { ... }
+//
+// For a capability with required=true:
+//
+// package scrobbler
+//
+// // Scrobbler requires all methods
+// type Scrobbler interface {
+// IsAuthorized(IsAuthorizedRequest) (bool, error)
+// NowPlaying(NowPlayingRequest) error
+// Scrobble(ScrobbleRequest) error
+// }
+//
+// func Register(impl Scrobbler) { ... }
+package capabilities
diff --git a/plugins/capabilities/lifecycle.go b/plugins/capabilities/lifecycle.go
new file mode 100644
index 000000000..b5f19ec5b
--- /dev/null
+++ b/plugins/capabilities/lifecycle.go
@@ -0,0 +1,19 @@
+package capabilities
+
+// Lifecycle provides plugin lifecycle hooks.
+// This capability allows plugins to perform initialization when loaded,
+// such as establishing connections, starting background processes, or
+// validating configuration.
+//
+// The OnInit function is called once when the plugin is loaded, and is NOT
+// called when the plugin is hot-reloaded. Plugins should not assume this
+// function will be called on every startup.
+//
+//nd:capability name=lifecycle
+type Lifecycle interface {
+ // OnInit is called after a plugin is fully loaded with all services registered.
+ // Plugins can use this function to perform one-time initialization tasks.
+ // Errors are logged but will not prevent the plugin from being loaded.
+ //nd:export name=nd_on_init
+ OnInit() error
+}
diff --git a/plugins/capabilities/lifecycle.yaml b/plugins/capabilities/lifecycle.yaml
new file mode 100644
index 000000000..7c6af62b8
--- /dev/null
+++ b/plugins/capabilities/lifecycle.yaml
@@ -0,0 +1,7 @@
+version: v1-draft
+exports:
+ nd_on_init:
+ description: |-
+ OnInit is called after a plugin is fully loaded with all services registered.
+ Plugins can use this function to perform one-time initialization tasks.
+ Errors are logged but will not prevent the plugin from being loaded.
diff --git a/plugins/capabilities/lyrics.go b/plugins/capabilities/lyrics.go
new file mode 100644
index 000000000..6f6d19177
--- /dev/null
+++ b/plugins/capabilities/lyrics.go
@@ -0,0 +1,26 @@
+package capabilities
+
+// Lyrics provides lyrics for a given track from external sources.
+//
+//nd:capability name=lyrics required=true
+type Lyrics interface {
+ //nd:export name=nd_lyrics_get_lyrics
+ GetLyrics(GetLyricsRequest) (GetLyricsResponse, error)
+}
+
+// GetLyricsRequest contains the track information for lyrics lookup.
+type GetLyricsRequest struct {
+ Track TrackInfo `json:"track"`
+}
+
+// GetLyricsResponse contains the lyrics returned by the plugin.
+type GetLyricsResponse struct {
+ Lyrics []LyricsText `json:"lyrics"`
+}
+
+// LyricsText represents a single set of lyrics in raw text format.
+// Text can be plain text or LRC format — Navidrome will parse it.
+type LyricsText struct {
+ Lang string `json:"lang,omitempty"`
+ Text string `json:"text"`
+}
diff --git a/plugins/capabilities/lyrics.yaml b/plugins/capabilities/lyrics.yaml
new file mode 100644
index 000000000..e4f88476c
--- /dev/null
+++ b/plugins/capabilities/lyrics.yaml
@@ -0,0 +1,115 @@
+version: v1-draft
+exports:
+ nd_lyrics_get_lyrics:
+ input:
+ $ref: '#/components/schemas/GetLyricsRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/GetLyricsResponse'
+ contentType: application/json
+components:
+ schemas:
+ ArtistRef:
+ description: ArtistRef is a reference to an artist with name and optional MBID.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID (if known).
+ name:
+ type: string
+ description: Name is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the artist.
+ required:
+ - name
+ GetLyricsRequest:
+ description: GetLyricsRequest contains the track information for lyrics lookup.
+ properties:
+ track:
+ $ref: '#/components/schemas/TrackInfo'
+ required:
+ - track
+ GetLyricsResponse:
+ description: GetLyricsResponse contains the lyrics returned by the plugin.
+ properties:
+ lyrics:
+ type: array
+ items:
+ $ref: '#/components/schemas/LyricsText'
+ required:
+ - lyrics
+ LyricsText:
+ description: |-
+ LyricsText represents a single set of lyrics in raw text format.
+ Text can be plain text or LRC format — Navidrome will parse it.
+ properties:
+ lang:
+ type: string
+ text:
+ type: string
+ required:
+ - text
+ TrackInfo:
+ description: TrackInfo contains track metadata.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome track ID.
+ title:
+ type: string
+ description: Title is the track title.
+ album:
+ type: string
+ description: Album is the album name.
+ artist:
+ type: string
+ description: Artist is the formatted artist name for display (e.g., "Artist1 • Artist2").
+ albumArtist:
+ type: string
+ description: AlbumArtist is the formatted album artist name for display.
+ artists:
+ type: array
+ description: Artists is the list of track artists.
+ items:
+ $ref: '#/components/schemas/ArtistRef'
+ albumArtists:
+ type: array
+ description: AlbumArtists is the list of album artists.
+ items:
+ $ref: '#/components/schemas/ArtistRef'
+ duration:
+ type: number
+ format: float
+ description: Duration is the track duration in seconds.
+ trackNumber:
+ type: integer
+ format: int32
+ description: TrackNumber is the track number on the album.
+ discNumber:
+ type: integer
+ format: int32
+ description: DiscNumber is the disc number.
+ mbzRecordingId:
+ type: string
+ description: MBZRecordingID is the MusicBrainz recording ID.
+ mbzAlbumId:
+ type: string
+ description: MBZAlbumID is the MusicBrainz album/release ID.
+ mbzReleaseGroupId:
+ type: string
+ description: MBZReleaseGroupID is the MusicBrainz release group ID.
+ mbzReleaseTrackId:
+ type: string
+ description: MBZReleaseTrackID is the MusicBrainz release track ID.
+ required:
+ - id
+ - title
+ - album
+ - artist
+ - albumArtist
+ - artists
+ - albumArtists
+ - duration
+ - trackNumber
+ - discNumber
diff --git a/plugins/capabilities/metadata_agent.go b/plugins/capabilities/metadata_agent.go
new file mode 100644
index 000000000..407f21ec5
--- /dev/null
+++ b/plugins/capabilities/metadata_agent.go
@@ -0,0 +1,237 @@
+package capabilities
+
+// MetadataAgent provides artist and album metadata retrieval.
+// This capability allows plugins to provide external metadata for artists and albums,
+// such as biographies, images, similar artists, and top songs.
+//
+// Plugins implementing this capability can choose which methods to implement.
+// Each method is optional - plugins only need to provide the functionality they support.
+//
+//nd:capability name=metadata
+type MetadataAgent interface {
+ // GetArtistMBID retrieves the MusicBrainz ID for an artist.
+ //nd:export name=nd_get_artist_mbid
+ GetArtistMBID(ArtistMBIDRequest) (*ArtistMBIDResponse, error)
+
+ // GetArtistURL retrieves the external URL for an artist.
+ //nd:export name=nd_get_artist_url
+ GetArtistURL(ArtistRequest) (*ArtistURLResponse, error)
+
+ // GetArtistBiography retrieves the biography for an artist.
+ //nd:export name=nd_get_artist_biography
+ GetArtistBiography(ArtistRequest) (*ArtistBiographyResponse, error)
+
+ // GetSimilarArtists retrieves similar artists for a given artist.
+ //nd:export name=nd_get_similar_artists
+ GetSimilarArtists(SimilarArtistsRequest) (*SimilarArtistsResponse, error)
+
+ // GetArtistImages retrieves images for an artist.
+ //nd:export name=nd_get_artist_images
+ GetArtistImages(ArtistRequest) (*ArtistImagesResponse, error)
+
+ // GetArtistTopSongs retrieves top songs for an artist.
+ //nd:export name=nd_get_artist_top_songs
+ GetArtistTopSongs(TopSongsRequest) (*TopSongsResponse, error)
+
+ // GetAlbumInfo retrieves album information.
+ //nd:export name=nd_get_album_info
+ GetAlbumInfo(AlbumRequest) (*AlbumInfoResponse, error)
+
+ // GetAlbumImages retrieves images for an album.
+ //nd:export name=nd_get_album_images
+ GetAlbumImages(AlbumRequest) (*AlbumImagesResponse, error)
+
+ // GetSimilarSongsByTrack retrieves songs similar to a specific track.
+ //nd:export name=nd_get_similar_songs_by_track
+ GetSimilarSongsByTrack(SimilarSongsByTrackRequest) (*SimilarSongsResponse, error)
+
+ // GetSimilarSongsByAlbum retrieves songs similar to tracks on an album.
+ //nd:export name=nd_get_similar_songs_by_album
+ GetSimilarSongsByAlbum(SimilarSongsByAlbumRequest) (*SimilarSongsResponse, error)
+
+ // GetSimilarSongsByArtist retrieves songs similar to an artist's catalog.
+ //nd:export name=nd_get_similar_songs_by_artist
+ GetSimilarSongsByArtist(SimilarSongsByArtistRequest) (*SimilarSongsResponse, error)
+}
+
+// ArtistMBIDRequest is the request for GetArtistMBID.
+type ArtistMBIDRequest struct {
+ // ID is the internal Navidrome artist ID.
+ ID string `json:"id"`
+ // Name is the artist name.
+ Name string `json:"name"`
+}
+
+// ArtistMBIDResponse is the response for GetArtistMBID.
+type ArtistMBIDResponse struct {
+ // MBID is the MusicBrainz ID for the artist.
+ MBID string `json:"mbid"`
+}
+
+// ArtistRequest is the common request for artist-related functions.
+type ArtistRequest struct {
+ // ID is the internal Navidrome artist ID.
+ ID string `json:"id"`
+ // Name is the artist name.
+ Name string `json:"name"`
+ // MBID is the MusicBrainz ID for the artist (if known).
+ MBID string `json:"mbid,omitempty"`
+}
+
+// ArtistURLResponse is the response for GetArtistURL.
+type ArtistURLResponse struct {
+ // URL is the external URL for the artist.
+ URL string `json:"url"`
+}
+
+// ArtistBiographyResponse is the response for GetArtistBiography.
+type ArtistBiographyResponse struct {
+ // Biography is the artist biography text.
+ Biography string `json:"biography"`
+}
+
+// SimilarArtistsRequest is the request for GetSimilarArtists.
+type SimilarArtistsRequest struct {
+ // ID is the internal Navidrome artist ID.
+ ID string `json:"id"`
+ // Name is the artist name.
+ Name string `json:"name"`
+ // MBID is the MusicBrainz ID for the artist (if known).
+ MBID string `json:"mbid,omitempty"`
+ // Limit is the maximum number of similar artists to return.
+ Limit int32 `json:"limit"`
+}
+
+// SimilarArtistsResponse is the response for GetSimilarArtists.
+type SimilarArtistsResponse struct {
+ // Artists is the list of similar artists.
+ Artists []ArtistRef `json:"artists"`
+}
+
+// ImageInfo represents an image with URL and size.
+type ImageInfo struct {
+ // URL is the URL of the image.
+ URL string `json:"url"`
+ // Size is the size of the image in pixels (width or height).
+ Size int32 `json:"size"`
+}
+
+// ArtistImagesResponse is the response for GetArtistImages.
+type ArtistImagesResponse struct {
+ // Images is the list of artist images.
+ Images []ImageInfo `json:"images"`
+}
+
+// TopSongsRequest is the request for GetArtistTopSongs.
+type TopSongsRequest struct {
+ // ID is the internal Navidrome artist ID.
+ ID string `json:"id"`
+ // Name is the artist name.
+ Name string `json:"name"`
+ // MBID is the MusicBrainz ID for the artist (if known).
+ MBID string `json:"mbid,omitempty"`
+ // Count is the maximum number of top songs to return.
+ Count int32 `json:"count"`
+}
+
+// SongRef is a reference to a song with metadata for matching.
+type SongRef struct {
+ // ID is the internal Navidrome mediafile ID (if known).
+ ID string `json:"id,omitempty"`
+ // Name is the song name.
+ Name string `json:"name"`
+ // MBID is the MusicBrainz ID for the song.
+ MBID string `json:"mbid,omitempty"`
+ // ISRC is the International Standard Recording Code for the song.
+ ISRC string `json:"isrc,omitempty"`
+ // Artist is the artist name.
+ Artist string `json:"artist,omitempty"`
+ // ArtistMBID is the MusicBrainz artist ID.
+ ArtistMBID string `json:"artistMbid,omitempty"`
+ // Album is the album name.
+ Album string `json:"album,omitempty"`
+ // AlbumMBID is the MusicBrainz release ID.
+ AlbumMBID string `json:"albumMbid,omitempty"`
+ // Duration is the song duration in seconds.
+ Duration float32 `json:"duration,omitempty"`
+}
+
+// TopSongsResponse is the response for GetArtistTopSongs.
+type TopSongsResponse struct {
+ // Songs is the list of top songs.
+ Songs []SongRef `json:"songs"`
+}
+
+// AlbumRequest is the common request for album-related functions.
+type AlbumRequest struct {
+ // Name is the album name.
+ Name string `json:"name"`
+ // Artist is the album artist name.
+ Artist string `json:"artist"`
+ // MBID is the MusicBrainz ID for the album (if known).
+ MBID string `json:"mbid,omitempty"`
+}
+
+// AlbumInfoResponse is the response for GetAlbumInfo.
+type AlbumInfoResponse struct {
+ // Name is the album name.
+ Name string `json:"name"`
+ // MBID is the MusicBrainz ID for the album.
+ MBID string `json:"mbid"`
+ // Description is the album description/notes.
+ Description string `json:"description"`
+ // URL is the external URL for the album.
+ URL string `json:"url"`
+}
+
+// AlbumImagesResponse is the response for GetAlbumImages.
+type AlbumImagesResponse struct {
+ // Images is the list of album images.
+ Images []ImageInfo `json:"images"`
+}
+
+// SimilarSongsByTrackRequest is the request for GetSimilarSongsByTrack.
+type SimilarSongsByTrackRequest struct {
+ // ID is the internal Navidrome mediafile ID.
+ ID string `json:"id"`
+ // Name is the track title.
+ Name string `json:"name"`
+ // Artist is the artist name.
+ Artist string `json:"artist"`
+ // MBID is the MusicBrainz recording ID (if known).
+ MBID string `json:"mbid,omitempty"`
+ // Count is the maximum number of similar songs to return.
+ Count int32 `json:"count"`
+}
+
+// SimilarSongsByAlbumRequest is the request for GetSimilarSongsByAlbum.
+type SimilarSongsByAlbumRequest struct {
+ // ID is the internal Navidrome album ID.
+ ID string `json:"id"`
+ // Name is the album name.
+ Name string `json:"name"`
+ // Artist is the album artist name.
+ Artist string `json:"artist"`
+ // MBID is the MusicBrainz release ID (if known).
+ MBID string `json:"mbid,omitempty"`
+ // Count is the maximum number of similar songs to return.
+ Count int32 `json:"count"`
+}
+
+// SimilarSongsByArtistRequest is the request for GetSimilarSongsByArtist.
+type SimilarSongsByArtistRequest struct {
+ // ID is the internal Navidrome artist ID.
+ ID string `json:"id"`
+ // Name is the artist name.
+ Name string `json:"name"`
+ // MBID is the MusicBrainz artist ID (if known).
+ MBID string `json:"mbid,omitempty"`
+ // Count is the maximum number of similar songs to return.
+ Count int32 `json:"count"`
+}
+
+// SimilarSongsResponse is the response for GetSimilarSongsBy* functions.
+type SimilarSongsResponse struct {
+ // Songs is the list of similar songs.
+ Songs []SongRef `json:"songs"`
+}
diff --git a/plugins/capabilities/metadata_agent.yaml b/plugins/capabilities/metadata_agent.yaml
new file mode 100644
index 000000000..4940a5056
--- /dev/null
+++ b/plugins/capabilities/metadata_agent.yaml
@@ -0,0 +1,396 @@
+version: v1-draft
+exports:
+ nd_get_artist_mbid:
+ description: GetArtistMBID retrieves the MusicBrainz ID for an artist.
+ input:
+ $ref: '#/components/schemas/ArtistMBIDRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/ArtistMBIDResponse'
+ contentType: application/json
+ nd_get_artist_url:
+ description: GetArtistURL retrieves the external URL for an artist.
+ input:
+ $ref: '#/components/schemas/ArtistRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/ArtistURLResponse'
+ contentType: application/json
+ nd_get_artist_biography:
+ description: GetArtistBiography retrieves the biography for an artist.
+ input:
+ $ref: '#/components/schemas/ArtistRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/ArtistBiographyResponse'
+ contentType: application/json
+ nd_get_similar_artists:
+ description: GetSimilarArtists retrieves similar artists for a given artist.
+ input:
+ $ref: '#/components/schemas/SimilarArtistsRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/SimilarArtistsResponse'
+ contentType: application/json
+ nd_get_artist_images:
+ description: GetArtistImages retrieves images for an artist.
+ input:
+ $ref: '#/components/schemas/ArtistRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/ArtistImagesResponse'
+ contentType: application/json
+ nd_get_artist_top_songs:
+ description: GetArtistTopSongs retrieves top songs for an artist.
+ input:
+ $ref: '#/components/schemas/TopSongsRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/TopSongsResponse'
+ contentType: application/json
+ nd_get_album_info:
+ description: GetAlbumInfo retrieves album information.
+ input:
+ $ref: '#/components/schemas/AlbumRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/AlbumInfoResponse'
+ contentType: application/json
+ nd_get_album_images:
+ description: GetAlbumImages retrieves images for an album.
+ input:
+ $ref: '#/components/schemas/AlbumRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/AlbumImagesResponse'
+ contentType: application/json
+ nd_get_similar_songs_by_track:
+ description: GetSimilarSongsByTrack retrieves songs similar to a specific track.
+ input:
+ $ref: '#/components/schemas/SimilarSongsByTrackRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/SimilarSongsResponse'
+ contentType: application/json
+ nd_get_similar_songs_by_album:
+ description: GetSimilarSongsByAlbum retrieves songs similar to tracks on an album.
+ input:
+ $ref: '#/components/schemas/SimilarSongsByAlbumRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/SimilarSongsResponse'
+ contentType: application/json
+ nd_get_similar_songs_by_artist:
+ description: GetSimilarSongsByArtist retrieves songs similar to an artist's catalog.
+ input:
+ $ref: '#/components/schemas/SimilarSongsByArtistRequest'
+ contentType: application/json
+ output:
+ $ref: '#/components/schemas/SimilarSongsResponse'
+ contentType: application/json
+components:
+ schemas:
+ AlbumImagesResponse:
+ description: AlbumImagesResponse is the response for GetAlbumImages.
+ properties:
+ images:
+ type: array
+ description: Images is the list of album images.
+ items:
+ $ref: '#/components/schemas/ImageInfo'
+ required:
+ - images
+ AlbumInfoResponse:
+ description: AlbumInfoResponse is the response for GetAlbumInfo.
+ properties:
+ name:
+ type: string
+ description: Name is the album name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the album.
+ description:
+ type: string
+ description: Description is the album description/notes.
+ url:
+ type: string
+ description: URL is the external URL for the album.
+ required:
+ - name
+ - mbid
+ - description
+ - url
+ AlbumRequest:
+ description: AlbumRequest is the common request for album-related functions.
+ properties:
+ name:
+ type: string
+ description: Name is the album name.
+ artist:
+ type: string
+ description: Artist is the album artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the album (if known).
+ required:
+ - name
+ - artist
+ ArtistBiographyResponse:
+ description: ArtistBiographyResponse is the response for GetArtistBiography.
+ properties:
+ biography:
+ type: string
+ description: Biography is the artist biography text.
+ required:
+ - biography
+ ArtistImagesResponse:
+ description: ArtistImagesResponse is the response for GetArtistImages.
+ properties:
+ images:
+ type: array
+ description: Images is the list of artist images.
+ items:
+ $ref: '#/components/schemas/ImageInfo'
+ required:
+ - images
+ ArtistMBIDRequest:
+ description: ArtistMBIDRequest is the request for GetArtistMBID.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID.
+ name:
+ type: string
+ description: Name is the artist name.
+ required:
+ - id
+ - name
+ ArtistMBIDResponse:
+ description: ArtistMBIDResponse is the response for GetArtistMBID.
+ properties:
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the artist.
+ required:
+ - mbid
+ ArtistRef:
+ description: ArtistRef is a reference to an artist with name and optional MBID.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID (if known).
+ name:
+ type: string
+ description: Name is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the artist.
+ required:
+ - name
+ ArtistRequest:
+ description: ArtistRequest is the common request for artist-related functions.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID.
+ name:
+ type: string
+ description: Name is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the artist (if known).
+ required:
+ - id
+ - name
+ ArtistURLResponse:
+ description: ArtistURLResponse is the response for GetArtistURL.
+ properties:
+ url:
+ type: string
+ description: URL is the external URL for the artist.
+ required:
+ - url
+ ImageInfo:
+ description: ImageInfo represents an image with URL and size.
+ properties:
+ url:
+ type: string
+ description: URL is the URL of the image.
+ size:
+ type: integer
+ format: int32
+ description: Size is the size of the image in pixels (width or height).
+ required:
+ - url
+ - size
+ SimilarArtistsRequest:
+ description: SimilarArtistsRequest is the request for GetSimilarArtists.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID.
+ name:
+ type: string
+ description: Name is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the artist (if known).
+ limit:
+ type: integer
+ format: int32
+ description: Limit is the maximum number of similar artists to return.
+ required:
+ - id
+ - name
+ - limit
+ SimilarArtistsResponse:
+ description: SimilarArtistsResponse is the response for GetSimilarArtists.
+ properties:
+ artists:
+ type: array
+ description: Artists is the list of similar artists.
+ items:
+ $ref: '#/components/schemas/ArtistRef'
+ required:
+ - artists
+ SimilarSongsByAlbumRequest:
+ description: SimilarSongsByAlbumRequest is the request for GetSimilarSongsByAlbum.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome album ID.
+ name:
+ type: string
+ description: Name is the album name.
+ artist:
+ type: string
+ description: Artist is the album artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz release ID (if known).
+ count:
+ type: integer
+ format: int32
+ description: Count is the maximum number of similar songs to return.
+ required:
+ - id
+ - name
+ - artist
+ - count
+ SimilarSongsByArtistRequest:
+ description: SimilarSongsByArtistRequest is the request for GetSimilarSongsByArtist.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID.
+ name:
+ type: string
+ description: Name is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz artist ID (if known).
+ count:
+ type: integer
+ format: int32
+ description: Count is the maximum number of similar songs to return.
+ required:
+ - id
+ - name
+ - count
+ SimilarSongsByTrackRequest:
+ description: SimilarSongsByTrackRequest is the request for GetSimilarSongsByTrack.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome mediafile ID.
+ name:
+ type: string
+ description: Name is the track title.
+ artist:
+ type: string
+ description: Artist is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz recording ID (if known).
+ count:
+ type: integer
+ format: int32
+ description: Count is the maximum number of similar songs to return.
+ required:
+ - id
+ - name
+ - artist
+ - count
+ SimilarSongsResponse:
+ description: SimilarSongsResponse is the response for GetSimilarSongsBy* functions.
+ properties:
+ songs:
+ type: array
+ description: Songs is the list of similar songs.
+ items:
+ $ref: '#/components/schemas/SongRef'
+ required:
+ - songs
+ SongRef:
+ description: SongRef is a reference to a song with metadata for matching.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome mediafile ID (if known).
+ name:
+ type: string
+ description: Name is the song name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the song.
+ isrc:
+ type: string
+ description: ISRC is the International Standard Recording Code for the song.
+ artist:
+ type: string
+ description: Artist is the artist name.
+ artistMbid:
+ type: string
+ description: ArtistMBID is the MusicBrainz artist ID.
+ album:
+ type: string
+ description: Album is the album name.
+ albumMbid:
+ type: string
+ description: AlbumMBID is the MusicBrainz release ID.
+ duration:
+ type: number
+ format: float
+ description: Duration is the song duration in seconds.
+ required:
+ - name
+ TopSongsRequest:
+ description: TopSongsRequest is the request for GetArtistTopSongs.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID.
+ name:
+ type: string
+ description: Name is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the artist (if known).
+ count:
+ type: integer
+ format: int32
+ description: Count is the maximum number of top songs to return.
+ required:
+ - id
+ - name
+ - count
+ TopSongsResponse:
+ description: TopSongsResponse is the response for GetArtistTopSongs.
+ properties:
+ songs:
+ type: array
+ description: Songs is the list of top songs.
+ items:
+ $ref: '#/components/schemas/SongRef'
+ required:
+ - songs
diff --git a/plugins/capabilities/scheduler_callback.go b/plugins/capabilities/scheduler_callback.go
new file mode 100644
index 000000000..93f66f10d
--- /dev/null
+++ b/plugins/capabilities/scheduler_callback.go
@@ -0,0 +1,27 @@
+package capabilities
+
+// SchedulerCallback provides scheduled task handling.
+// This capability allows plugins to receive callbacks when their scheduled tasks execute.
+// Plugins that use the scheduler host service must implement this capability
+// to handle task execution.
+//
+//nd:capability name=scheduler
+type SchedulerCallback interface {
+ // OnCallback is called when a scheduled task fires.
+ // Errors are logged but do not affect the scheduling system.
+ //nd:export name=nd_scheduler_callback
+ OnCallback(SchedulerCallbackRequest) error
+}
+
+// SchedulerCallbackRequest is the request provided when a scheduled task fires.
+type SchedulerCallbackRequest struct {
+ // ScheduleID is the unique identifier for this scheduled task.
+ // This is either the ID provided when scheduling, or an auto-generated UUID if none was specified.
+ ScheduleID string `json:"scheduleId"`
+ // Payload is the payload data that was provided when the task was scheduled.
+ // Can be used to pass context or parameters to the callback handler.
+ Payload string `json:"payload"`
+ // IsRecurring is true if this is a recurring schedule (created via ScheduleRecurring),
+ // false if it's a one-time schedule (created via ScheduleOneTime).
+ IsRecurring bool `json:"isRecurring"`
+}
diff --git a/plugins/capabilities/scheduler_callback.yaml b/plugins/capabilities/scheduler_callback.yaml
new file mode 100644
index 000000000..9a081cd08
--- /dev/null
+++ b/plugins/capabilities/scheduler_callback.yaml
@@ -0,0 +1,33 @@
+version: v1-draft
+exports:
+ nd_scheduler_callback:
+ description: |-
+ OnCallback is called when a scheduled task fires.
+ Errors are logged but do not affect the scheduling system.
+ input:
+ $ref: '#/components/schemas/SchedulerCallbackRequest'
+ contentType: application/json
+components:
+ schemas:
+ SchedulerCallbackRequest:
+ description: SchedulerCallbackRequest is the request provided when a scheduled task fires.
+ properties:
+ scheduleId:
+ type: string
+ description: |-
+ ScheduleID is the unique identifier for this scheduled task.
+ This is either the ID provided when scheduling, or an auto-generated UUID if none was specified.
+ payload:
+ type: string
+ description: |-
+ Payload is the payload data that was provided when the task was scheduled.
+ Can be used to pass context or parameters to the callback handler.
+ isRecurring:
+ type: boolean
+ description: |-
+ IsRecurring is true if this is a recurring schedule (created via ScheduleRecurring),
+ false if it's a one-time schedule (created via ScheduleOneTime).
+ required:
+ - scheduleId
+ - payload
+ - isRecurring
diff --git a/plugins/capabilities/scrobbler.go b/plugins/capabilities/scrobbler.go
new file mode 100644
index 000000000..8091efe50
--- /dev/null
+++ b/plugins/capabilities/scrobbler.go
@@ -0,0 +1,106 @@
+package capabilities
+
+// Scrobbler provides scrobbling functionality to external services.
+// This capability allows plugins to submit listening history to services like Last.fm,
+// ListenBrainz, or custom scrobbling backends.
+//
+// All methods are required - plugins implementing this capability must provide
+// all three functions: IsAuthorized, NowPlaying, and Scrobble.
+//
+//nd:capability name=scrobbler required=true
+type Scrobbler interface {
+ // IsAuthorized checks if a user is authorized to scrobble to this service.
+ //nd:export name=nd_scrobbler_is_authorized
+ IsAuthorized(IsAuthorizedRequest) (bool, error)
+
+ // NowPlaying sends a now playing notification to the scrobbling service.
+ //nd:export name=nd_scrobbler_now_playing
+ NowPlaying(NowPlayingRequest) error
+
+ // Scrobble submits a completed scrobble to the scrobbling service.
+ //nd:export name=nd_scrobbler_scrobble
+ Scrobble(ScrobbleRequest) error
+}
+
+// IsAuthorizedRequest is the request for authorization check.
+type IsAuthorizedRequest struct {
+ // Username is the username of the user.
+ Username string `json:"username"`
+}
+
+// ArtistRef is a reference to an artist with name and optional MBID.
+type ArtistRef struct {
+ // ID is the internal Navidrome artist ID (if known).
+ ID string `json:"id,omitempty"`
+ // Name is the artist name.
+ Name string `json:"name"`
+ // MBID is the MusicBrainz ID for the artist.
+ MBID string `json:"mbid,omitempty"`
+}
+
+// TrackInfo contains track metadata.
+type TrackInfo struct {
+ // ID is the internal Navidrome track ID.
+ ID string `json:"id"`
+ // Title is the track title.
+ Title string `json:"title"`
+ // Album is the album name.
+ Album string `json:"album"`
+ // Artist is the formatted artist name for display (e.g., "Artist1 • Artist2").
+ Artist string `json:"artist"`
+ // AlbumArtist is the formatted album artist name for display.
+ AlbumArtist string `json:"albumArtist"`
+ // Artists is the list of track artists.
+ Artists []ArtistRef `json:"artists"`
+ // AlbumArtists is the list of album artists.
+ AlbumArtists []ArtistRef `json:"albumArtists"`
+ // Duration is the track duration in seconds.
+ Duration float32 `json:"duration"`
+ // TrackNumber is the track number on the album.
+ TrackNumber int32 `json:"trackNumber"`
+ // DiscNumber is the disc number.
+ DiscNumber int32 `json:"discNumber"`
+ // MBZRecordingID is the MusicBrainz recording ID.
+ MBZRecordingID string `json:"mbzRecordingId,omitempty"`
+ // MBZAlbumID is the MusicBrainz album/release ID.
+ MBZAlbumID string `json:"mbzAlbumId,omitempty"`
+ // MBZReleaseGroupID is the MusicBrainz release group ID.
+ MBZReleaseGroupID string `json:"mbzReleaseGroupId,omitempty"`
+ // MBZReleaseTrackID is the MusicBrainz release track ID.
+ MBZReleaseTrackID string `json:"mbzReleaseTrackId,omitempty"`
+}
+
+// NowPlayingRequest is the request for now playing notification.
+type NowPlayingRequest struct {
+ // Username is the username of the user.
+ Username string `json:"username"`
+ // Track is the track currently playing.
+ Track TrackInfo `json:"track"`
+ // Position is the current playback position in seconds.
+ Position int32 `json:"position"`
+}
+
+// ScrobbleRequest is the request for submitting a scrobble.
+type ScrobbleRequest struct {
+ // Username is the username of the user.
+ Username string `json:"username"`
+ // Track is the track that was played.
+ Track TrackInfo `json:"track"`
+ // Timestamp is the Unix timestamp when the track started playing.
+ Timestamp int64 `json:"timestamp"`
+}
+
+// ScrobblerError represents an error type for scrobbling operations.
+type ScrobblerError string
+
+const (
+ // ScrobblerErrorNotAuthorized indicates the user is not authorized.
+ ScrobblerErrorNotAuthorized ScrobblerError = "scrobbler(not_authorized)"
+ // ScrobblerErrorRetryLater indicates the operation should be retried later.
+ ScrobblerErrorRetryLater ScrobblerError = "scrobbler(retry_later)"
+ // ScrobblerErrorUnrecoverable indicates an unrecoverable error.
+ ScrobblerErrorUnrecoverable ScrobblerError = "scrobbler(unrecoverable)"
+)
+
+// Error implements the error interface for ScrobblerError.
+func (e ScrobblerError) Error() string { return string(e) }
diff --git a/plugins/capabilities/scrobbler.yaml b/plugins/capabilities/scrobbler.yaml
new file mode 100644
index 000000000..5de351a5f
--- /dev/null
+++ b/plugins/capabilities/scrobbler.yaml
@@ -0,0 +1,141 @@
+version: v1-draft
+exports:
+ nd_scrobbler_is_authorized:
+ description: IsAuthorized checks if a user is authorized to scrobble to this service.
+ input:
+ $ref: '#/components/schemas/IsAuthorizedRequest'
+ contentType: application/json
+ output:
+ type: boolean
+ contentType: application/json
+ nd_scrobbler_now_playing:
+ description: NowPlaying sends a now playing notification to the scrobbling service.
+ input:
+ $ref: '#/components/schemas/NowPlayingRequest'
+ contentType: application/json
+ nd_scrobbler_scrobble:
+ description: Scrobble submits a completed scrobble to the scrobbling service.
+ input:
+ $ref: '#/components/schemas/ScrobbleRequest'
+ contentType: application/json
+components:
+ schemas:
+ ArtistRef:
+ description: ArtistRef is a reference to an artist with name and optional MBID.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome artist ID (if known).
+ name:
+ type: string
+ description: Name is the artist name.
+ mbid:
+ type: string
+ description: MBID is the MusicBrainz ID for the artist.
+ required:
+ - name
+ IsAuthorizedRequest:
+ description: IsAuthorizedRequest is the request for authorization check.
+ properties:
+ username:
+ type: string
+ description: Username is the username of the user.
+ required:
+ - username
+ NowPlayingRequest:
+ description: NowPlayingRequest is the request for now playing notification.
+ properties:
+ username:
+ type: string
+ description: Username is the username of the user.
+ track:
+ $ref: '#/components/schemas/TrackInfo'
+ description: Track is the track currently playing.
+ position:
+ type: integer
+ format: int32
+ description: Position is the current playback position in seconds.
+ required:
+ - username
+ - track
+ - position
+ ScrobbleRequest:
+ description: ScrobbleRequest is the request for submitting a scrobble.
+ properties:
+ username:
+ type: string
+ description: Username is the username of the user.
+ track:
+ $ref: '#/components/schemas/TrackInfo'
+ description: Track is the track that was played.
+ timestamp:
+ type: integer
+ format: int64
+ description: Timestamp is the Unix timestamp when the track started playing.
+ required:
+ - username
+ - track
+ - timestamp
+ TrackInfo:
+ description: TrackInfo contains track metadata.
+ properties:
+ id:
+ type: string
+ description: ID is the internal Navidrome track ID.
+ title:
+ type: string
+ description: Title is the track title.
+ album:
+ type: string
+ description: Album is the album name.
+ artist:
+ type: string
+ description: Artist is the formatted artist name for display (e.g., "Artist1 • Artist2").
+ albumArtist:
+ type: string
+ description: AlbumArtist is the formatted album artist name for display.
+ artists:
+ type: array
+ description: Artists is the list of track artists.
+ items:
+ $ref: '#/components/schemas/ArtistRef'
+ albumArtists:
+ type: array
+ description: AlbumArtists is the list of album artists.
+ items:
+ $ref: '#/components/schemas/ArtistRef'
+ duration:
+ type: number
+ format: float
+ description: Duration is the track duration in seconds.
+ trackNumber:
+ type: integer
+ format: int32
+ description: TrackNumber is the track number on the album.
+ discNumber:
+ type: integer
+ format: int32
+ description: DiscNumber is the disc number.
+ mbzRecordingId:
+ type: string
+ description: MBZRecordingID is the MusicBrainz recording ID.
+ mbzAlbumId:
+ type: string
+ description: MBZAlbumID is the MusicBrainz album/release ID.
+ mbzReleaseGroupId:
+ type: string
+ description: MBZReleaseGroupID is the MusicBrainz release group ID.
+ mbzReleaseTrackId:
+ type: string
+ description: MBZReleaseTrackID is the MusicBrainz release track ID.
+ required:
+ - id
+ - title
+ - album
+ - artist
+ - albumArtist
+ - artists
+ - albumArtists
+ - duration
+ - trackNumber
+ - discNumber
diff --git a/plugins/capabilities/taskworker.go b/plugins/capabilities/taskworker.go
new file mode 100644
index 000000000..c53d50174
--- /dev/null
+++ b/plugins/capabilities/taskworker.go
@@ -0,0 +1,27 @@
+package capabilities
+
+// TaskWorker provides task execution handling.
+// This capability allows plugins to receive callbacks when their queued tasks
+// are ready to execute. Plugins that use the taskqueue host service must
+// implement this capability.
+//
+//nd:capability name=taskworker
+type TaskWorker interface {
+ // OnTaskExecute is called when a queued task is ready to run.
+ // The returned string is a status/result message stored in the tasks table.
+ // Return an error to trigger retry (if retries are configured).
+ //nd:export name=nd_task_execute
+ OnTaskExecute(TaskExecuteRequest) (string, error)
+}
+
+// TaskExecuteRequest is the request provided when a task is ready to execute.
+type TaskExecuteRequest struct {
+ // QueueName is the name of the queue this task belongs to.
+ QueueName string `json:"queueName"`
+ // TaskID is the unique identifier for this task.
+ TaskID string `json:"taskId"`
+ // Payload is the opaque data provided when the task was enqueued.
+ Payload []byte `json:"payload"`
+ // Attempt is the current attempt number (1-based: first attempt = 1).
+ Attempt int32 `json:"attempt"`
+}
diff --git a/plugins/capabilities/taskworker.yaml b/plugins/capabilities/taskworker.yaml
new file mode 100644
index 000000000..7aa7126e0
--- /dev/null
+++ b/plugins/capabilities/taskworker.yaml
@@ -0,0 +1,37 @@
+version: v1-draft
+exports:
+ nd_task_execute:
+ description: |-
+ OnTaskExecute is called when a queued task is ready to run.
+ The returned string is a status/result message stored in the tasks table.
+ Return an error to trigger retry (if retries are configured).
+ input:
+ $ref: '#/components/schemas/TaskExecuteRequest'
+ contentType: application/json
+ output:
+ type: string
+ contentType: application/json
+components:
+ schemas:
+ TaskExecuteRequest:
+ description: TaskExecuteRequest is the request provided when a task is ready to execute.
+ properties:
+ queueName:
+ type: string
+ description: QueueName is the name of the queue this task belongs to.
+ taskId:
+ type: string
+ description: TaskID is the unique identifier for this task.
+ payload:
+ type: string
+ format: byte
+ description: Payload is the opaque data provided when the task was enqueued.
+ attempt:
+ type: integer
+ format: int32
+ description: 'Attempt is the current attempt number (1-based: first attempt = 1).'
+ required:
+ - queueName
+ - taskId
+ - payload
+ - attempt
diff --git a/plugins/capabilities/websocket_callback.go b/plugins/capabilities/websocket_callback.go
new file mode 100644
index 000000000..ddfc0fc95
--- /dev/null
+++ b/plugins/capabilities/websocket_callback.go
@@ -0,0 +1,61 @@
+package capabilities
+
+// WebSocketCallback provides WebSocket message handling.
+// This capability allows plugins to receive callbacks for WebSocket events
+// such as text messages, binary messages, errors, and connection closures.
+// Plugins that use the WebSocket host service must implement this capability
+// to handle incoming events.
+//
+//nd:capability name=websocket
+type WebSocketCallback interface {
+ // OnTextMessage is called when a text message is received on a WebSocket connection.
+ //nd:export name=nd_websocket_on_text_message
+ OnTextMessage(OnTextMessageRequest) error
+
+ // OnBinaryMessage is called when a binary message is received on a WebSocket connection.
+ //nd:export name=nd_websocket_on_binary_message
+ OnBinaryMessage(OnBinaryMessageRequest) error
+
+ // OnError is called when an error occurs on a WebSocket connection.
+ //nd:export name=nd_websocket_on_error
+ OnError(OnErrorRequest) error
+
+ // OnClose is called when a WebSocket connection is closed.
+ //nd:export name=nd_websocket_on_close
+ OnClose(OnCloseRequest) error
+}
+
+// OnTextMessageRequest is the request provided when a text message is received.
+type OnTextMessageRequest struct {
+ // ConnectionID is the unique identifier for the WebSocket connection that received the message.
+ ConnectionID string `json:"connectionId"`
+ // Message is the text message content received from the WebSocket.
+ Message string `json:"message"`
+}
+
+// OnBinaryMessageRequest is the request provided when a binary message is received.
+type OnBinaryMessageRequest struct {
+ // ConnectionID is the unique identifier for the WebSocket connection that received the message.
+ ConnectionID string `json:"connectionId"`
+ // Data is the binary data received from the WebSocket, encoded as base64.
+ Data []byte `json:"data"`
+}
+
+// OnErrorRequest is the request provided when an error occurs on a WebSocket connection.
+type OnErrorRequest struct {
+ // ConnectionID is the unique identifier for the WebSocket connection where the error occurred.
+ ConnectionID string `json:"connectionId"`
+ // Error is the error message describing what went wrong.
+ Error string `json:"error"`
+}
+
+// OnCloseRequest is the request provided when a WebSocket connection is closed.
+type OnCloseRequest struct {
+ // ConnectionID is the unique identifier for the WebSocket connection that was closed.
+ ConnectionID string `json:"connectionId"`
+ // Code is the WebSocket close status code (e.g., 1000 for normal closure,
+ // 1001 for going away, 1006 for abnormal closure).
+ Code int32 `json:"code"`
+ // Reason is the human-readable reason for the connection closure, if provided.
+ Reason string `json:"reason"`
+}
diff --git a/plugins/capabilities/websocket_callback.yaml b/plugins/capabilities/websocket_callback.yaml
new file mode 100644
index 000000000..6cd0cff9f
--- /dev/null
+++ b/plugins/capabilities/websocket_callback.yaml
@@ -0,0 +1,80 @@
+version: v1-draft
+exports:
+ nd_websocket_on_text_message:
+ description: OnTextMessage is called when a text message is received on a WebSocket connection.
+ input:
+ $ref: '#/components/schemas/OnTextMessageRequest'
+ contentType: application/json
+ nd_websocket_on_binary_message:
+ description: OnBinaryMessage is called when a binary message is received on a WebSocket connection.
+ input:
+ $ref: '#/components/schemas/OnBinaryMessageRequest'
+ contentType: application/json
+ nd_websocket_on_error:
+ description: OnError is called when an error occurs on a WebSocket connection.
+ input:
+ $ref: '#/components/schemas/OnErrorRequest'
+ contentType: application/json
+ nd_websocket_on_close:
+ description: OnClose is called when a WebSocket connection is closed.
+ input:
+ $ref: '#/components/schemas/OnCloseRequest'
+ contentType: application/json
+components:
+ schemas:
+ OnBinaryMessageRequest:
+ description: OnBinaryMessageRequest is the request provided when a binary message is received.
+ properties:
+ connectionId:
+ type: string
+ description: ConnectionID is the unique identifier for the WebSocket connection that received the message.
+ data:
+ type: string
+ format: byte
+ description: Data is the binary data received from the WebSocket, encoded as base64.
+ required:
+ - connectionId
+ - data
+ OnCloseRequest:
+ description: OnCloseRequest is the request provided when a WebSocket connection is closed.
+ properties:
+ connectionId:
+ type: string
+ description: ConnectionID is the unique identifier for the WebSocket connection that was closed.
+ code:
+ type: integer
+ format: int32
+ description: |-
+ Code is the WebSocket close status code (e.g., 1000 for normal closure,
+ 1001 for going away, 1006 for abnormal closure).
+ reason:
+ type: string
+ description: Reason is the human-readable reason for the connection closure, if provided.
+ required:
+ - connectionId
+ - code
+ - reason
+ OnErrorRequest:
+ description: OnErrorRequest is the request provided when an error occurs on a WebSocket connection.
+ properties:
+ connectionId:
+ type: string
+ description: ConnectionID is the unique identifier for the WebSocket connection where the error occurred.
+ error:
+ type: string
+ description: Error is the error message describing what went wrong.
+ required:
+ - connectionId
+ - error
+ OnTextMessageRequest:
+ description: OnTextMessageRequest is the request provided when a text message is received.
+ properties:
+ connectionId:
+ type: string
+ description: ConnectionID is the unique identifier for the WebSocket connection that received the message.
+ message:
+ type: string
+ description: Message is the text message content received from the WebSocket.
+ required:
+ - connectionId
+ - message
diff --git a/plugins/capabilities_test.go b/plugins/capabilities_test.go
new file mode 100644
index 000000000..35fc3910a
--- /dev/null
+++ b/plugins/capabilities_test.go
@@ -0,0 +1,81 @@
+package plugins
+
+import (
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+// mockFunctionChecker implements functionExistsChecker for testing
+type mockFunctionChecker struct {
+ functions map[string]bool
+}
+
+func (m *mockFunctionChecker) FunctionExists(name string) bool {
+ return m.functions[name]
+}
+
+var _ = Describe("Capabilities", func() {
+ Describe("detectCapabilities", func() {
+ It("detects MetadataAgent capability when plugin exports artist biography function", func() {
+ checker := &mockFunctionChecker{
+ functions: map[string]bool{
+ FuncGetArtistBiography: true,
+ },
+ }
+
+ caps := detectCapabilities(checker)
+ Expect(caps).To(ContainElement(CapabilityMetadataAgent))
+ })
+
+ It("detects MetadataAgent capability when plugin exports multiple functions", func() {
+ checker := &mockFunctionChecker{
+ functions: map[string]bool{
+ FuncGetArtistMBID: true,
+ FuncGetArtistURL: true,
+ FuncGetAlbumInfo: true,
+ FuncGetAlbumImages: true,
+ },
+ }
+
+ caps := detectCapabilities(checker)
+ Expect(caps).To(ContainElement(CapabilityMetadataAgent))
+ Expect(caps).To(HaveLen(1)) // Should only have one MetadataAgent capability
+ })
+
+ It("returns empty slice when no capability functions are exported", func() {
+ checker := &mockFunctionChecker{
+ functions: map[string]bool{
+ "some_other_function": true,
+ },
+ }
+
+ caps := detectCapabilities(checker)
+ Expect(caps).To(BeEmpty())
+ })
+
+ It("returns empty slice when plugin exports no functions", func() {
+ checker := &mockFunctionChecker{
+ functions: map[string]bool{},
+ }
+
+ caps := detectCapabilities(checker)
+ Expect(caps).To(BeEmpty())
+ })
+ })
+
+ Describe("hasCapability", func() {
+ It("returns true when capability exists", func() {
+ caps := []Capability{CapabilityMetadataAgent}
+ Expect(hasCapability(caps, CapabilityMetadataAgent)).To(BeTrue())
+ })
+
+ It("returns false when capability does not exist", func() {
+ var caps []Capability
+ Expect(hasCapability(caps, CapabilityMetadataAgent)).To(BeFalse())
+ })
+
+ It("returns false when capabilities slice is nil", func() {
+ Expect(hasCapability(nil, CapabilityMetadataAgent)).To(BeFalse())
+ })
+ })
+})
diff --git a/plugins/capability_lifecycle.go b/plugins/capability_lifecycle.go
new file mode 100644
index 000000000..499e3916d
--- /dev/null
+++ b/plugins/capability_lifecycle.go
@@ -0,0 +1,38 @@
+package plugins
+
+import (
+ "context"
+
+ "github.com/navidrome/navidrome/log"
+)
+
+// CapabilityLifecycle indicates the plugin has lifecycle callback functions.
+// Detected when the plugin exports the nd_on_init function.
+const CapabilityLifecycle Capability = "Lifecycle"
+
+const FuncOnInit = "nd_on_init"
+
+func init() {
+ registerCapability(
+ CapabilityLifecycle,
+ FuncOnInit,
+ )
+}
+
+// callPluginInit calls the plugin's nd_on_init function if it has the Lifecycle capability.
+// This is called after the plugin is fully loaded with all services registered.
+func callPluginInit(ctx context.Context, instance *plugin) {
+ if !hasCapability(instance.capabilities, CapabilityLifecycle) {
+ return
+ }
+
+ log.Debug(ctx, "Calling plugin init function", "plugin", instance.name)
+
+ err := callPluginFunctionNoInput(ctx, instance, FuncOnInit)
+ if err != nil {
+ log.Error(ctx, "Plugin init function failed", "plugin", instance.name, err)
+ return
+ }
+
+ log.Debug(ctx, "Plugin init function completed", "plugin", instance.name)
+}
diff --git a/plugins/cmd/ndpgen/.gitignore b/plugins/cmd/ndpgen/.gitignore
new file mode 100644
index 000000000..315ccc05f
--- /dev/null
+++ b/plugins/cmd/ndpgen/.gitignore
@@ -0,0 +1 @@
+ndpgen
\ No newline at end of file
diff --git a/plugins/cmd/ndpgen/README.md b/plugins/cmd/ndpgen/README.md
new file mode 100644
index 000000000..d2f67a60c
--- /dev/null
+++ b/plugins/cmd/ndpgen/README.md
@@ -0,0 +1,198 @@
+# ndpgen
+
+Navidrome Plugin Development Kit (PDK) code generator. It reads Go interface definitions with special annotations and generates client wrappers for WASM plugins.
+
+This tool is the unified code generator that handle both host function wrappers and capability wrappers.
+
+## Usage
+
+```bash
+ndpgen -input -output [-package ] [-v] [-dry-run] [-host-only] [-go] [-python] [-rust]
+```
+
+### Flags
+
+| Flag | Description | Default |
+|--------------|----------------------------------------------------------------|----------------------|
+| `-input` | Directory containing Go source files with annotated interfaces | Required |
+| `-output` | Directory where generated files will be written | Same as input |
+| `-package` | Package name for generated files | Inferred from output |
+| `-v` | Verbose output | `false` |
+| `-dry-run` | Parse and validate without writing files | `false` |
+| `-host-only` | Generate only host function wrappers (capability support TBD) | `true` |
+| `-go` | Generate Go client wrappers | `true`* |
+| `-python` | Generate Python client wrappers | `false` |
+| `-rust` | Generate Rust client wrappers | `false` |
+
+\* `-go` is enabled by default when neither `-python` nor `-rust` is specified. Use combinations like `-go -python -rust` to generate multiple languages.
+
+### Example
+
+```bash
+go run ./plugins/cmd/ndpgen \
+ -input ./plugins/host \
+ -output ./plugins/pdk
+```
+
+## Annotations
+
+### `//nd:hostservice`
+
+Marks an interface as a host service that will have wrappers generated.
+
+```go
+//nd:hostservice name= permission=
+type MyService interface { ... }
+```
+
+| Parameter | Description | Required |
+|--------------|-----------------------------------------------------------------|----------|
+| `name` | Service name used in generated type names and function prefixes | Yes |
+| `permission` | Permission required by plugins to use this service | Yes |
+
+### `//nd:hostfunc`
+
+Marks a method within a host service interface for export to plugins.
+
+```go
+//nd:hostfunc [name=]
+MethodName(ctx context.Context, ...) (result Type, err error)
+```
+
+| Parameter | Description | Required |
+|-----------|-------------------------------------------------------------------------|----------|
+| `name` | Custom export name (default: `_` in lowercase) | No |
+
+## Input Format
+
+Host service interfaces must follow these conventions:
+
+1. **First parameter must be `context.Context`** - Required for all methods
+2. **Last return value should be `error`** - For proper error handling
+3. **Annotations must be on consecutive lines** - No blank comment lines between doc and annotation
+
+### Example Interface
+
+```go
+package host
+
+import "context"
+
+// SubsonicAPIService provides access to Navidrome's Subsonic API.
+// This documentation becomes part of the generated code.
+//nd:hostservice name=SubsonicAPI permission=subsonicapi
+type SubsonicAPIService interface {
+ // Call executes a Subsonic API request and returns the response.
+ //nd:hostfunc
+ Call(ctx context.Context, uri string) (response string, err error)
+}
+```
+
+## Generated Output
+
+### Go Client Library (Go/TinyGo WASM)
+
+Generated files are named `nd_host_.go` (lowercase) and placed in `$output/go/host/`. The `$output/go/` directory becomes a complete Go module (`github.com/navidrome/navidrome/plugins/pdk/go`) with package name `host`, intended for import by Navidrome plugins built with TinyGo.
+
+The generator creates:
+- `nd_host_.go` - Client wrapper code (WASM build)
+- `nd_host__stub.go` - Mock implementations for non-WASM platforms (testing)
+- `doc.go` - Package documentation listing all available services
+- `go.mod` - Go module file with required dependencies
+
+Each service file includes:
+
+- `// Code generated by ndpgen. DO NOT EDIT.` header
+- Required imports (`encoding/json`, `errors`, `github.com/extism/go-pdk`)
+- `//go:wasmimport` declarations for each host function
+- Response struct types and any struct definitions from the service
+- Wrapper functions that handle memory allocation and JSON parsing
+
+### Testing Plugins with Mocks
+
+The stub files (`*_stub.go`) contain [testify/mock](https://github.com/stretchr/testify) implementations that allow plugin authors to unit test their code on non-WASM platforms.
+
+Each host service has:
+- A private mock struct embedding `mock.Mock`
+- An exported auto-instantiated mock instance (e.g., `host.CacheMock`, `host.ArtworkMock`)
+- Wrapper functions that delegate to the mock
+
+**Example: Testing a plugin that uses the Cache service**
+
+```go
+package myplugin
+
+import (
+ "testing"
+
+ "github.com/navidrome/navidrome/plugins/pdk/go/host"
+)
+
+func TestMyPluginFunction(t *testing.T) {
+ // Set expectations on the mock
+ host.CacheMock.On("GetString", "my-key").Return("cached-value", true, nil)
+ host.CacheMock.On("SetString", "new-key", "new-value", int64(3600)).Return(nil)
+
+ // Call your plugin code that uses host.CacheGetString and host.CacheSetString
+ result := myPluginFunction()
+
+ // Assert the result
+ if result != "expected" {
+ t.Errorf("unexpected result: %s", result)
+ }
+
+ // Verify all expected calls were made
+ host.CacheMock.AssertExpectations(t)
+}
+```
+
+**Resetting mocks between tests:**
+
+If you need to reset mock state between tests, testify's mock doesn't have a built-in reset. Either use separate test functions (testify automatically resets between test runs), or create a helper to set up fresh expectations.
+
+### Python Client Library
+
+When using `-python`, Python client files are generated in a `python/` subdirectory.
+
+### Rust Client Library
+
+When using `-rust`, Rust client files are generated in a `rust/` subdirectory.
+
+## Supported Types
+
+ndpgen supports these Go types in method signatures:
+
+| Type | JSON Representation |
+|-------------------------------|------------------------------------------|
+| `string`, `int`, `bool`, etc. | Native JSON types |
+| `[]T` (slices) | JSON arrays |
+| `map[K]V` (maps) | JSON objects |
+| `*T` (pointers) | Nullable fields |
+| `interface{}` / `any` | Converts to `any` |
+| Custom structs | JSON objects (must be JSON-serializable) |
+
+### Multiple Return Values
+
+Methods can return multiple values (plus error):
+
+```go
+//nd:hostfunc
+Search(ctx context.Context, query string) (results []string, total int, hasMore bool, err error)
+```
+
+Generates:
+
+```go
+type ServiceSearchResponse struct {
+ Results []string `json:"results,omitempty"`
+ Total int `json:"total,omitempty"`
+ HasMore bool `json:"hasMore,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+```
+
+## Running Tests
+
+```bash
+go test ./plugins/cmd/ndpgen/...
+```
diff --git a/plugins/cmd/ndpgen/go.mod b/plugins/cmd/ndpgen/go.mod
new file mode 100644
index 000000000..af9fce441
--- /dev/null
+++ b/plugins/cmd/ndpgen/go.mod
@@ -0,0 +1,26 @@
+module github.com/navidrome/navidrome/plugins/cmd/ndpgen
+
+go 1.25
+
+require (
+ github.com/extism/go-pdk v1.1.3
+ github.com/onsi/ginkgo/v2 v2.27.5
+ github.com/onsi/gomega v1.39.0
+ github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
+ golang.org/x/tools v0.41.0
+ gopkg.in/yaml.v3 v3.0.1
+)
+
+require (
+ github.com/Masterminds/semver/v3 v3.4.0 // indirect
+ github.com/go-logr/logr v1.4.3 // indirect
+ github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
+ github.com/google/go-cmp v0.7.0 // indirect
+ github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect
+ go.yaml.in/yaml/v3 v3.0.4 // indirect
+ golang.org/x/mod v0.32.0 // indirect
+ golang.org/x/net v0.49.0 // indirect
+ golang.org/x/sync v0.19.0 // indirect
+ golang.org/x/sys v0.40.0 // indirect
+ golang.org/x/text v0.33.0 // indirect
+)
diff --git a/plugins/cmd/ndpgen/go.sum b/plugins/cmd/ndpgen/go.sum
new file mode 100644
index 000000000..952672d0e
--- /dev/null
+++ b/plugins/cmd/ndpgen/go.sum
@@ -0,0 +1,75 @@
+github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
+github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
+github.com/extism/go-pdk v1.1.3 h1:hfViMPWrqjN6u67cIYRALZTZLk/enSPpNKa+rZ9X2SQ=
+github.com/extism/go-pdk v1.1.3/go.mod h1:Gz+LIU/YCKnKXhgge8yo5Yu1F/lbv7KtKFkiCSzW/P4=
+github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs=
+github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo=
+github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M=
+github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk=
+github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE=
+github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc=
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
+github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
+github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
+github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc=
+github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=
+github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE=
+github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo=
+github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg=
+github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE=
+github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A=
+github.com/onsi/ginkgo/v2 v2.27.5 h1:ZeVgZMx2PDMdJm/+w5fE/OyG6ILo1Y3e+QX4zSR0zTE=
+github.com/onsi/ginkgo/v2 v2.27.5/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo=
+github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q=
+github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
+github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
+github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
+github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
+github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
+github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
+github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
+github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
+github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
+github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
+golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
+golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
+golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
+golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
+golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
+golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
+golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
+google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=
+google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/plugins/cmd/ndpgen/integration_test.go b/plugins/cmd/ndpgen/integration_test.go
new file mode 100644
index 000000000..db500c1fc
--- /dev/null
+++ b/plugins/cmd/ndpgen/integration_test.go
@@ -0,0 +1,534 @@
+package main
+
+import (
+ "fmt"
+ "go/format"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+// normalizeGeneratedCode normalizes generated code for comparison with expected output.
+func normalizeGeneratedCode(code string) string {
+ // Replace package names (generated uses ndpdk, testdata may use ndhost)
+ code = strings.ReplaceAll(code, "package ndhost", "package ndpdk")
+ return code
+}
+
+var _ = Describe("ndpgen CLI", Ordered, func() {
+ var (
+ testDir string
+ outputDir string
+ ndpgenBin string
+ )
+
+ BeforeAll(func() {
+ // Set testdata directory (relative to ndpgen root)
+ testdataDir = filepath.Join(mustGetWd(GinkgoT()), "testdata")
+
+ // Build the ndpgen binary
+ ndpgenBin = filepath.Join(os.TempDir(), "ndpgen-test")
+ cmd := exec.Command("go", "build", "-o", ndpgenBin, ".")
+ cmd.Dir = mustGetWd(GinkgoT())
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Failed to build ndpgen: %s", output)
+ DeferCleanup(func() {
+ os.Remove(ndpgenBin)
+ })
+ })
+
+ BeforeEach(func() {
+ var err error
+ testDir, err = os.MkdirTemp("", "ndpgen-test-input-*")
+ Expect(err).ToNot(HaveOccurred())
+ outputDir, err = os.MkdirTemp("", "ndpgen-test-output-*")
+ Expect(err).ToNot(HaveOccurred())
+ })
+
+ AfterEach(func() {
+ os.RemoveAll(testDir)
+ os.RemoveAll(outputDir)
+ })
+
+ Describe("CLI flags and behavior", func() {
+ BeforeEach(func() {
+ serviceCode := `package testpkg
+
+import "context"
+
+//nd:hostservice name=Test permission=test
+type TestService interface {
+ //nd:hostfunc
+ DoAction(ctx context.Context, input string) (output string, err error)
+}
+`
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
+ })
+
+ It("supports verbose mode", func() {
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-v")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ outputStr := string(output)
+ Expect(outputStr).To(ContainSubstring("Input directory:"))
+ Expect(outputStr).To(ContainSubstring("Base output directory:"))
+ Expect(outputStr).To(ContainSubstring("Go output directory:"))
+ Expect(outputStr).To(ContainSubstring("Found 1 host service(s)"))
+ Expect(outputStr).To(ContainSubstring("Generated"))
+ })
+
+ It("supports dry-run mode", func() {
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-dry-run")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ Expect(string(output)).To(ContainSubstring("func TestDoAction("))
+ Expect(filepath.Join(outputDir, "nd_host_test.go")).ToNot(BeAnExistingFile())
+ })
+
+ It("uses default package name 'host'", func() {
+ customOutput, err := os.MkdirTemp("", "mypkg")
+ Expect(err).ToNot(HaveOccurred())
+ defer os.RemoveAll(customOutput)
+
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", customOutput)
+ _, err = cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred())
+
+ // Go code goes to $output/go/host/
+ content, err := os.ReadFile(filepath.Join(customOutput, "go", "host", "nd_host_test.go"))
+ Expect(err).ToNot(HaveOccurred())
+ Expect(string(content)).To(ContainSubstring("package host"))
+ })
+
+ It("returns error for invalid input directory", func() {
+ cmd := exec.Command(ndpgenBin, "-input", "/nonexistent/path")
+ output, err := cmd.CombinedOutput()
+ Expect(err).To(HaveOccurred())
+ Expect(string(output)).To(ContainSubstring("parsing source files"))
+ })
+
+ It("handles no annotated services gracefully", func() {
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte("package testpkg\n"), 0600)).To(Succeed())
+
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-v")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+ Expect(string(output)).To(ContainSubstring("No host services found"))
+ })
+
+ It("generates separate files for multiple services", func() {
+ // Remove service.go created by BeforeEach
+ Expect(os.Remove(filepath.Join(testDir, "service.go"))).To(Succeed())
+
+ service1 := `package testpkg
+import "context"
+//nd:hostservice name=ServiceA permission=a
+type ServiceA interface {
+ //nd:hostfunc
+ MethodA(ctx context.Context) error
+}
+`
+ service2 := `package testpkg
+import "context"
+//nd:hostservice name=ServiceB permission=b
+type ServiceB interface {
+ //nd:hostfunc
+ MethodB(ctx context.Context) error
+}
+`
+ Expect(os.WriteFile(filepath.Join(testDir, "a.go"), []byte(service1), 0600)).To(Succeed())
+ Expect(os.WriteFile(filepath.Join(testDir, "b.go"), []byte(service2), 0600)).To(Succeed())
+
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-v")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+ Expect(string(output)).To(ContainSubstring("Found 2 host service(s)"))
+
+ // Go code goes to $output/go/host/
+ goHostDir := filepath.Join(outputDir, "go", "host")
+ Expect(filepath.Join(goHostDir, "nd_host_servicea.go")).To(BeAnExistingFile())
+ Expect(filepath.Join(goHostDir, "nd_host_serviceb.go")).To(BeAnExistingFile())
+ })
+
+ It("generates Go client code by default", func() {
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ // Go client code goes to $output/go/host/
+ goHostDir := filepath.Join(outputDir, "go", "host")
+ Expect(filepath.Join(goHostDir, "nd_host_test.go")).To(BeAnExistingFile())
+ // Stub file also generated
+ Expect(filepath.Join(goHostDir, "nd_host_test_stub.go")).To(BeAnExistingFile())
+ // doc.go in host dir
+ Expect(filepath.Join(goHostDir, "doc.go")).To(BeAnExistingFile())
+ // go.mod at parent $output/go/ for consolidated module
+ goDir := filepath.Join(outputDir, "go")
+ Expect(filepath.Join(goDir, "go.mod")).To(BeAnExistingFile())
+ })
+ })
+
+ Describe("code generation", func() {
+ DescribeTable("generates correct client output",
+ func(serviceFile, goClientExpectedFile, pyClientExpectedFile, rsClientExpectedFile string) {
+ serviceCode := readTestdata(serviceFile)
+ goClientExpected := readTestdata(goClientExpectedFile)
+ pyClientExpected := readTestdata(pyClientExpectedFile)
+ rsClientExpected := readTestdata(rsClientExpectedFile)
+
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
+
+ // Generate all client code (Go, Python, Rust)
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-go", "-python", "-rust")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ // Verify Go client code (now in $output/go/host/)
+ goHostDir := filepath.Join(outputDir, "go", "host")
+ entries, err := os.ReadDir(goHostDir)
+ Expect(err).ToNot(HaveOccurred())
+
+ var goClientFiles []string
+ for _, e := range entries {
+ if !e.IsDir() &&
+ !strings.HasSuffix(e.Name(), "_stub.go") &&
+ e.Name() != "doc.go" && e.Name() != "go.mod" {
+ goClientFiles = append(goClientFiles, e.Name())
+ }
+ }
+ Expect(goClientFiles).To(HaveLen(1), "Expected exactly one Go client file, got: %v", goClientFiles)
+
+ goClientActual, err := os.ReadFile(filepath.Join(goHostDir, goClientFiles[0]))
+ Expect(err).ToNot(HaveOccurred())
+
+ formattedGoClientActual, err := format.Source(goClientActual)
+ Expect(err).ToNot(HaveOccurred(), "Generated Go client code is not valid Go:\n%s", goClientActual)
+
+ // Normalize expected code to match ndpgen output format
+ normalizedExpected := normalizeGeneratedCode(goClientExpected)
+ formattedGoClientExpected, err := format.Source([]byte(normalizedExpected))
+ Expect(err).ToNot(HaveOccurred(), "Expected Go client code is not valid Go")
+
+ Expect(string(formattedGoClientActual)).To(Equal(string(formattedGoClientExpected)), "Go client code mismatch")
+
+ // Verify Python client code (now in $output/python/host/)
+ pythonHostDir := filepath.Join(outputDir, "python", "host")
+ pyClientEntries, err := os.ReadDir(pythonHostDir)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(pyClientEntries).To(HaveLen(1), "Expected exactly one Python client file")
+
+ pyClientActual, err := os.ReadFile(filepath.Join(pythonHostDir, pyClientEntries[0].Name()))
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(string(pyClientActual)).To(Equal(pyClientExpected), "Python client code mismatch")
+
+ // Verify Rust client code (now in $output/rust/nd-pdk-host/src/)
+ rustSrcDir := filepath.Join(outputDir, "rust", "nd-pdk-host", "src")
+ rsClientEntries, err := os.ReadDir(rustSrcDir)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(rsClientEntries).To(HaveLen(2), "Expected Rust client file and lib.rs in src/")
+
+ // Find the client file (not lib.rs)
+ var rsClientName string
+ for _, entry := range rsClientEntries {
+ if entry.Name() != "lib.rs" {
+ rsClientName = entry.Name()
+ break
+ }
+ }
+ Expect(rsClientName).ToNot(BeEmpty(), "Expected to find Rust client file")
+
+ rsClientActual, err := os.ReadFile(filepath.Join(rustSrcDir, rsClientName))
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(string(rsClientActual)).To(Equal(rsClientExpected), "Rust client code mismatch")
+ },
+
+ Entry("simple string params",
+ "echo_service.go.txt", "echo_client_expected.go.txt", "echo_client_expected.py", "echo_client_expected.rs"),
+
+ Entry("multiple simple params (int32)",
+ "math_service.go.txt", "math_client_expected.go.txt", "math_client_expected.py", "math_client_expected.rs"),
+
+ Entry("struct param with request type",
+ "store_service.go.txt", "store_client_expected.go.txt", "store_client_expected.py", "store_client_expected.rs"),
+
+ Entry("mixed simple and complex params",
+ "list_service.go.txt", "list_client_expected.go.txt", "list_client_expected.py", "list_client_expected.rs"),
+
+ Entry("method without error",
+ "counter_service.go.txt", "counter_client_expected.go.txt", "counter_client_expected.py", "counter_client_expected.rs"),
+
+ Entry("no params, error only",
+ "ping_service.go.txt", "ping_client_expected.go.txt", "ping_client_expected.py", "ping_client_expected.rs"),
+
+ Entry("map and interface types",
+ "meta_service.go.txt", "meta_client_expected.go.txt", "meta_client_expected.py", "meta_client_expected.rs"),
+
+ Entry("pointer types",
+ "users_service.go.txt", "users_client_expected.go.txt", "users_client_expected.py", "users_client_expected.rs"),
+
+ Entry("multiple returns",
+ "search_service.go.txt", "search_client_expected.go.txt", "search_client_expected.py", "search_client_expected.rs"),
+
+ Entry("bytes",
+ "codec_service.go.txt", "codec_client_expected.go.txt", "codec_client_expected.py", "codec_client_expected.rs"),
+
+ Entry("option pattern (value, exists bool)",
+ "config_service.go.txt", "config_client_expected.go.txt", "config_client_expected.py", "config_client_expected.rs"),
+ )
+
+ It("generates compilable client code for comprehensive service", func() {
+ serviceCode := readTestdata("comprehensive_service.go.txt")
+
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
+
+ // Generate client code
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Generation failed: %s", output)
+
+ // Go code goes to $output/go/host/
+ goHostDir := filepath.Join(outputDir, "go", "host")
+
+ // Read generated client code
+ entries, err := os.ReadDir(goHostDir)
+ Expect(err).ToNot(HaveOccurred())
+
+ // Find the client file
+ var clientFileName string
+ for _, entry := range entries {
+ name := entry.Name()
+ if name != "doc.go" && name != "go.mod" && !strings.HasSuffix(name, "_stub.go") && strings.HasSuffix(name, ".go") {
+ clientFileName = name
+ break
+ }
+ }
+ Expect(clientFileName).ToNot(BeEmpty(), "Expected to find Go client file")
+
+ content, err := os.ReadFile(filepath.Join(goHostDir, clientFileName))
+ Expect(err).ToNot(HaveOccurred())
+
+ // Verify key expected content
+ contentStr := string(content)
+ // Should have wasmimport declarations for all methods
+ Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_simpleparams"))
+ Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_structparam"))
+ Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_noerror"))
+ Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_noparams"))
+ Expect(contentStr).To(ContainSubstring("//go:wasmimport extism:host/user comprehensive_noparamsnoreturns"))
+
+ // Should have response types for methods with complex returns (private types in client code)
+ Expect(contentStr).To(ContainSubstring("type comprehensiveSimpleParamsResponse struct"))
+ Expect(contentStr).To(ContainSubstring("type comprehensiveMultipleReturnsResponse struct"))
+
+ // Should have wrapper functions
+ Expect(contentStr).To(ContainSubstring("func ComprehensiveSimpleParams("))
+ Expect(contentStr).To(ContainSubstring("func ComprehensiveNoParams()"))
+ Expect(contentStr).To(ContainSubstring("func ComprehensiveNoParamsNoReturns()"))
+
+ // Create a plugin directory with proper import structure
+ pluginDir := filepath.Join(outputDir, "plugin")
+ Expect(os.MkdirAll(pluginDir, 0750)).To(Succeed())
+
+ // go.mod is at parent $output/go/ for consolidated module
+ goDir := filepath.Join(outputDir, "go")
+
+ // Create go.mod for the plugin that imports the generated library
+ goMod := fmt.Sprintf(`module testplugin
+
+go 1.25
+
+require github.com/navidrome/navidrome/plugins/pdk/go v0.0.0
+
+replace github.com/navidrome/navidrome/plugins/pdk/go => %s
+`, goDir)
+ Expect(os.WriteFile(filepath.Join(pluginDir, "go.mod"), []byte(goMod), 0600)).To(Succeed())
+
+ // Add a simple main function that imports and uses the ndpdk package
+ mainGo := `package main
+
+import ndpdk "github.com/navidrome/navidrome/plugins/pdk/go/host"
+
+func main() {}
+
+// Use some functions to ensure import is not unused
+var _ = ndpdk.ComprehensiveNoParams
+`
+ Expect(os.WriteFile(filepath.Join(pluginDir, "main.go"), []byte(mainGo), 0600)).To(Succeed())
+
+ // Tidy dependencies for the generated go library
+ goTidyLibCmd := exec.Command("go", "mod", "tidy")
+ goTidyLibCmd.Dir = goDir
+ goTidyLibOutput, err := goTidyLibCmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "go mod tidy (library) failed: %s", goTidyLibOutput)
+
+ // Tidy dependencies for the plugin
+ goTidyCmd := exec.Command("go", "mod", "tidy")
+ goTidyCmd.Dir = pluginDir
+ goTidyOutput, err := goTidyCmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "go mod tidy (plugin) failed: %s", goTidyOutput)
+
+ // Build as WASM plugin - this validates the client code compiles correctly
+ buildCmd := exec.Command("go", "build", "-buildmode=c-shared", "-o", "plugin.wasm", ".")
+ buildCmd.Dir = pluginDir
+ buildCmd.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm")
+ buildOutput, err := buildCmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "WASM build failed: %s", buildOutput)
+
+ // Verify .wasm file was created
+ Expect(filepath.Join(pluginDir, "plugin.wasm")).To(BeAnExistingFile())
+ })
+
+ It("generates Python client code with -python flag", func() {
+ serviceCode := `package testpkg
+
+import "context"
+
+//nd:hostservice name=Test permission=test
+type TestService interface {
+ //nd:hostfunc
+ DoAction(ctx context.Context, input string) (output string, err error)
+}
+`
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
+
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-python")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ // Verify Python client code exists in $output/python/host/
+ pythonHostDir := filepath.Join(outputDir, "python", "host")
+ Expect(pythonHostDir).To(BeADirectory())
+
+ pythonFile := filepath.Join(pythonHostDir, "nd_host_test.py")
+ Expect(pythonFile).To(BeAnExistingFile())
+
+ content, err := os.ReadFile(pythonFile)
+ Expect(err).ToNot(HaveOccurred())
+
+ contentStr := string(content)
+ Expect(contentStr).To(ContainSubstring("Code generated by ndpgen. DO NOT EDIT."))
+ Expect(contentStr).To(ContainSubstring("class HostFunctionError(Exception):"))
+ Expect(contentStr).To(ContainSubstring(`@extism.import_fn("extism:host/user", "test_doaction")`))
+ Expect(contentStr).To(ContainSubstring("def test_do_action(input: str) -> str:"))
+ })
+
+ It("generates both Go and Python client code with -go -python flags", func() {
+ serviceCode := `package testpkg
+
+import "context"
+
+//nd:hostservice name=Test permission=test
+type TestService interface {
+ //nd:hostfunc
+ DoAction(ctx context.Context, input string) (output string, err error)
+}
+`
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
+
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-go", "-python")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ // Verify Go client code exists in $output/go/host/
+ goHostDir := filepath.Join(outputDir, "go", "host")
+ Expect(filepath.Join(goHostDir, "nd_host_test.go")).To(BeAnExistingFile())
+
+ // Verify Python client code exists in $output/python/host/
+ pythonHostDir := filepath.Join(outputDir, "python", "host")
+ Expect(pythonHostDir).To(BeADirectory())
+ Expect(filepath.Join(pythonHostDir, "nd_host_test.py")).To(BeAnExistingFile())
+ })
+
+ It("generates Python code with dataclass for multi-value returns", func() {
+ serviceCode := `package testpkg
+
+import "context"
+
+//nd:hostservice name=Cache permission=cache
+type CacheService interface {
+ //nd:hostfunc
+ GetString(ctx context.Context, key string) (value string, exists bool, err error)
+}
+`
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
+
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-python")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ content, err := os.ReadFile(filepath.Join(outputDir, "python", "host", "nd_host_cache.py"))
+ Expect(err).ToNot(HaveOccurred())
+
+ contentStr := string(content)
+ Expect(contentStr).To(ContainSubstring("@dataclass"))
+ Expect(contentStr).To(ContainSubstring("class CacheGetStringResult:"))
+ Expect(contentStr).To(ContainSubstring("value: str"))
+ Expect(contentStr).To(ContainSubstring("exists: bool"))
+ Expect(contentStr).To(ContainSubstring("def cache_get_string(key: str) -> CacheGetStringResult:"))
+ })
+
+ It("generates Python code for methods with no parameters", func() {
+ serviceCode := `package testpkg
+
+import "context"
+
+//nd:hostservice name=Test permission=test
+type TestService interface {
+ //nd:hostfunc
+ Ping(ctx context.Context) (status string, err error)
+}
+`
+ Expect(os.WriteFile(filepath.Join(testDir, "service.go"), []byte(serviceCode), 0600)).To(Succeed())
+
+ cmd := exec.Command(ndpgenBin, "-input", testDir, "-output", outputDir, "-package", "ndpdk", "-python")
+ output, err := cmd.CombinedOutput()
+ Expect(err).ToNot(HaveOccurred(), "Command failed: %s", output)
+
+ content, err := os.ReadFile(filepath.Join(outputDir, "python", "host", "nd_host_test.py"))
+ Expect(err).ToNot(HaveOccurred())
+
+ contentStr := string(content)
+ Expect(contentStr).To(ContainSubstring("def test_ping() -> str:"))
+ Expect(contentStr).To(ContainSubstring(`request_bytes = b"{}"`))
+ })
+ })
+})
+
+var testdataDir string
+
+func readTestdata(filename string) string {
+ content, err := os.ReadFile(filepath.Join(testdataDir, filename))
+ Expect(err).ToNot(HaveOccurred(), "Failed to read testdata file: %s", filename)
+ return string(content)
+}
+
+func mustGetWd(t FullGinkgoTInterface) string {
+ dir, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Look for ndpgen's own go.mod (the subproject root)
+ for {
+ goModPath := filepath.Join(dir, "go.mod")
+ if _, err := os.Stat(goModPath); err == nil {
+ // Check if this is the ndpgen go.mod by reading it
+ content, err := os.ReadFile(goModPath)
+ if err == nil && strings.Contains(string(content), "plugins/cmd/ndpgen") {
+ return dir
+ }
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ t.Fatal("could not find ndpgen project root")
+ }
+ dir = parent
+ }
+}
diff --git a/plugins/cmd/ndpgen/internal/generator.go b/plugins/cmd/ndpgen/internal/generator.go
new file mode 100644
index 000000000..705cd4d36
--- /dev/null
+++ b/plugins/cmd/ndpgen/internal/generator.go
@@ -0,0 +1,889 @@
+package internal
+
+import (
+ "bytes"
+ "embed"
+ "fmt"
+ "strings"
+ "text/template"
+)
+
+//go:embed templates/*.tmpl
+var templatesFS embed.FS
+
+// hostFuncMap returns the template functions for host code generation.
+func hostFuncMap(svc Service) template.FuncMap {
+ return template.FuncMap{
+ "lower": strings.ToLower,
+ "title": strings.Title,
+ "exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
+ "requestType": func(m Method) string { return m.RequestTypeName(svc.Name) },
+ "responseType": func(m Method) string { return m.ResponseTypeName(svc.Name) },
+ }
+}
+
+// clientFuncMap returns the template functions for client code generation.
+// Uses private (lowercase) type names for request/response structs.
+func clientFuncMap(svc Service) template.FuncMap {
+ return template.FuncMap{
+ "lower": strings.ToLower,
+ "title": strings.Title,
+ "exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
+ "requestType": func(m Method) string { return m.ClientRequestTypeName(svc.Name) },
+ "responseType": func(m Method) string { return m.ClientResponseTypeName(svc.Name) },
+ "formatDoc": formatDoc,
+ "mockReturnValues": mockReturnValues,
+ }
+}
+
+// mockReturnValues generates the testify mock return value accessors for a method.
+// For example: args.String(0), args.Bool(1), args.Error(2)
+func mockReturnValues(m Method) string {
+ var parts []string
+ idx := 0
+
+ for _, r := range m.Returns {
+ parts = append(parts, mockAccessor(r.Type, idx))
+ idx++
+ }
+
+ if m.HasError {
+ parts = append(parts, fmt.Sprintf("args.Error(%d)", idx))
+ }
+
+ return strings.Join(parts, ", ")
+}
+
+// mockAccessor returns the testify mock accessor call for a given type and index.
+func mockAccessor(typ string, idx int) string {
+ switch {
+ case typ == "string":
+ return fmt.Sprintf("args.String(%d)", idx)
+ case typ == "bool":
+ return fmt.Sprintf("args.Bool(%d)", idx)
+ case typ == "int":
+ return fmt.Sprintf("args.Int(%d)", idx)
+ case typ == "int64":
+ return fmt.Sprintf("args.Get(%d).(int64)", idx)
+ case typ == "int32":
+ return fmt.Sprintf("args.Get(%d).(int32)", idx)
+ case typ == "float64":
+ return fmt.Sprintf("args.Get(%d).(float64)", idx)
+ case typ == "float32":
+ return fmt.Sprintf("args.Get(%d).(float32)", idx)
+ case typ == "[]byte":
+ return fmt.Sprintf("args.Get(%d).([]byte)", idx)
+ default:
+ // For slices, maps, pointers, and custom types, use Get with type assertion
+ return fmt.Sprintf("args.Get(%d).(%s)", idx, typ)
+ }
+}
+
+// pythonFuncMap returns the template functions for Python client code generation.
+func pythonFuncMap(svc Service) template.FuncMap {
+ return template.FuncMap{
+ "lower": strings.ToLower,
+ "exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
+ "pythonFunc": func(m Method) string { return m.PythonFunctionName(svc.ExportPrefix()) },
+ "pythonResultType": func(m Method) string { return m.PythonResultTypeName(svc.Name) },
+ "pythonDefault": pythonDefaultValue,
+ }
+}
+
+// GenerateHost generates the host function wrapper code for a service.
+func GenerateHost(svc Service, pkgName string) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/host.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading host template: %w", err)
+ }
+
+ tmpl, err := template.New("host").Funcs(hostFuncMap(svc)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := templateData{
+ Package: pkgName,
+ Service: svc,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GenerateClientGo generates client wrapper code for plugins to call host functions.
+func GenerateClientGo(svc Service, pkgName string) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/client.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading client template: %w", err)
+ }
+
+ tmpl, err := template.New("client").Funcs(clientFuncMap(svc)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := templateData{
+ Package: pkgName,
+ Service: svc,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GenerateClientGoStub generates stub code for non-WASM platforms.
+// These stubs provide type definitions and function signatures for IDE support,
+// but panic at runtime since host functions are only available in WASM plugins.
+func GenerateClientGoStub(svc Service, pkgName string) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/client_stub.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading client stub template: %w", err)
+ }
+
+ tmpl, err := template.New("client_stub").Funcs(clientFuncMap(svc)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := templateData{
+ Package: pkgName,
+ Service: svc,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+type templateData struct {
+ Package string
+ Service Service
+}
+
+// formatDoc formats a documentation string for Go comments.
+// It prefixes each line with "// " and trims trailing whitespace.
+func formatDoc(doc string) string {
+ if doc == "" {
+ return ""
+ }
+ lines := strings.Split(strings.TrimSpace(doc), "\n")
+ var result []string
+ for _, line := range lines {
+ result = append(result, "// "+strings.TrimRight(line, " \t"))
+ }
+ return strings.Join(result, "\n")
+}
+
+// GenerateClientPython generates Python client wrapper code for plugins.
+func GenerateClientPython(svc Service) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/client.py.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading Python client template: %w", err)
+ }
+
+ tmpl, err := template.New("client_py").Funcs(pythonFuncMap(svc)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := templateData{
+ Service: svc,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// pythonDefaultValue returns a Python default value for response.get() calls.
+func pythonDefaultValue(p Param) string {
+ switch p.Type {
+ case "string":
+ return `, ""`
+ case "int", "int32", "int64":
+ return ", 0"
+ case "float32", "float64":
+ return ", 0.0"
+ case "bool":
+ return ", False"
+ case "[]byte":
+ return ", b\"\""
+ default:
+ return ", None"
+ }
+}
+
+// rustFuncMap returns the template functions for Rust client code generation.
+func rustFuncMap(svc Service) template.FuncMap {
+ knownStructs := svc.KnownStructs()
+ return template.FuncMap{
+ "lower": strings.ToLower,
+ "exportName": func(m Method) string { return m.FunctionName(svc.ExportPrefix()) },
+ "requestType": func(m Method) string { return m.RequestTypeName(svc.Name) },
+ "responseType": func(m Method) string { return m.ResponseTypeName(svc.Name) },
+ "rustFunc": func(m Method) string { return m.RustFunctionName(svc.ExportPrefix()) },
+ "rustDocComment": RustDocComment,
+ "rustType": func(p Param) string { return p.RustTypeWithStructs(knownStructs) },
+ "rustParamType": func(p Param) string { return p.RustParamTypeWithStructs(knownStructs) },
+ "fieldRustType": func(f FieldDef) string { return f.RustType(knownStructs) },
+ }
+}
+
+// GenerateClientRust generates Rust client wrapper code for plugins.
+func GenerateClientRust(svc Service) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/client.rs.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading Rust client template: %w", err)
+ }
+
+ tmpl, err := template.New("client_rs").Funcs(rustFuncMap(svc)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ partialContent, err := templatesFS.ReadFile("templates/base64_bytes.rs.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading base64_bytes partial: %w", err)
+ }
+ tmpl, err = tmpl.Parse(string(partialContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing base64_bytes partial: %w", err)
+ }
+
+ data := templateData{
+ Service: svc,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// firstLine returns the first line of a multi-line string, with the first word removed.
+func firstLine(s string) string {
+ line := s
+ if idx := strings.Index(s, "\n"); idx >= 0 {
+ line = s[:idx]
+ }
+ // Remove the first word (service name like "ArtworkService")
+ if idx := strings.Index(line, " "); idx >= 0 {
+ line = line[idx+1:]
+ }
+ return line
+}
+
+// GenerateRustLib generates the lib.rs file that exposes all service modules.
+func GenerateRustLib(services []Service) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/lib.rs.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading Rust lib template: %w", err)
+ }
+
+ tmpl, err := template.New("lib_rs").Funcs(template.FuncMap{
+ "lower": strings.ToLower,
+ "firstLine": firstLine,
+ }).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := struct {
+ Services []Service
+ }{
+ Services: services,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GenerateGoDoc generates the doc.go file that provides package documentation.
+func GenerateGoDoc(services []Service, pkgName string) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/doc.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading Go doc template: %w", err)
+ }
+
+ tmpl, err := template.New("doc_go").Funcs(template.FuncMap{
+ "firstLine": firstLine,
+ }).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := struct {
+ Package string
+ Services []Service
+ }{
+ Package: pkgName,
+ Services: services,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GenerateGoMod generates the go.mod file for the Go client library.
+func GenerateGoMod() ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/go.mod.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading go.mod template: %w", err)
+ }
+ return tmplContent, nil
+}
+
+// capabilityTemplateData holds data for capability template execution.
+type capabilityTemplateData struct {
+ Package string
+ Capability Capability
+}
+
+// capabilityFuncMap returns template functions for capability code generation.
+func capabilityFuncMap(cap Capability) template.FuncMap {
+ return template.FuncMap{
+ "formatDoc": formatDoc,
+ "indent": indentText,
+ "agentName": capabilityAgentName,
+ "providerInterface": func(e Export) string { return e.ProviderInterfaceName() },
+ "implVar": func(e Export) string { return e.ImplVarName() },
+ "exportFunc": func(e Export) string { return e.ExportFuncName() },
+ }
+}
+
+// indentText adds n tabs to each line of text.
+func indentText(n int, s string) string {
+ indent := strings.Repeat("\t", n)
+ lines := strings.Split(s, "\n")
+ for i, line := range lines {
+ if line != "" {
+ lines[i] = indent + line
+ }
+ }
+ return strings.Join(lines, "\n")
+}
+
+// capabilityAgentName returns the interface name for a capability.
+// Uses the Go interface name stripped of common suffixes.
+func capabilityAgentName(cap Capability) string {
+ name := cap.Interface
+ // Remove common suffixes to get a clean name
+ for _, suffix := range []string{"Agent", "Callback", "Service"} {
+ if strings.HasSuffix(name, suffix) {
+ name = name[:len(name)-len(suffix)]
+ break
+ }
+ }
+ // Use the shortened name or the original if no suffix found
+ if name == "" {
+ name = cap.Interface
+ }
+ return name
+}
+
+// GenerateCapabilityGo generates Go export wrapper code for a capability.
+func GenerateCapabilityGo(cap Capability, pkgName string) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/capability.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading capability template: %w", err)
+ }
+
+ tmpl, err := template.New("capability").Funcs(capabilityFuncMap(cap)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := capabilityTemplateData{
+ Package: pkgName,
+ Capability: cap,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GenerateCapabilityGoStub generates stub code for non-WASM platforms.
+func GenerateCapabilityGoStub(cap Capability, pkgName string) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/capability_stub.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading capability stub template: %w", err)
+ }
+
+ tmpl, err := template.New("capability_stub").Funcs(capabilityFuncMap(cap)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ data := capabilityTemplateData{
+ Package: pkgName,
+ Capability: cap,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// rustCapabilityFuncMap returns template functions for Rust capability code generation.
+func rustCapabilityFuncMap(cap Capability) template.FuncMap {
+ knownStructs := cap.KnownStructs()
+ return template.FuncMap{
+ "rustDocComment": RustDocComment,
+ "rustTypeAlias": rustTypeAlias,
+ "rustConstType": rustConstType,
+ "rustConstName": rustConstName,
+ "rustFieldName": func(name string) string { return ToSnakeCase(name) },
+ "rustMethodName": func(name string) string { return ToSnakeCase(name) },
+ "fieldRustType": func(f FieldDef) string { return f.RustType(knownStructs) },
+ "rustOutputType": rustOutputType,
+ "isPrimitiveRust": isPrimitiveRustType,
+ "skipSerializingFunc": skipSerializingFunc,
+ "hasHashMap": hasHashMap,
+ "agentName": capabilityAgentName,
+ "providerInterface": func(e Export) string { return e.ProviderInterfaceName() },
+ "registerMacroName": func(name string) string { return registerMacroName(cap.Name, name) },
+ "snakeCase": ToSnakeCase,
+ "indent": func(spaces int, s string) string {
+ indent := strings.Repeat(" ", spaces)
+ lines := strings.Split(s, "\n")
+ for i, line := range lines {
+ if line != "" {
+ lines[i] = indent + line
+ }
+ }
+ return strings.Join(lines, "\n")
+ },
+ }
+}
+
+// rustTypeAlias converts a Go type to its Rust equivalent for type aliases.
+// For string types used as error sentinels/constants, we use &'static str
+// since Rust consts can't be heap-allocated String values.
+func rustTypeAlias(goType string) string {
+ switch goType {
+ case "string":
+ return "&'static str"
+ case "int", "int32":
+ return "i32"
+ case "int64":
+ return "i64"
+ default:
+ return goType
+ }
+}
+
+// rustConstType converts a Go type to its Rust equivalent for const declarations.
+// For String types, it returns &'static str since Rust consts can't be heap-allocated.
+func rustConstType(goType string) string {
+ switch goType {
+ case "string", "String":
+ return "&'static str"
+ case "int", "int32":
+ return "i32"
+ case "int64":
+ return "i64"
+ default:
+ return goType
+ }
+}
+
+// rustOutputType converts a Go type to Rust for capability method signatures.
+// It handles pointer types specially - for capability outputs, pointers become the base type
+// (not Option) because Rust's Result already provides optional semantics.
+//
+// TODO: Pointer to primitive types (e.g., *string, *int32) are not handled correctly.
+// Currently "*string" returns "string" instead of "String". This would generate invalid
+// Rust code. No current capability uses this pattern, but it should be fixed if needed.
+func rustOutputType(goType string) string {
+ // Strip pointer prefix - capability outputs use Result for optionality
+ if strings.HasPrefix(goType, "*") {
+ return goType[1:]
+ }
+ // Convert Go primitives to Rust primitives
+ switch goType {
+ case "bool":
+ return "bool"
+ case "string":
+ return "String"
+ case "int", "int32":
+ return "i32"
+ case "int64":
+ return "i64"
+ case "float32":
+ return "f32"
+ case "float64":
+ return "f64"
+ }
+ return goType
+}
+
+// isPrimitiveRustType returns true if the Go type maps to a Rust primitive type.
+func isPrimitiveRustType(goType string) bool {
+ // Strip pointer prefix first
+ if strings.HasPrefix(goType, "*") {
+ goType = goType[1:]
+ }
+ switch goType {
+ case "bool", "string", "int", "int32", "int64", "float32", "float64":
+ return true
+ }
+ return false
+}
+
+// rustConstName converts a Go const name to Rust convention (SCREAMING_SNAKE_CASE).
+func rustConstName(name string) string {
+ return strings.ToUpper(ToSnakeCase(name))
+}
+
+// skipSerializingFunc returns the appropriate skip_serializing_if function name.
+func skipSerializingFunc(goType string) string {
+ if strings.HasPrefix(goType, "*") || strings.HasPrefix(goType, "[]") || strings.HasPrefix(goType, "map[") {
+ return "Option::is_none"
+ }
+ switch goType {
+ case "string":
+ return "String::is_empty"
+ case "bool":
+ return "std::ops::Not::not"
+ case "int32":
+ return "is_zero_i32"
+ case "uint32":
+ return "is_zero_u32"
+ case "int64":
+ return "is_zero_i64"
+ case "uint64":
+ return "is_zero_u64"
+ case "float32":
+ return "is_zero_f32"
+ case "float64":
+ return "is_zero_f64"
+ default:
+ return "Option::is_none"
+ }
+}
+
+// hasHashMap returns true if any struct in the capability uses HashMap.
+func hasHashMap(cap Capability) bool {
+ for _, st := range cap.Structs {
+ for _, f := range st.Fields {
+ if strings.HasPrefix(f.Type, "map[") {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// registerMacroName returns the macro name for registering an optional method.
+// For package "websocket" and method "OnClose", returns "register_websocket_close".
+func registerMacroName(pkg, name string) string {
+ // Remove common prefixes from method name
+ for _, prefix := range []string{"Get", "On"} {
+ if strings.HasPrefix(name, prefix) {
+ name = name[len(prefix):]
+ break
+ }
+ }
+ return "register_" + ToSnakeCase(pkg) + "_" + ToSnakeCase(name)
+}
+
+// GenerateCapabilityRust generates Rust export wrapper code for a capability.
+func GenerateCapabilityRust(cap Capability) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/capability.rs.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading Rust capability template: %w", err)
+ }
+
+ tmpl, err := template.New("capability_rust").Funcs(rustCapabilityFuncMap(cap)).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ partialContent, err := templatesFS.ReadFile("templates/base64_bytes.rs.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading base64_bytes partial: %w", err)
+ }
+ tmpl, err = tmpl.Parse(string(partialContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing base64_bytes partial: %w", err)
+ }
+
+ data := capabilityTemplateData{
+ Package: cap.Name,
+ Capability: cap,
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, data); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GenerateCapabilityRustLib generates the lib.rs file for the Rust capabilities crate.
+func GenerateCapabilityRustLib(capabilities []Capability) ([]byte, error) {
+ var buf bytes.Buffer
+ buf.WriteString("// Code generated by ndpgen. DO NOT EDIT.\n\n")
+ buf.WriteString("//! Navidrome Plugin Development Kit - Capability Wrappers\n")
+ buf.WriteString("//!\n")
+ buf.WriteString("//! This crate provides type definitions, traits, and registration macros\n")
+ buf.WriteString("//! for implementing Navidrome plugin capabilities in Rust.\n\n")
+
+ // Module declarations
+ for _, cap := range capabilities {
+ moduleName := ToSnakeCase(cap.Name)
+ buf.WriteString(fmt.Sprintf("pub mod %s;\n", moduleName))
+ }
+
+ return buf.Bytes(), nil
+}
+
+// pdkFuncMap returns the template functions for PDK code generation.
+func pdkFuncMap() template.FuncMap {
+ return template.FuncMap{
+ "firstSentence": firstSentence,
+ "paramList": pdkParamList,
+ "returnList": pdkReturnList,
+ "argList": pdkArgList,
+ "argListWithReceiver": pdkArgListWithReceiver,
+ "mockReturns": pdkMockReturns,
+ "constValue": pdkConstValue,
+ "stubTypeUnderlying": stubTypeUnderlying,
+ "methodReceiver": pdkMethodReceiver,
+ }
+}
+
+// stubTypeUnderlying returns the appropriate stub type for non-WASM builds.
+// For types that reference internal packages (like memory.Memory), returns "struct{}".
+func stubTypeUnderlying(t PDKType) string {
+ underlying := t.Underlying
+ // If the underlying type references a package (contains a dot), use a stub struct
+ if strings.Contains(underlying, ".") {
+ return "struct{}"
+ }
+ // For simple types like int, int32, return as-is
+ return underlying
+}
+
+// firstSentence returns the first sentence of a doc string, normalized to a single line.
+func firstSentence(doc string) string {
+ if doc == "" {
+ return ""
+ }
+ // Normalize whitespace (replace newlines with spaces, collapse multiple spaces)
+ doc = strings.Join(strings.Fields(doc), " ")
+
+ // Find first period followed by space or end
+ for i, r := range doc {
+ if r == '.' && (i+1 >= len(doc) || doc[i+1] == ' ') {
+ return doc[:i+1]
+ }
+ }
+ return doc
+}
+
+// pdkParamList generates a parameter list string for function signature.
+func pdkParamList(params []PDKParam) string {
+ var parts []string
+ for _, p := range params {
+ if p.Name != "" {
+ parts = append(parts, p.Name+" "+p.Type)
+ } else {
+ parts = append(parts, p.Type)
+ }
+ }
+ return strings.Join(parts, ", ")
+}
+
+// pdkReturnList generates a return list string for function signature.
+func pdkReturnList(returns []PDKReturn) string {
+ if len(returns) == 0 {
+ return ""
+ }
+ if len(returns) == 1 && returns[0].Name == "" {
+ return " " + returns[0].Type
+ }
+ var parts []string
+ for _, r := range returns {
+ if r.Name != "" {
+ parts = append(parts, r.Name+" "+r.Type)
+ } else {
+ parts = append(parts, r.Type)
+ }
+ }
+ return " (" + strings.Join(parts, ", ") + ")"
+}
+
+// pdkArgList generates an argument list string for function call.
+func pdkArgList(params []PDKParam) string {
+ var parts []string
+ for _, p := range params {
+ if p.Name != "" {
+ parts = append(parts, p.Name)
+ } else {
+ parts = append(parts, "_")
+ }
+ }
+ return strings.Join(parts, ", ")
+}
+
+// pdkArgListWithReceiver generates an argument list that includes the receiver variable
+// as the first argument to PDKMock.Called(). This allows tests to verify which instance
+// a method was called on.
+func pdkArgListWithReceiver(params []PDKParam, typeName string) string {
+ // Use lowercase first letter of type name as receiver variable
+ receiverVar := strings.ToLower(typeName[:1])
+ parts := []string{receiverVar}
+ for _, p := range params {
+ if p.Name != "" {
+ parts = append(parts, p.Name)
+ } else {
+ parts = append(parts, "_")
+ }
+ }
+ return strings.Join(parts, ", ")
+}
+
+// pdkMethodReceiver generates the receiver declaration for a method.
+// Example: "r *HTTPRequest" or "m Memory"
+func pdkMethodReceiver(receiver, typeName string) string {
+ receiverVar := strings.ToLower(typeName[:1])
+ if strings.HasPrefix(receiver, "*") {
+ return receiverVar + " *" + typeName
+ }
+ return receiverVar + " " + typeName
+}
+
+// pdkMockReturns generates the mock return accessors for a function.
+func pdkMockReturns(returns []PDKReturn) string {
+ var parts []string
+ for i, r := range returns {
+ parts = append(parts, mockAccessorForType(r.Type, i))
+ }
+ return strings.Join(parts, ", ")
+}
+
+// mockAccessorForType returns the testify mock accessor for a type.
+func mockAccessorForType(typ string, idx int) string {
+ switch typ {
+ case "string":
+ return fmt.Sprintf("args.String(%d)", idx)
+ case "bool":
+ return fmt.Sprintf("args.Bool(%d)", idx)
+ case "int":
+ return fmt.Sprintf("args.Int(%d)", idx)
+ case "error":
+ return fmt.Sprintf("args.Error(%d)", idx)
+ case "[]byte":
+ return fmt.Sprintf("args.Get(%d).([]byte)", idx)
+ case "uint64":
+ return fmt.Sprintf("args.Get(%d).(uint64)", idx)
+ case "uint32":
+ return fmt.Sprintf("args.Get(%d).(uint32)", idx)
+ case "uint16":
+ return fmt.Sprintf("args.Get(%d).(uint16)", idx)
+ default:
+ return fmt.Sprintf("args.Get(%d).(%s)", idx, typ)
+ }
+}
+
+// pdkConstValue returns the value expression for a constant.
+func pdkConstValue(c PDKConst) string {
+ if c.Value == "" || c.Value == "iota" {
+ return "iota"
+ }
+ return c.Value
+}
+
+// GeneratePDKGo generates the WASM implementation of the PDK wrapper package.
+func GeneratePDKGo(symbols *PDKSymbols) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/pdk.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading pdk template: %w", err)
+ }
+
+ tmpl, err := template.New("pdk").Funcs(pdkFuncMap()).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, symbols); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GeneratePDKGoStub generates the native stub implementation of the PDK wrapper package.
+func GeneratePDKGoStub(symbols *PDKSymbols) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/pdk_stub.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading pdk stub template: %w", err)
+ }
+
+ tmpl, err := template.New("pdk_stub").Funcs(pdkFuncMap()).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, symbols); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// GeneratePDKTypesStub generates the native type definitions for the PDK wrapper package.
+func GeneratePDKTypesStub(symbols *PDKSymbols) ([]byte, error) {
+ tmplContent, err := templatesFS.ReadFile("templates/types_stub.go.tmpl")
+ if err != nil {
+ return nil, fmt.Errorf("reading types stub template: %w", err)
+ }
+
+ tmpl, err := template.New("types_stub").Funcs(pdkFuncMap()).Parse(string(tmplContent))
+ if err != nil {
+ return nil, fmt.Errorf("parsing template: %w", err)
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, symbols); err != nil {
+ return nil, fmt.Errorf("executing template: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
diff --git a/plugins/cmd/ndpgen/internal/generator_test.go b/plugins/cmd/ndpgen/internal/generator_test.go
new file mode 100644
index 000000000..34c2c2886
--- /dev/null
+++ b/plugins/cmd/ndpgen/internal/generator_test.go
@@ -0,0 +1,1664 @@
+package internal
+
+import (
+ "go/format"
+ "os"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Generator", func() {
+ Describe("GenerateHost", func() {
+ It("should generate valid Go code for a simple service with strings", func() {
+ // All methods use JSON request/response types
+ svc := Service{
+ Name: "SubsonicAPI",
+ Permission: "subsonicapi",
+ Interface: "SubsonicAPIService",
+ Methods: []Method{
+ {
+ Name: "Call",
+ HasError: true,
+ Params: []Param{NewParam("uri", "string")},
+ Returns: []Param{NewParam("response", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ // Verify the code is valid Go
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for generated header
+ Expect(codeStr).To(ContainSubstring("Code generated by ndpgen. DO NOT EDIT."))
+
+ // Check for package declaration
+ Expect(codeStr).To(ContainSubstring("package host"))
+
+ // All methods now use request type for JSON protocol
+ Expect(codeStr).To(ContainSubstring("type SubsonicAPICallRequest struct"))
+ Expect(codeStr).To(ContainSubstring(`Uri string `))
+
+ // Response type with error handling
+ Expect(codeStr).To(ContainSubstring("type SubsonicAPICallResponse struct"))
+ Expect(codeStr).To(ContainSubstring(`Response string `))
+ Expect(codeStr).To(ContainSubstring(`Error string `))
+
+ // Check for registration function
+ Expect(codeStr).To(ContainSubstring("func RegisterSubsonicAPIHostFunctions(service SubsonicAPIService)"))
+
+ // Check for host function name
+ Expect(codeStr).To(ContainSubstring(`"subsonicapi_call"`))
+
+ // Check for JSON unmarshal (all methods use JSON now)
+ Expect(codeStr).To(ContainSubstring("json.Unmarshal"))
+ })
+
+ It("should generate code for methods without parameters", func() {
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "NoParams",
+ HasError: true,
+ Returns: []Param{NewParam("result", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ // Methods without params don't need a request type - no params to serialize
+ Expect(codeStr).NotTo(ContainSubstring("type TestNoParamsRequest struct"))
+ // But still uses PTR input/output for consistency
+ Expect(codeStr).To(MatchRegexp(`\[\]extism\.ValueType\{extism\.ValueTypePTR\},\s*\[\]extism\.ValueType\{extism\.ValueTypePTR\}`))
+ })
+
+ It("should generate code for methods without return values", func() {
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "NoReturn",
+ HasError: true,
+ Params: []Param{NewParam("input", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+ })
+
+ It("should generate code for multiple methods", func() {
+ svc := Service{
+ Name: "Scheduler",
+ Permission: "scheduler",
+ Interface: "SchedulerService",
+ Methods: []Method{
+ {
+ Name: "ScheduleRecurring",
+ HasError: true,
+ Params: []Param{NewParam("cronExpression", "string")},
+ Returns: []Param{NewParam("scheduleID", "string")},
+ },
+ {
+ Name: "ScheduleOneTime",
+ HasError: true,
+ Params: []Param{NewParam("delaySeconds", "int32")},
+ Returns: []Param{NewParam("scheduleID", "string")},
+ },
+ {
+ Name: "CancelSchedule",
+ HasError: true,
+ Params: []Param{NewParam("scheduleID", "string")},
+ Returns: []Param{NewParam("canceled", "bool")},
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ Expect(codeStr).To(ContainSubstring("scheduler_schedulerecurring"))
+ Expect(codeStr).To(ContainSubstring("scheduler_scheduleonetime"))
+ Expect(codeStr).To(ContainSubstring("scheduler_cancelschedule"))
+ })
+
+ It("should handle multiple simple parameters with JSON", func() {
+ // All params use JSON - single PTR input
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "MultiParam",
+ HasError: true,
+ Params: []Param{
+ NewParam("name", "string"),
+ NewParam("count", "int32"),
+ NewParam("enabled", "bool"),
+ },
+ Returns: []Param{NewParam("result", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ // All methods use request type with JSON protocol
+ Expect(codeStr).To(ContainSubstring("type TestMultiParamRequest struct"))
+ // Check for JSON unmarshal (all methods use JSON now)
+ Expect(codeStr).To(ContainSubstring("json.Unmarshal"))
+ // Check that input/output ValueType both use PTR (JSON)
+ Expect(codeStr).To(MatchRegexp(`\[\]extism\.ValueType\{extism\.ValueTypePTR\},\s*\[\]extism\.ValueType\{extism\.ValueTypePTR\}`))
+ })
+
+ It("should use single PTR for mixed simple and complex params", func() {
+ // When any param needs JSON, all are bundled into one request struct
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "MixedParam",
+ HasError: true,
+ Params: []Param{
+ NewParam("id", "string"), // simple (PTR for string)
+ NewParam("tags", "[]string"), // complex - needs JSON
+ },
+ Returns: []Param{NewParam("count", "int32")}, // simple
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ // Request type IS needed because of complex param
+ Expect(codeStr).To(ContainSubstring("type TestMixedParamRequest struct"))
+ // When using request type, only ONE PTR for input (the JSON request)
+ Expect(codeStr).To(MatchRegexp(`\[\]extism\.ValueType\{extism\.ValueTypePTR\},\s*\[\]extism\.ValueType\{extism\.ValueTypePTR\}`))
+ })
+
+ It("should generate proper JSON tags for complex types", func() {
+ // Complex types (structs, slices, maps) need JSON serialization
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "Method",
+ HasError: true,
+ Params: []Param{NewParam("inputValue", "[]string")}, // slice needs JSON
+ Returns: []Param{NewParam("outputValue", "map[string]string")}, // map needs JSON
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ // Complex params need request type with JSON tags
+ Expect(codeStr).To(ContainSubstring(`json:"inputValue"`))
+ // Complex returns need response type with JSON tags
+ Expect(codeStr).To(ContainSubstring(`json:"outputValue,omitempty"`))
+ })
+
+ It("should include required imports", func() {
+ // Service with complex types needs JSON import
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "Method",
+ HasError: true,
+ Params: []Param{NewParam("data", "MyStruct")}, // struct needs JSON
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ Expect(codeStr).To(ContainSubstring(`"context"`))
+ Expect(codeStr).To(ContainSubstring(`"encoding/json"`))
+ Expect(codeStr).To(ContainSubstring(`extism "github.com/extism/go-sdk"`))
+ })
+
+ It("should always include json import for JSON protocol", func() {
+ // All services use JSON protocol, so json import is always needed
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "Method",
+ Params: []Param{NewParam("count", "int32")},
+ Returns: []Param{NewParam("result", "int64")},
+ },
+ },
+ }
+
+ code, err := GenerateHost(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ Expect(codeStr).To(ContainSubstring(`"context"`))
+ Expect(codeStr).To(ContainSubstring(`"encoding/json"`))
+ Expect(codeStr).To(ContainSubstring(`extism "github.com/extism/go-sdk"`))
+ })
+ })
+
+ Describe("toJSONName", func() {
+ It("should convert to camelCase matching Rust serde behavior", func() {
+ Expect(toJSONName("InputValue")).To(Equal("inputValue"))
+ Expect(toJSONName("URI")).To(Equal("uri"))
+ Expect(toJSONName("id")).To(Equal("id"))
+ Expect(toJSONName("ID")).To(Equal("id"))
+ Expect(toJSONName("ConnectionID")).To(Equal("connectionId"))
+ Expect(toJSONName("NewConnectionID")).To(Equal("newConnectionId"))
+ Expect(toJSONName("XMLHTTPRequest")).To(Equal("xmlhttpRequest"))
+ Expect(toJSONName("APIKey")).To(Equal("apiKey"))
+ })
+
+ It("should handle empty string", func() {
+ Expect(toJSONName("")).To(Equal(""))
+ })
+ })
+
+ Describe("NewParam", func() {
+ It("should create param with auto-generated JSON name", func() {
+ p := NewParam("MyParam", "string")
+ Expect(p.Name).To(Equal("MyParam"))
+ Expect(p.Type).To(Equal("string"))
+ Expect(p.JSONName).To(Equal("myParam"))
+ })
+ })
+
+ Describe("Method.IsOptionPattern", func() {
+ It("should return true for (value, exists bool) pattern", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ {Name: "exists", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeTrue())
+ })
+
+ It("should return true for (value, ok bool) pattern", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "value", Type: "int64"},
+ {Name: "ok", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeTrue())
+ })
+
+ It("should return true for (value, found bool) pattern", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "data", Type: "[]byte"},
+ {Name: "found", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeTrue())
+ })
+
+ It("should be case insensitive for bool name", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ {Name: "EXISTS", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeTrue())
+ })
+
+ It("should return false for single return", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeFalse())
+ })
+
+ It("should return false for more than two returns", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ {Name: "count", Type: "int"},
+ {Name: "exists", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeFalse())
+ })
+
+ It("should return false when second return is not bool", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ {Name: "count", Type: "int"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeFalse())
+ })
+
+ It("should return false when bool is not named exists/ok/found", func() {
+ m := Method{
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ {Name: "success", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeFalse())
+ })
+
+ It("should return false for Has() pattern where first return is bool", func() {
+ // Has(key) -> (exists bool) should NOT be treated as Option pattern
+ m := Method{
+ Returns: []Param{
+ {Name: "exists", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeFalse())
+ })
+
+ It("should return false when first return is bool (preserves Has-like methods)", func() {
+ // Even with two returns, if first is bool, don't convert to Option
+ m := Method{
+ Returns: []Param{
+ {Name: "result", Type: "bool"},
+ {Name: "exists", Type: "bool"},
+ },
+ }
+ Expect(m.IsOptionPattern()).To(BeFalse())
+ })
+ })
+
+ Describe("Python type and name helpers", func() {
+ Describe("ToPythonType", func() {
+ It("should map Go types to Python types", func() {
+ Expect(ToPythonType("string")).To(Equal("str"))
+ Expect(ToPythonType("int")).To(Equal("int"))
+ Expect(ToPythonType("int32")).To(Equal("int"))
+ Expect(ToPythonType("int64")).To(Equal("int"))
+ Expect(ToPythonType("float32")).To(Equal("float"))
+ Expect(ToPythonType("float64")).To(Equal("float"))
+ Expect(ToPythonType("bool")).To(Equal("bool"))
+ Expect(ToPythonType("[]byte")).To(Equal("bytes"))
+ Expect(ToPythonType("unknown")).To(Equal("Any"))
+ })
+ })
+
+ Describe("ToSnakeCase", func() {
+ It("should convert PascalCase to snake_case", func() {
+ Expect(ToSnakeCase("ScheduleRecurring")).To(Equal("schedule_recurring"))
+ Expect(ToSnakeCase("GetString")).To(Equal("get_string"))
+ Expect(ToSnakeCase("simple")).To(Equal("simple"))
+ })
+
+ It("should handle acronyms correctly", func() {
+ Expect(ToSnakeCase("ID")).To(Equal("id"))
+ Expect(ToSnakeCase("ScheduleID")).To(Equal("schedule_id"))
+ Expect(ToSnakeCase("NewScheduleID")).To(Equal("new_schedule_id"))
+ Expect(ToSnakeCase("XMLParser")).To(Equal("xml_parser"))
+ Expect(ToSnakeCase("GetHTTPResponse")).To(Equal("get_http_response"))
+ })
+ })
+
+ Describe("Method.PythonFunctionName", func() {
+ It("should generate snake_case function name with service prefix", func() {
+ m := Method{Name: "GetString"}
+ Expect(m.PythonFunctionName("cache")).To(Equal("cache_get_string"))
+ })
+ })
+
+ Describe("Param.PythonType", func() {
+ It("should return Python type for parameter", func() {
+ p := NewParam("value", "string")
+ Expect(p.PythonType()).To(Equal("str"))
+ })
+ })
+
+ Describe("Param.PythonName", func() {
+ It("should return snake_case name for parameter", func() {
+ p := NewParam("ttlSeconds", "int64")
+ Expect(p.PythonName()).To(Equal("ttl_seconds"))
+ })
+ })
+ })
+
+ Describe("GenerateClientPython", func() {
+ It("should generate valid Python code for a simple service", func() {
+ svc := Service{
+ Name: "SubsonicAPI",
+ Permission: "subsonicapi",
+ Interface: "SubsonicAPIService",
+ Methods: []Method{
+ {
+ Name: "Call",
+ HasError: true,
+ Params: []Param{NewParam("uri", "string")},
+ Returns: []Param{NewParam("responseJSON", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateClientPython(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for generated header
+ Expect(codeStr).To(ContainSubstring("Code generated by ndpgen. DO NOT EDIT."))
+
+ // Check for imports
+ Expect(codeStr).To(ContainSubstring("from dataclasses import dataclass"))
+ Expect(codeStr).To(ContainSubstring("import extism"))
+ Expect(codeStr).To(ContainSubstring("import json"))
+
+ // Check for exception class
+ Expect(codeStr).To(ContainSubstring("class HostFunctionError(Exception):"))
+
+ // Check for raw import function
+ Expect(codeStr).To(ContainSubstring(`@extism.import_fn("extism:host/user", "subsonicapi_call")`))
+ Expect(codeStr).To(ContainSubstring("def _subsonicapi_call(offset: int) -> int:"))
+
+ // Check for wrapper function with type hints
+ Expect(codeStr).To(ContainSubstring("def subsonicapi_call(uri: str) -> str:"))
+
+ // Check for error handling
+ Expect(codeStr).To(ContainSubstring("raise HostFunctionError(response["))
+ })
+
+ It("should generate dataclass for multi-value returns", func() {
+ svc := Service{
+ Name: "Cache",
+ Permission: "cache",
+ Interface: "CacheService",
+ Methods: []Method{
+ {
+ Name: "GetString",
+ HasError: true,
+ Params: []Param{NewParam("key", "string")},
+ Returns: []Param{
+ NewParam("value", "string"),
+ NewParam("exists", "bool"),
+ },
+ },
+ },
+ }
+
+ code, err := GenerateClientPython(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for dataclass
+ Expect(codeStr).To(ContainSubstring("@dataclass"))
+ Expect(codeStr).To(ContainSubstring("class CacheGetStringResult:"))
+ Expect(codeStr).To(ContainSubstring("value: str"))
+ Expect(codeStr).To(ContainSubstring("exists: bool"))
+
+ // Check that function returns dataclass
+ Expect(codeStr).To(ContainSubstring("def cache_get_string(key: str) -> CacheGetStringResult:"))
+ Expect(codeStr).To(ContainSubstring("return CacheGetStringResult("))
+ })
+
+ It("should handle methods with no parameters", func() {
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "NoParams",
+ HasError: true,
+ Returns: []Param{NewParam("result", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateClientPython(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Function with no params
+ Expect(codeStr).To(ContainSubstring("def test_no_params() -> str:"))
+ // Empty request
+ Expect(codeStr).To(ContainSubstring(`request_bytes = b"{}"`))
+ })
+
+ It("should handle methods with no return values", func() {
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "NoReturn",
+ HasError: true,
+ Params: []Param{NewParam("input", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateClientPython(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Function returns None
+ Expect(codeStr).To(ContainSubstring("def test_no_return(input: str) -> None:"))
+ })
+
+ It("should generate correct Python defaults for different types", func() {
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "AllTypes",
+ HasError: true,
+ Returns: []Param{
+ NewParam("strVal", "string"),
+ NewParam("intVal", "int64"),
+ NewParam("floatVal", "float64"),
+ NewParam("boolVal", "bool"),
+ },
+ },
+ },
+ }
+
+ code, err := GenerateClientPython(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check defaults in response.get() calls
+ Expect(codeStr).To(ContainSubstring(`response.get("strVal", "")`))
+ Expect(codeStr).To(ContainSubstring(`response.get("intVal", 0)`))
+ Expect(codeStr).To(ContainSubstring(`response.get("floatVal", 0.0)`))
+ Expect(codeStr).To(ContainSubstring(`response.get("boolVal", False)`))
+ })
+
+ It("should not import base64 for non-byte services", func() {
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "Call",
+ HasError: true,
+ Params: []Param{NewParam("uri", "string")},
+ Returns: []Param{NewParam("response", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateClientPython(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ Expect(codeStr).NotTo(ContainSubstring("import base64"))
+ })
+
+ It("should generate base64 encoding/decoding for byte fields", func() {
+ svc := Service{
+ Name: "Codec",
+ Permission: "codec",
+ Interface: "CodecService",
+ Methods: []Method{
+ {
+ Name: "Encode",
+ HasError: true,
+ Params: []Param{NewParam("data", "[]byte")},
+ Returns: []Param{NewParam("result", "[]byte")},
+ },
+ },
+ }
+
+ code, err := GenerateClientPython(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Should import base64
+ Expect(codeStr).To(ContainSubstring("import base64"))
+
+ // Should base64-encode byte params in request
+ Expect(codeStr).To(ContainSubstring(`base64.b64encode(data).decode("ascii")`))
+
+ // Should base64-decode byte returns in response
+ Expect(codeStr).To(ContainSubstring(`base64.b64decode(response.get("result", ""))`))
+ })
+ })
+
+ Describe("GenerateGoDoc", func() {
+ It("should generate valid doc.go content for multiple services", func() {
+ services := []Service{
+ {
+ Name: "Cache",
+ Permission: "cache",
+ Interface: "CacheService",
+ Doc: "CacheService provides temporary key-value storage with TTL.",
+ },
+ {
+ Name: "Scheduler",
+ Permission: "scheduler",
+ Interface: "SchedulerService",
+ Doc: "SchedulerService manages scheduled tasks.",
+ },
+ }
+
+ code, err := GenerateGoDoc(services, "ndpdk")
+ Expect(err).NotTo(HaveOccurred())
+
+ // Verify it's valid Go code
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for generated header
+ Expect(codeStr).To(ContainSubstring("Code generated by ndpgen. DO NOT EDIT."))
+
+ // Check for package declaration
+ Expect(codeStr).To(ContainSubstring("package ndpdk"))
+
+ // Check for package documentation
+ Expect(codeStr).To(ContainSubstring("Package ndpdk provides Navidrome Plugin Development Kit wrappers"))
+
+ // Check that services are listed
+ Expect(codeStr).To(ContainSubstring("Cache:"))
+ Expect(codeStr).To(ContainSubstring("Scheduler:"))
+ })
+ })
+
+ Describe("GenerateGoMod", func() {
+ It("should generate valid go.mod content", func() {
+ code, err := GenerateGoMod()
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for module declaration (consolidated PDK path at pdk/go level)
+ Expect(codeStr).To(ContainSubstring("module github.com/navidrome/navidrome/plugins/pdk/go"))
+ // Ensure it's not the old host-specific path
+ Expect(codeStr).NotTo(ContainSubstring("module github.com/navidrome/navidrome/plugins/pdk/go/host"))
+
+ // Check for Go version
+ Expect(codeStr).To(ContainSubstring("go 1.25"))
+
+ // Check for extism-go-pdk dependency
+ Expect(codeStr).To(ContainSubstring("github.com/extism/go-pdk"))
+ })
+ })
+
+ Describe("GenerateClientGo", func() {
+ It("should include errors import when service has methods with errors", func() {
+ svc := Service{
+ Name: "Cache",
+ Permission: "cache",
+ Interface: "CacheService",
+ Methods: []Method{
+ {
+ Name: "Get",
+ HasError: true,
+ Params: []Param{NewParam("key", "string")},
+ Returns: []Param{NewParam("value", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateClientGo(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ // Verify the code is valid Go (can't actually compile without wasip1)
+ codeStr := string(code)
+
+ // Check for errors import when methods have errors
+ Expect(codeStr).To(ContainSubstring(`"errors"`))
+ Expect(codeStr).To(ContainSubstring("errors.New"))
+ })
+
+ It("should not include errors import when service has no methods with errors", func() {
+ svc := Service{
+ Name: "Config",
+ Permission: "config",
+ Interface: "ConfigService",
+ Methods: []Method{
+ {
+ Name: "Get",
+ HasError: false,
+ Params: []Param{NewParam("key", "string")},
+ Returns: []Param{NewParam("value", "string"), NewParam("exists", "bool")},
+ },
+ {
+ Name: "List",
+ HasError: false,
+ Params: []Param{NewParam("prefix", "string")},
+ Returns: []Param{NewParam("keys", "[]string")},
+ },
+ },
+ }
+
+ code, err := GenerateClientGo(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check that errors is NOT imported when no methods have errors
+ Expect(codeStr).NotTo(ContainSubstring(`"errors"`))
+ Expect(codeStr).NotTo(ContainSubstring("errors.New"))
+ })
+
+ It("should generate valid Go code structure", func() {
+ svc := Service{
+ Name: "SubsonicAPI",
+ Permission: "subsonicapi",
+ Interface: "SubsonicAPIService",
+ Methods: []Method{
+ {
+ Name: "Call",
+ HasError: true,
+ Params: []Param{NewParam("uri", "string")},
+ Returns: []Param{NewParam("response", "string")},
+ },
+ },
+ }
+
+ code, err := GenerateClientGo(svc, "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for generated header
+ Expect(codeStr).To(ContainSubstring("Code generated by ndpgen. DO NOT EDIT."))
+
+ // Check for build tag
+ Expect(codeStr).To(ContainSubstring("//go:build wasip1"))
+
+ // Check for package declaration
+ Expect(codeStr).To(ContainSubstring("package host"))
+
+ // Check for wasmimport directive
+ Expect(codeStr).To(ContainSubstring("//go:wasmimport extism:host/user"))
+
+ // Check for PDK import
+ Expect(codeStr).To(ContainSubstring("github.com/navidrome/navidrome/plugins/pdk/go/pdk"))
+ })
+
+ })
+
+ Describe("GenerateClientGoStub", func() {
+ It("should generate valid mock code with testify/mock", func() {
+ svc := Service{
+ Name: "Cache",
+ Permission: "cache",
+ Interface: "CacheService",
+ Doc: "CacheService provides caching capabilities.",
+ Methods: []Method{
+ {
+ Name: "Get",
+ Doc: "Get retrieves a value from the cache.",
+ Params: []Param{
+ {Name: "key", Type: "string"},
+ },
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ {Name: "exists", Type: "bool"},
+ },
+ },
+ },
+ }
+
+ code, err := GenerateClientGoStub(svc, "ndpdk")
+ Expect(err).NotTo(HaveOccurred())
+
+ // Verify it's valid Go code
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for build tag (non-WASM)
+ Expect(codeStr).To(ContainSubstring("//go:build !wasip1"))
+
+ // Check for package declaration
+ Expect(codeStr).To(ContainSubstring("package ndpdk"))
+
+ // Check for mock comment
+ Expect(codeStr).To(ContainSubstring("mock implementations for non-WASM builds"))
+
+ // Check for testify/mock import
+ Expect(codeStr).To(ContainSubstring(`"github.com/stretchr/testify/mock"`))
+
+ // Check for private mock struct
+ Expect(codeStr).To(ContainSubstring("type mockCacheService struct"))
+ Expect(codeStr).To(ContainSubstring("mock.Mock"))
+
+ // Check for exported mock instance
+ Expect(codeStr).To(ContainSubstring("var CacheMock = &mockCacheService{}"))
+
+ // Check for mock method
+ Expect(codeStr).To(ContainSubstring("func (m *mockCacheService) Get(key string)"))
+ Expect(codeStr).To(ContainSubstring("m.Called(key)"))
+
+ // Check for wrapper function delegating to mock
+ Expect(codeStr).To(ContainSubstring("func CacheGet(key string)"))
+ Expect(codeStr).To(ContainSubstring("return CacheMock.Get(key)"))
+
+ // Stub files should NOT have request/response types (they're not needed)
+ Expect(codeStr).NotTo(ContainSubstring("Request struct"))
+ Expect(codeStr).NotTo(ContainSubstring("Response struct"))
+ })
+
+ It("should generate correct mock return values for different types", func() {
+ svc := Service{
+ Name: "Test",
+ Permission: "test",
+ Interface: "TestService",
+ Methods: []Method{
+ {
+ Name: "GetString",
+ Params: []Param{
+ {Name: "key", Type: "string"},
+ },
+ Returns: []Param{
+ {Name: "value", Type: "string"},
+ },
+ HasError: true,
+ },
+ {
+ Name: "GetInt64",
+ Params: []Param{
+ {Name: "key", Type: "string"},
+ },
+ Returns: []Param{
+ {Name: "value", Type: "int64"},
+ {Name: "exists", Type: "bool"},
+ },
+ HasError: true,
+ },
+ {
+ Name: "GetBytes",
+ Params: []Param{
+ {Name: "key", Type: "string"},
+ },
+ Returns: []Param{
+ {Name: "value", Type: "[]byte"},
+ },
+ HasError: true,
+ },
+ },
+ }
+
+ code, err := GenerateClientGoStub(svc, "ndpdk")
+ Expect(err).NotTo(HaveOccurred())
+
+ // Verify it's valid Go code
+ _, err = format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check string return uses args.String(0)
+ Expect(codeStr).To(ContainSubstring("args.String(0)"))
+
+ // Check int64 return uses args.Get(0).(int64)
+ Expect(codeStr).To(ContainSubstring("args.Get(0).(int64)"))
+
+ // Check bool return uses args.Bool(1)
+ Expect(codeStr).To(ContainSubstring("args.Bool(1)"))
+
+ // Check []byte return uses args.Get(0).([]byte)
+ Expect(codeStr).To(ContainSubstring("args.Get(0).([]byte)"))
+
+ // Check error returns use args.Error(N)
+ Expect(codeStr).To(ContainSubstring("args.Error("))
+ })
+ })
+
+ Describe("Integration", func() {
+ It("should generate compilable code from parsed source", func() {
+ // This is an integration test that verifies the full pipeline
+ src := `package host
+
+import "context"
+
+// TestService is a test service.
+//nd:hostservice name=Test permission=test
+type TestService interface {
+ // DoSomething does something.
+ //nd:hostfunc
+ DoSomething(ctx context.Context, input string) (output string, err error)
+}
+`
+ // Create temporary directory
+ tmpDir := GinkgoT().TempDir()
+ path := tmpDir + "/test.go"
+ err := writeFile(path, src)
+ Expect(err).NotTo(HaveOccurred())
+
+ // Parse
+ services, err := ParseDirectory(tmpDir)
+ Expect(err).NotTo(HaveOccurred())
+ Expect(services).To(HaveLen(1))
+
+ // Generate
+ code, err := GenerateHost(services[0], "host")
+ Expect(err).NotTo(HaveOccurred())
+
+ // Format (validates syntax)
+ formatted, err := format.Source(code)
+ Expect(err).NotTo(HaveOccurred())
+
+ // Verify key elements
+ codeStr := string(formatted)
+ Expect(codeStr).To(ContainSubstring("RegisterTestHostFunctions"))
+ Expect(codeStr).To(ContainSubstring(`"test_dosomething"`))
+ })
+ })
+
+ Describe("GenerateCapabilityGo", func() {
+ It("should generate valid Go code for a non-required capability", func() {
+ cap := Capability{
+ Name: "metadata",
+ Interface: "MetadataAgent",
+ Required: false,
+ Doc: "MetadataAgent provides metadata retrieval.",
+ Methods: []Export{
+ {
+ Name: "GetArtistBiography",
+ ExportName: "nd_get_artist_biography",
+ Input: Param{Type: "ArtistInput"},
+ Output: Param{Type: "ArtistBiographyOutput"},
+ Doc: "Returns artist biography",
+ },
+ {
+ Name: "GetArtistImages",
+ ExportName: "nd_get_artist_images",
+ Input: Param{Type: "ArtistInput"},
+ Output: Param{Type: "ArtistImagesOutput"},
+ Doc: "Returns artist images",
+ },
+ },
+ Structs: []StructDef{
+ {
+ Name: "ArtistInput",
+ Fields: []FieldDef{
+ {Name: "ID", Type: "string", JSONTag: "id"},
+ {Name: "Name", Type: "string", JSONTag: "name"},
+ },
+ },
+ {
+ Name: "ArtistBiographyOutput",
+ Fields: []FieldDef{
+ {Name: "Biography", Type: "string", JSONTag: "biography"},
+ },
+ },
+ {
+ Name: "ArtistImagesOutput",
+ Fields: []FieldDef{
+ {Name: "Images", Type: "[]ImageInfo", JSONTag: "images"},
+ },
+ },
+ {
+ Name: "ImageInfo",
+ Fields: []FieldDef{
+ {Name: "URL", Type: "string", JSONTag: "url"},
+ {Name: "Size", Type: "int32", JSONTag: "size"},
+ },
+ },
+ },
+ }
+
+ code, err := GenerateCapabilityGo(cap, "metadata")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for build tag
+ Expect(codeStr).To(ContainSubstring("//go:build wasip1"))
+
+ // Check for package declaration
+ Expect(codeStr).To(ContainSubstring("package metadata"))
+
+ // Check for marker interface (non-required)
+ Expect(codeStr).To(ContainSubstring("type Metadata interface{}"))
+
+ // Check for provider interfaces
+ Expect(codeStr).To(ContainSubstring("type ArtistBiographyProvider interface"))
+ Expect(codeStr).To(ContainSubstring("type ArtistImagesProvider interface"))
+
+ // Check for Register function with type assertions
+ Expect(codeStr).To(ContainSubstring("func Register(impl Metadata)"))
+ Expect(codeStr).To(ContainSubstring("impl.(ArtistBiographyProvider)"))
+
+ // Check for export wrappers
+ Expect(codeStr).To(ContainSubstring("//go:wasmexport nd_get_artist_biography"))
+ Expect(codeStr).To(ContainSubstring("func _NdGetArtistBiography()"))
+
+ // Check for NotImplementedCode handling
+ Expect(codeStr).To(ContainSubstring("NotImplementedCode"))
+ Expect(codeStr).To(ContainSubstring("return NotImplementedCode"))
+
+ // Check struct definitions
+ Expect(codeStr).To(ContainSubstring("type ArtistInput struct"))
+ Expect(codeStr).To(ContainSubstring("type ImageInfo struct"))
+ })
+
+ It("should generate valid Go code for a required capability", func() {
+ cap := Capability{
+ Name: "scrobbler",
+ Interface: "Scrobbler",
+ Required: true,
+ Methods: []Export{
+ {
+ Name: "IsAuthorized",
+ ExportName: "nd_scrobbler_is_authorized",
+ Input: Param{Type: "AuthInput"},
+ Output: Param{Type: "AuthOutput"},
+ },
+ {
+ Name: "Scrobble",
+ ExportName: "nd_scrobbler_scrobble",
+ Input: Param{Type: "ScrobbleInput"},
+ Output: Param{Type: "ScrobblerOutput"},
+ },
+ },
+ Structs: []StructDef{
+ {Name: "AuthInput", Fields: []FieldDef{{Name: "UserID", Type: "string", JSONTag: "userId"}}},
+ {Name: "AuthOutput", Fields: []FieldDef{{Name: "Authorized", Type: "bool", JSONTag: "authorized"}}},
+ {Name: "ScrobbleInput", Fields: []FieldDef{{Name: "UserID", Type: "string", JSONTag: "userId"}}},
+ {Name: "ScrobblerOutput", Fields: []FieldDef{{Name: "Error", Type: "*string", JSONTag: "error", OmitEmpty: true}}},
+ },
+ }
+
+ code, err := GenerateCapabilityGo(cap, "scrobbler")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for full interface (required capability)
+ Expect(codeStr).To(ContainSubstring("type Scrobbler interface {"))
+ Expect(codeStr).To(ContainSubstring("IsAuthorized(AuthInput) (AuthOutput, error)"))
+ Expect(codeStr).To(ContainSubstring("Scrobble(ScrobbleInput) (ScrobblerOutput, error)"))
+
+ // Should NOT have provider interfaces for required capability
+ Expect(codeStr).NotTo(ContainSubstring("AuthProvider interface"))
+
+ // Register should directly assign methods
+ Expect(codeStr).To(ContainSubstring("func Register(impl Scrobbler)"))
+ Expect(codeStr).To(ContainSubstring("impl.IsAuthorized"))
+ })
+
+ It("should include type aliases and consts", func() {
+ cap := Capability{
+ Name: "scrobbler",
+ Interface: "Scrobbler",
+ Required: true,
+ Methods: []Export{
+ {
+ Name: "Scrobble",
+ ExportName: "nd_scrobble",
+ Input: Param{Type: "ScrobbleInput"},
+ Output: Param{Type: "ScrobblerOutput"},
+ },
+ },
+ Structs: []StructDef{
+ {Name: "ScrobbleInput", Fields: []FieldDef{{Name: "UserID", Type: "string", JSONTag: "userId"}}},
+ {Name: "ScrobblerOutput", Fields: []FieldDef{{Name: "ErrorType", Type: "*ScrobblerErrorType", JSONTag: "errorType", OmitEmpty: true}}},
+ },
+ TypeAliases: []TypeAlias{
+ {Name: "ScrobblerErrorType", Type: "string", Doc: "ScrobblerErrorType indicates error handling."},
+ },
+ Consts: []ConstGroup{
+ {
+ Type: "ScrobblerErrorType",
+ Values: []ConstDef{
+ {Name: "ScrobblerErrorNone", Value: `"none"`, Doc: "No error"},
+ {Name: "ScrobblerErrorRetry", Value: `"retry"`, Doc: "Retry later"},
+ },
+ },
+ },
+ }
+
+ code, err := GenerateCapabilityGo(cap, "scrobbler")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check type alias
+ Expect(codeStr).To(ContainSubstring("type ScrobblerErrorType string"))
+
+ // Check consts - all consts should have type annotation
+ Expect(codeStr).To(ContainSubstring("ScrobblerErrorNone ScrobblerErrorType ="))
+ Expect(codeStr).To(ContainSubstring(`"none"`))
+ Expect(codeStr).To(ContainSubstring("ScrobblerErrorRetry ScrobblerErrorType ="))
+ Expect(codeStr).To(ContainSubstring(`"retry"`))
+ })
+ })
+
+ Describe("GenerateCapabilityGoStub", func() {
+ It("should generate valid stub code for non-WASM builds", func() {
+ cap := Capability{
+ Name: "metadata",
+ Interface: "MetadataAgent",
+ Required: false,
+ Methods: []Export{
+ {
+ Name: "GetArtistBiography",
+ ExportName: "nd_get_artist_biography",
+ Input: Param{Type: "ArtistInput"},
+ Output: Param{Type: "ArtistBiographyOutput"},
+ },
+ },
+ Structs: []StructDef{
+ {Name: "ArtistInput", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
+ {Name: "ArtistBiographyOutput", Fields: []FieldDef{{Name: "Biography", Type: "string", JSONTag: "biography"}}},
+ },
+ }
+
+ code, err := GenerateCapabilityGoStub(cap, "metadata")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check for non-WASM build tag
+ Expect(codeStr).To(ContainSubstring("//go:build !wasip1"))
+
+ // Check for package declaration
+ Expect(codeStr).To(ContainSubstring("package metadata"))
+
+ // Check for no-op Register
+ Expect(codeStr).To(ContainSubstring("func Register(_ Metadata) {}"))
+
+ // Check struct definitions are present
+ Expect(codeStr).To(ContainSubstring("type ArtistInput struct"))
+
+ // Check there are no export wrappers
+ Expect(codeStr).NotTo(ContainSubstring("//go:wasmexport"))
+ Expect(codeStr).NotTo(ContainSubstring("pdk.InputJSON"))
+ })
+ })
+
+ Describe("End-to-end capability generation", func() {
+ It("should parse and generate capability code from source", func() {
+ src := `package capabilities
+
+// Lifecycle provides plugin lifecycle hooks.
+//nd:capability name=lifecycle
+type Lifecycle interface {
+ // OnInit is called when the plugin is loaded.
+ //nd:export name=nd_on_init
+ OnInit(OnInitInput) (OnInitOutput, error)
+}
+
+// OnInitInput is the input for OnInit.
+type OnInitInput struct {
+}
+
+// OnInitOutput is the output for OnInit.
+type OnInitOutput struct {
+ // Error is the error message if initialization failed.
+ Error *string ` + "`json:\"error,omitempty\"`" + `
+}
+`
+ // Create temporary directory
+ tmpDir := GinkgoT().TempDir()
+ path := tmpDir + "/lifecycle.go"
+ err := writeFile(path, src)
+ Expect(err).NotTo(HaveOccurred())
+
+ // Parse
+ capabilities, err := ParseCapabilities(tmpDir)
+ Expect(err).NotTo(HaveOccurred())
+ Expect(capabilities).To(HaveLen(1))
+
+ cap := capabilities[0]
+ Expect(cap.Name).To(Equal("lifecycle"))
+ Expect(cap.Methods).To(HaveLen(1))
+
+ // Generate WASM code
+ code, err := GenerateCapabilityGo(cap, "lifecycle")
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+ Expect(codeStr).To(ContainSubstring("//go:wasmexport nd_on_init"))
+ Expect(codeStr).To(ContainSubstring("type InitProvider interface"))
+
+ // Generate stub code
+ stubCode, err := GenerateCapabilityGoStub(cap, "lifecycle")
+ Expect(err).NotTo(HaveOccurred())
+
+ stubStr := string(stubCode)
+ Expect(stubStr).To(ContainSubstring("//go:build !wasip1"))
+ Expect(stubStr).To(ContainSubstring("func Register(_ Lifecycle) {}"))
+ })
+ })
+})
+
+var _ = Describe("Rust Generation", func() {
+ Describe("skipSerializingFunc", func() {
+ It("should return Option::is_none for pointer, slice, and map types", func() {
+ Expect(skipSerializingFunc("*string")).To(Equal("Option::is_none"))
+ Expect(skipSerializingFunc("*MyStruct")).To(Equal("Option::is_none"))
+ Expect(skipSerializingFunc("[]string")).To(Equal("Option::is_none"))
+ Expect(skipSerializingFunc("[]int32")).To(Equal("Option::is_none"))
+ Expect(skipSerializingFunc("map[string]int")).To(Equal("Option::is_none"))
+ })
+
+ It("should return String::is_empty for string type", func() {
+ Expect(skipSerializingFunc("string")).To(Equal("String::is_empty"))
+ })
+
+ It("should return std::ops::Not::not for bool type", func() {
+ Expect(skipSerializingFunc("bool")).To(Equal("std::ops::Not::not"))
+ })
+
+ It("should return is_zero_* functions for numeric types", func() {
+ Expect(skipSerializingFunc("int32")).To(Equal("is_zero_i32"))
+ Expect(skipSerializingFunc("uint32")).To(Equal("is_zero_u32"))
+ Expect(skipSerializingFunc("int64")).To(Equal("is_zero_i64"))
+ Expect(skipSerializingFunc("uint64")).To(Equal("is_zero_u64"))
+ Expect(skipSerializingFunc("float32")).To(Equal("is_zero_f32"))
+ Expect(skipSerializingFunc("float64")).To(Equal("is_zero_f64"))
+ })
+
+ It("should return Option::is_none for unknown types", func() {
+ Expect(skipSerializingFunc("CustomType")).To(Equal("Option::is_none"))
+ })
+ })
+
+ Describe("rustOutputType", func() {
+ It("should convert Go primitives to Rust primitives", func() {
+ Expect(rustOutputType("bool")).To(Equal("bool"))
+ Expect(rustOutputType("string")).To(Equal("String"))
+ Expect(rustOutputType("int")).To(Equal("i32"))
+ Expect(rustOutputType("int32")).To(Equal("i32"))
+ Expect(rustOutputType("int64")).To(Equal("i64"))
+ Expect(rustOutputType("float32")).To(Equal("f32"))
+ Expect(rustOutputType("float64")).To(Equal("f64"))
+ })
+
+ It("should strip pointer prefix", func() {
+ // NOTE: This behavior is incorrect for pointer to primitives.
+ // "*string" returns "string" instead of "String", which would generate
+ // invalid Rust code. No current capability uses this pattern.
+ // See TODO in rustOutputType function.
+ Expect(rustOutputType("*string")).To(Equal("string"))
+ Expect(rustOutputType("*MyStruct")).To(Equal("MyStruct"))
+ })
+
+ It("should pass through unknown types", func() {
+ Expect(rustOutputType("CustomType")).To(Equal("CustomType"))
+ Expect(rustOutputType("MyStruct")).To(Equal("MyStruct"))
+ })
+ })
+
+ Describe("isPrimitiveRustType", func() {
+ It("should return true for primitive Go types", func() {
+ Expect(isPrimitiveRustType("bool")).To(BeTrue())
+ Expect(isPrimitiveRustType("string")).To(BeTrue())
+ Expect(isPrimitiveRustType("int")).To(BeTrue())
+ Expect(isPrimitiveRustType("int32")).To(BeTrue())
+ Expect(isPrimitiveRustType("int64")).To(BeTrue())
+ Expect(isPrimitiveRustType("float32")).To(BeTrue())
+ Expect(isPrimitiveRustType("float64")).To(BeTrue())
+ })
+
+ It("should return false for non-primitive types", func() {
+ Expect(isPrimitiveRustType("MyStruct")).To(BeFalse())
+ Expect(isPrimitiveRustType("CustomType")).To(BeFalse())
+ Expect(isPrimitiveRustType("[]string")).To(BeFalse())
+ Expect(isPrimitiveRustType("map[string]int")).To(BeFalse())
+ })
+
+ It("should handle pointer types by stripping prefix", func() {
+ Expect(isPrimitiveRustType("*string")).To(BeTrue())
+ Expect(isPrimitiveRustType("*int64")).To(BeTrue())
+ Expect(isPrimitiveRustType("*MyStruct")).To(BeFalse())
+ })
+ })
+
+ Describe("GenerateCapabilityRust", func() {
+ It("should generate valid Rust code with primitive output types", func() {
+ cap := Capability{
+ Name: "test",
+ Interface: "TestAgent",
+ Required: true,
+ SourceFile: "test",
+ Methods: []Export{
+ {
+ Name: "GetBool",
+ ExportName: "nd_get_bool",
+ Input: Param{Type: "BoolInput"},
+ Output: Param{Type: "bool"},
+ },
+ {
+ Name: "GetString",
+ ExportName: "nd_get_string",
+ Input: Param{Type: "StrInput"},
+ Output: Param{Type: "string"},
+ },
+ {
+ Name: "GetInt",
+ ExportName: "nd_get_int",
+ Input: Param{Type: "IntInput"},
+ Output: Param{Type: "int32"},
+ },
+ },
+ Structs: []StructDef{
+ {Name: "BoolInput", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
+ {Name: "StrInput", Fields: []FieldDef{{Name: "Key", Type: "string", JSONTag: "key"}}},
+ {Name: "IntInput", Fields: []FieldDef{{Name: "Index", Type: "int32", JSONTag: "index"}}},
+ },
+ }
+
+ code, err := GenerateCapabilityRust(cap)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Check that primitive output types are not prefixed with $crate::
+ // The template should use isPrimitiveRust to determine this
+ Expect(codeStr).To(ContainSubstring("FnResult>"))
+ Expect(codeStr).To(ContainSubstring("FnResult>"))
+ Expect(codeStr).To(ContainSubstring("FnResult>"))
+
+ // Verify that primitive output types don't use $crate:: prefix in FnResult
+ // The pattern "$crate::test::bool>" would indicate incorrect generation
+ Expect(codeStr).NotTo(ContainSubstring("$crate::test::bool>"))
+ Expect(codeStr).NotTo(ContainSubstring("$crate::test::String>"))
+ Expect(codeStr).NotTo(ContainSubstring("$crate::test::i32>"))
+ })
+
+ It("should generate valid Rust code with struct output types", func() {
+ cap := Capability{
+ Name: "metadata",
+ Interface: "MetadataAgent",
+ Required: true,
+ SourceFile: "metadata",
+ Methods: []Export{
+ {
+ Name: "GetArtist",
+ ExportName: "nd_get_artist",
+ Input: Param{Type: "ArtistInput"},
+ Output: Param{Type: "ArtistOutput"},
+ },
+ },
+ Structs: []StructDef{
+ {Name: "ArtistInput", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
+ {Name: "ArtistOutput", Fields: []FieldDef{{Name: "Name", Type: "string", JSONTag: "name"}}},
+ },
+ }
+
+ code, err := GenerateCapabilityRust(cap)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Non-primitive struct types should use $crate:: prefix
+ Expect(codeStr).To(ContainSubstring("$crate::metadata::ArtistOutput"))
+ })
+
+ It("should generate valid Rust code with pointer output types", func() {
+ cap := Capability{
+ Name: "test",
+ Interface: "TestAgent",
+ Required: true,
+ SourceFile: "test",
+ Methods: []Export{
+ {
+ Name: "GetOptionalStruct",
+ ExportName: "nd_get_optional_struct",
+ Input: Param{Type: "Input"},
+ Output: Param{Type: "*Output"},
+ },
+ },
+ Structs: []StructDef{
+ {Name: "Input", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
+ {Name: "Output", Fields: []FieldDef{{Name: "Value", Type: "string", JSONTag: "value"}}},
+ },
+ }
+
+ code, err := GenerateCapabilityRust(cap)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Pointer to struct should strip pointer and use struct type with $crate::
+ Expect(codeStr).To(ContainSubstring("$crate::test::Output>"))
+ // Pointer output types should NOT have Option<> wrapping - Result handles optionality
+ Expect(codeStr).NotTo(ContainSubstring("Option<"))
+ })
+
+ It("should include all float types correctly", func() {
+ cap := Capability{
+ Name: "test",
+ Interface: "TestAgent",
+ Required: true,
+ SourceFile: "test",
+ Methods: []Export{
+ {
+ Name: "GetFloat32",
+ ExportName: "nd_get_float32",
+ Input: Param{Type: "Input"},
+ Output: Param{Type: "float32"},
+ },
+ {
+ Name: "GetFloat64",
+ ExportName: "nd_get_float64",
+ Input: Param{Type: "Input"},
+ Output: Param{Type: "float64"},
+ },
+ },
+ Structs: []StructDef{
+ {Name: "Input", Fields: []FieldDef{{Name: "ID", Type: "string", JSONTag: "id"}}},
+ },
+ }
+
+ code, err := GenerateCapabilityRust(cap)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ Expect(codeStr).To(ContainSubstring("FnResult>"))
+ Expect(codeStr).To(ContainSubstring("FnResult>"))
+ })
+ })
+
+ Describe("GenerateClientRust", func() {
+ It("should generate Option for (value, exists bool) pattern", func() {
+ svc := Service{
+ Name: "Config",
+ Permission: "config",
+ Interface: "ConfigService",
+ Methods: []Method{
+ {
+ Name: "Get",
+ Params: []Param{
+ {Name: "key", Type: "string", JSONName: "key"},
+ },
+ Returns: []Param{
+ {Name: "value", Type: "string", JSONName: "value"},
+ {Name: "exists", Type: "bool", JSONName: "exists"},
+ },
+ },
+ },
+ }
+
+ code, err := GenerateClientRust(svc)
+ Expect(err).NotTo(HaveOccurred())
+
+ codeStr := string(code)
+
+ // Should generate Option return type, not (String, bool)
+ Expect(codeStr).To(ContainSubstring("Result