diff --git a/.dockerignore b/.dockerignore index be1135a4..a3be6f83 100644 --- a/.dockerignore +++ b/.dockerignore @@ -33,8 +33,4 @@ docs/ !.env.example # CI workflow files don't need to ship in the image. -# -# This said `.forgejo/` and `.github/` — neither of which this repo has. Gitea -# Actions reads `.gitea/`, so the one directory that actually exists was the -# one not excluded, and every workflow edit invalidated the context. .gitea/ diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..600595f1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +# Files only the build pipeline uses stay out of `git archive`, which makes +# the public source release. The two release tests pin the workflow file, so +# they leave with it; without it they would fail `go test ./...`. +.gitea/ export-ignore +ci/ export-ignore +ci-requirements.md export-ignore +renovate.json export-ignore +internal/server/release_gate_test.go export-ignore +internal/server/release_version_test.go export-ignore +.gitattributes export-ignore diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index f065f4ff..b5901a6d 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -1,13 +1,20 @@ name: release -# Builds and pushes the minstrel container image to the Gitea registry. +# Builds and pushes the minstrel container image to the Gitea registry, and on +# main also makes the public release. # -# push to dev → :dev (freshly-built dev APK bundled) -# push to main → :latest + : (freshly-built stable APK bundled) -# push tag vYYYY.MM.DD.HHMM → :latest (fresh APK bundled, and attached to the Release) -# workflow_dispatch → manual trigger (same rules based on the ref) +# push to dev → :dev (freshly-built dev APK bundled), and the +# public release's dry run +# push to main → :latest + : (freshly-built stable APK bundled), then +# THE PUBLIC RELEASE: one commit and tag v on +# github.com/Fabled-Sword/minstrel, the image +# ghcr.io/fabled-sword/minstrel : + :latest, and a +# release page with its changelog on both forges +# workflow_dispatch → the same as a push to the dispatched branch, private +# half only; force_red checks the gate (see below) # -# That is the whole tag map. +# That is the whole tag map. The rest of this header is about the private +# registry; the public release is described at image-release. # # : on main is the ROLLBACK UNIT — every production commit addressable # without a release ceremony. It is minted only on main, where rollback is @@ -43,33 +50,24 @@ name: release # # Every branch build carries the app built from its own commit, so a merge to # main is all it takes to put a new app in front of stable phones: `:latest` -# serves it from /api/client/apk and the in-app update offers it. A release -# is an optional bookmark — a named point in history with the APK attached -# for download — never a step the app has to wait for. +# serves it from /api/client/apk and the in-app update offers it. The app is +# never published on its own; it reaches phones only through the server. # -# Release model: the tag IS the artifact's version name with a `v` in front. -# `v2026.09.10.1432` and `2026.09.10.1432` are the same string, derived from -# the tagged commit's UTC timestamp — so there is no mismatch to reconcile -# between what the tag says and what the APK reports, and nothing to look up -# when minting one. +# Release model: a merge to main IS the release. Its name is v +# from the merge commit's UTC time, so every merge has its own. The run makes +# the tag on both forges; nobody tags by hand. # -# TAGS ARE IMMUTABLE. Never move, retarget or delete a published tag. A -# same-day second release is not a collision — HHMM makes every tag unique -# by construction, so the answer is simply another tag. Anyone installing -# from a moved tag would hold something the tag no longer points at, which -# is a worse failure than an extra row in the tag list. +# TAGS ARE IMMUTABLE. Never move, retarget or delete a published tag. A re-run +# finds its tag already published: on the same tree it goes on, on another it +# stops. A failed public half is fixed on dev, and the next merge carries a new +# name. # -# :latest is updated by every main push AND every tag push, so it always -# reflects the newest blessed image. -# -# APK pipeline: on every push — dev, main and tags alike — the -# android-release job builds + signs the Android APK and uploads it as a -# workflow artifact. The image-release job declares `needs: android-release` -# and requires its success, so the docker image cannot start building until -# the APK is guaranteed-ready — no polling, no race, no silent-failure mode, -# and no image that moves a channel without an app inside it. Attaching the -# APK to the gitea Release is its own job (release-assets), tags only, behind -# the test gate below. +# APK pipeline: on every push the android-release job builds + signs the +# Android APK and uploads it as a workflow artifact. The image-release job +# declares `needs: android-release` and requires its success, so the docker +# image cannot start building until the APK is guaranteed-ready — no polling, +# no race, no silent-failure mode, and no image that moves a channel without +# an app inside it. # # THE GATE. Every verifying lane lives in this file — # Go (vet, lint, short tests), the Postgres integration suite, the web app @@ -88,23 +86,20 @@ name: release # path filters for the same reason: a web-only push still runs the Go suite, # because "not run" must never read as "passed". # -# What publishes, and is therefore gated: the image tags (image-release) and -# the APK + version sidecar attached to a tag's Release (release-assets). -# android-release only BUILDS the signed APK into a workflow artifact, which -# nobody outside this run can pull, so it runs in parallel with the lanes -# instead of after them; attaching it to the Release is the publishing half, -# and that half waits for the gate. +# What publishes, and is therefore gated: everything image-release pushes, the +# private image tags and the whole public release. android-release only BUILDS +# the signed APK into a workflow artifact, which nobody outside this run can +# pull, so it runs in parallel with the lanes instead of after them. # # To watch the gate refuse: dispatch this workflow with force_red=true. The go -# lane fails on purpose, and both publishing jobs must report skipped. +# lane fails on purpose, and the publishing job must report skipped. +# No path filter. The README, docs and tests ship in the public release too, +# so a merge to main that changes only them must still run, or it would not +# release. on: push: branches: [main, dev] - tags: ['v*'] - paths-ignore: - - 'docs/**' - - '**/*.md' workflow_dispatch: inputs: force_red: @@ -113,10 +108,10 @@ on: default: false # A rapid re-push to main supersedes the in-flight build: the later commit -# wins. Tags are immutable and unique, so no tag build can be superseded by -# another run on the same ref. +# wins. The event name is in the group so a dispatch and a push on the same +# ref never cancel each other. concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} cancel-in-progress: true jobs: @@ -153,8 +148,16 @@ jobs: - name: golangci-lint run: golangci-lint run ./... + # ci/testcount prints what plain go test would, plus how many tests + # ran. The step exits with go test's own status, kept aside in a file + # because the shell has no pipefail. The `|| rc=$?` matters: under + # `-e` a bare failing go test ends the group before its status is + # written, and a missing file fails the step as 1, never as a pass. - name: go test (short, race) - run: go test -short -race ./... + run: | + go build -o /tmp/testcount ./ci/testcount + { rc=0; go test -short -race -json ./... || rc=$?; echo "$rc" > /tmp/go-test-rc; } | /tmp/testcount + exit "$(cat /tmp/go-test-rc 2>/dev/null || echo 1)" # Full `go test -race` against an ephemeral Postgres. # @@ -273,16 +276,29 @@ jobs: fi # Apply embedded migrations to the fresh test DB, then run the - # full suite (no -short → integration tests execute). -p 1: - # every integration package TRUNCATEs the one shared test DB; - # concurrent package binaries → TRUNCATE deadlocks. Serialize - # package execution (the documented local invocation too). - # -timeout 20m: internal/api alone takes several minutes under - # -race on an idle runner, and a dev and a main run sharing the - # runner can push it past go test's default 10m with nothing - # hung. + # packages that hold database tests (no -short, so they execute). + # The `go` lane already runs every unit test; packages with no + # database test are left to it (ci/db-test-packages.sh). + # + # -p 1: every database package TRUNCATEs the one shared test DB, + # and concurrent package binaries deadlock on TRUNCATE. -p also + # bounds compiling, so the test binaries are built first with + # full parallelism (-run '^$' runs no test), and the serial pass + # reuses the build cache. + # + # -timeout 20m: internal/api alone takes minutes under -race on a + # busy runner, and a dev and a main run sharing the runner can + # push it past go test's default 10m with nothing hung. MINSTREL_DATABASE_URL="$MINSTREL_TEST_DATABASE_URL" go run ./cmd/minstrel migrate - go test -p 1 -race -timeout 20m ./... + PKGS=$(sh ci/db-test-packages.sh) + echo "database test packages: $(echo "$PKGS" | wc -l)" + go test -race -run '^$' $PKGS + # ci/testcount prints the usual go test output plus how many tests + # ran; the step exits with go test's own status (no pipefail, and + # `|| rc=$?` so -e cannot end the group before the status is kept). + go build -o /tmp/testcount ./ci/testcount + { rc=0; go test -p 1 -race -timeout 20m -json $PKGS || rc=$?; echo "$rc" > /tmp/go-test-rc; } | /tmp/testcount + exit "$(cat /tmp/go-test-rc 2>/dev/null || echo 1)" web: runs-on: go-ci @@ -359,6 +375,25 @@ jobs: - name: Unit tests run: ./gradlew testDebugUnitTest + # How many tests ran, summed from Gradle's JUnit reports. Runs after a + # failure too, so a red run still says how much of the suite it reached. + - name: Test count + if: always() + run: | + set -- app/build/test-results/testDebugUnitTest/*.xml + if [ ! -e "$1" ]; then echo "no unit test reports"; exit 0; fi + awk '/- - startsWith(github.ref, 'refs/tags/v') - || github.ref == 'refs/heads/dev' + github.ref == 'refs/heads/dev' || github.ref == 'refs/heads/main' runs-on: flutter-ci container: @@ -470,32 +503,6 @@ jobs: echo "channel=${channel}" >> "$GITHUB_OUTPUT" echo "::notice::APK $(printf '%s' "${out}" | tr '\n' ' ') channel=${channel}" - # Checked BEFORE the expensive work, not after it. "Attach APK to gitea - # Release" below resolves the release by tag and fails if it is absent — - # but that is the final step, so a tag pushed without a release would - # build an APK for several minutes first and only then find it has - # nowhere to put it. Same check, seconds in instead of minutes. - # - # Releases are normally created through the API (which creates the tag and - # the release together, so this passes). A bare `git push origin vX` is the - # case this catches. - - name: Release must exist for this tag - if: startsWith(github.ref, 'refs/tags/v') - shell: bash - working-directory: ${{ github.workspace }} - env: - CI_TOKEN: ${{ secrets.CI_TOKEN }} - run: | - set -euo pipefail - TAG="${GITHUB_REF#refs/tags/}" - if ! curl -fsSL -o /dev/null \ - -H "Authorization: token ${CI_TOKEN}" \ - "https://git.fabledsword.com/api/v1/repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}"; then - echo "::error::no release exists for ${TAG}. Create the release (which creates the tag) rather than pushing a bare tag — otherwise there is nothing to attach the APK to." - exit 1 - fi - echo "::notice::release found for ${TAG}" - - name: Cache Gradle dirs uses: actions/cache@v4 with: @@ -576,98 +583,21 @@ jobs: # artifact existing, so an empty upload must fail here, not there. if-no-files-found: error - # Publishes the signed APK and its version sidecar on the tag's Release. - # Split out of android-release so the APK can be BUILT in parallel with the - # lanes while being PUBLISHED only once they have all passed. - release-assets: - name: Attach APK to the Release (tag releases only) - needs: [go, integration, web, android, govulncheck, android-release] - if: >- - ${{ - !cancelled() - && needs.go.result == 'success' - && needs.integration.result == 'success' - && needs.web.result == 'success' - && needs.android.result == 'success' - && needs.govulncheck.result == 'success' - && needs.android-release.result == 'success' - && startsWith(github.ref, 'refs/tags/v') }} - runs-on: go-ci - container: - image: git.fabledsword.com/bvandeusen/ci-go:1.26 - - steps: - - name: Download signed APK artifact - uses: actions/download-artifact@v8 - with: - name: minstrel-apk - path: release-apk/ - - - name: Attach APK to gitea Release - # Tag releases only. A branch build has no Release to hang assets on - # and does not need one — its image bundles the APK, and the server - # serves it from /api/client/apk. - shell: bash - env: - CI_TOKEN: ${{ secrets.CI_TOKEN }} - VERSION_NAME: ${{ needs.android-release.outputs.version_name }} - VERSION_CODE: ${{ needs.android-release.outputs.version_code }} - run: | - set -euxo pipefail - TAG="${GITHUB_REF#refs/tags/}" - REPO="${GITHUB_REPOSITORY}" - APK_PATH="release-apk/app-release.apk" - ls -lh "${APK_PATH}" - - # Publish the version sidecar as a release asset next to the APK. - # - # This is what lets a later :latest build stop RECONSTRUCTING the - # bundled APK's version and simply read what was recorded. The - # ordering key in particular cannot be re-derived after the fact — - # it is build-time minutes, so once this job ends the value exists - # nowhere else. Reconstruction could only ever recover the name, - # and only by duplicating a formula that then has to be kept in - # step across two files. - SIDECAR_PATH="/tmp/minstrel.apk.version" - printf '{"name":"%s","code":%s,"channel":"stable"}\n' \ - "${VERSION_NAME}" "${VERSION_CODE}" > "${SIDECAR_PATH}" - cat "${SIDECAR_PATH}" - - RELEASE_JSON="$(curl -fsSL \ - -H "Authorization: token ${CI_TOKEN}" \ - "https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}")" - RELEASE_ID="$(printf '%s' "${RELEASE_JSON}" | grep -oP '"id":\s*\K[0-9]+' | head -1)" - if [ -z "${RELEASE_ID}" ]; then - echo "::error::release for ${TAG} not found"; exit 1 - fi - echo "release_id=${RELEASE_ID}" - - UPLOAD_HTTP=$(curl -sS -L -o /tmp/upload.out -w '%{http_code}' \ - -H "Authorization: token ${CI_TOKEN}" \ - -F "attachment=@${APK_PATH}" \ - "https://git.fabledsword.com/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=minstrel-${TAG}.apk") - echo "upload_http=${UPLOAD_HTTP}" - cat /tmp/upload.out || true - echo - if [ "${UPLOAD_HTTP}" -lt 200 ] || [ "${UPLOAD_HTTP}" -ge 300 ]; then - echo "::error::APK upload returned HTTP ${UPLOAD_HTTP}" - exit 1 - fi - - # Same treatment for the sidecar. Named `.apk.version` so the - # downloader's `\.apk$` match cannot pick it up by mistake. - SIDECAR_HTTP=$(curl -sS -L -o /tmp/upload-sidecar.out -w '%{http_code}' \ - -H "Authorization: token ${CI_TOKEN}" \ - -F "attachment=@${SIDECAR_PATH}" \ - "https://git.fabledsword.com/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=minstrel-${TAG}.apk.version") - echo "sidecar_upload_http=${SIDECAR_HTTP}" - cat /tmp/upload-sidecar.out || true - echo - if [ "${SIDECAR_HTTP}" -lt 200 ] || [ "${SIDECAR_HTTP}" -ge 300 ]; then - echo "::error::version sidecar upload returned HTTP ${SIDECAR_HTTP}" - exit 1 - fi - + # The image, and on main the public release. + # + # Every push builds its image FROM THE EXPORT, `git archive` of this commit, + # and runs the changelog and the leak gate on it first. So a dev push is the + # public release's dry run: an export that leaks or does not build is red the + # day it lands, not at the merge. + # + # A push to main is also the PUBLIC release, after the private push: + # 1. the export becomes one commit on github.com/Fabled-Sword/minstrel's + # main, tagged v, authored by AmateurDungeoneer and dated in UTC; + # 2. that tree is built into ghcr.io/fabled-sword/minstrel : and + # :latest, labelled with the public repository and commit; + # 3. a GitHub Release with the public changelog, and a release on this forge + # with the private one, both v, both naming the image. + # is YYYY.MM.DD.HHMM from the merge commit's time. image-release: name: Build + push container image # Every lane must have SUCCEEDED, each named here, and so must the APK @@ -689,34 +619,22 @@ jobs: env: IMAGE: git.fabledsword.com/bvandeusen/minstrel + PUBLIC_REPO: Fabled-Sword/minstrel + PUBLIC_IMAGE: ghcr.io/fabled-sword/minstrel steps: - name: Checkout uses: actions/checkout@v4 with: - # Full history: any job that DERIVES the version name needs it, - # because a shallow clone changes what git-derived values resolve to - # WITHOUT failing — a too-low value, silently, with every lane green. - # - # This job runs ci/version.sh itself: with no : image tags, - # the server's self-reported version is the only thing that says which - # build an image is. + # Full history and its tags: any job that DERIVES the version name + # needs it, because a shallow clone changes what git-derived values + # resolve to WITHOUT failing — a too-low value, silently, with every + # lane green. The changelog lists the commits since the previous + # release's tag, so it needs them too. fetch-depth: 0 - - name: Detect buildable project - id: guard - shell: bash - run: | - if [ -f Dockerfile ] && [ -f go.mod ]; then - echo "ready=true" >> "$GITHUB_OUTPUT" - else - echo "ready=false" >> "$GITHUB_OUTPUT" - echo "::notice::No Dockerfile + go.mod yet — release build skipped" - fi - - name: Compute image tags id: tags - if: steps.guard.outputs.ready == 'true' shell: bash run: | set -euo pipefail @@ -724,10 +642,10 @@ jobs: # THE VERSION, and it is derived the same way on every ref — the # branch decides the CHANNEL, never the version. # - # A per-ref string ("main", "dev", the tag name) would not order, and - # "dev" would be the same string forever — two dev images eight weeks - # apart indistinguishable in the UI. With no version image tags, this - # is how an admin tells which build a container is running. + # A per-ref string ("main", "dev") would not order, and "dev" would be + # the same string forever — two dev images eight weeks apart + # indistinguishable in the UI. The server's self-reported version is + # how an admin tells which build a private image is. # # `sed -n s///p` rather than `grep`: it exits 0 when nothing matches, # so the empty check below is actually reachable. A grep here would @@ -738,24 +656,7 @@ jobs: exit 1 fi - if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then - # A release refreshes the CHANNEL and mints nothing else. - # - # The tag build exists to produce the signed APK and attach it to - # the release; the image it rebuilds is the SAME SOURCE as the main - # build minutes earlier, differing only in which APK is baked in. - # When the same source is rebuilt with different contents, - # publish the moving channel tag and never a commit-addressable - # one. - # - # :latest moves here so the server hands out the same APK build - # that is attached to the Release: a phone that installed from the - # Release page and one that updated in-app hold one build, with one - # ordering key. Cut a release on main's tip, as :latest follows it. - CHANNEL=stable - echo "args=-t ${IMAGE}:latest" >> "$GITHUB_OUTPUT" - echo "::notice::Release build ${VERSION}: refreshing :latest around the new APK" - elif [[ "${GITHUB_REF}" == "refs/heads/dev" ]]; then + if [[ "${GITHUB_REF}" == "refs/heads/dev" ]]; then # The rolling test channel, and :dev ALONE — deliberately no # per-commit tag. A rolling channel is rolling by definition, so a # commit-addressable image here would be a rollback target nobody @@ -776,8 +677,72 @@ jobs: echo "version=${VERSION}" >> "$GITHUB_OUTPUT" echo "channel=${CHANNEL}" >> "$GITHUB_OUTPUT" + # The public release's name, and whether this run makes the release. + # Only a PUSH to main does: a dispatch on main rebuilds the private + # channel and publishes nothing outside this forge. + { + echo "EXPORT=${RUNNER_TEMP}/export" + echo "NAME=$(date -u -d "@$(git log -1 --format=%ct HEAD)" +%Y.%m.%d.%H%M)" + if [ "${GITHUB_EVENT_NAME}" = "push" ] && [ "${GITHUB_REF}" = "refs/heads/main" ]; then + echo "PUBLIC=true" + else + echo "PUBLIC=false" + fi + } >> "$GITHUB_ENV" + + # What a release would publish: the export, and its changelog. Neither + # may carry a banned word or a private record id (ci/leakgate.sh), and the + # export carries no CI file. + - name: Export, changelog and leak gate + shell: bash + run: | + set -euo pipefail + rm -rf "${EXPORT}" + mkdir -p "${EXPORT}" + git archive HEAD | tar -x -C "${EXPORT}" + for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json; do + if [ -e "${EXPORT}/${private}" ]; then + echo "::error::the export carries ${private}; .gitattributes export-ignore no longer covers it" + exit 1 + fi + done + bash ci/changelog.sh "${RUNNER_TEMP}/changelog" + echo "--- the public changelog of v${NAME} ---" + cat "${RUNNER_TEMP}/changelog/public.md" + echo "---" + bash ci/leakgate.sh "${EXPORT}" "${RUNNER_TEMP}/changelog/public.md" + + # The secrets the public half needs, checked before anything is pushed + # anywhere. A dev push warns about one that is missing or refused; a main + # push stops. Nothing here writes: the push token reads the public + # repository, and the forge token updates a release that does not exist. + - name: Public release secrets + shell: bash + env: + PUBLIC_PUSH_TOKEN: ${{ secrets.PUBLIC_PUSH_TOKEN }} + GHCR_USER: ${{ vars.GHCR_USER || secrets.GHCR_USER }} + GHCR_TOKEN: ${{ secrets.GHCR_TOKEN }} + FORGE_TOKEN: ${{ secrets.CI_TOKEN }} + run: | + set -u + bad="" + say() { bad="yes"; if [ "${PUBLIC}" = "true" ]; then echo "::error::$1"; else echo "::warning::$1"; fi; } + [ -n "${GHCR_USER}" ] || say "GHCR_USER is empty or unset (an Actions variable or secret)" + [ -n "${GHCR_TOKEN}" ] || say "the GHCR_TOKEN secret is empty or unset" + if [ -z "${PUBLIC_PUSH_TOKEN}" ]; then + say "the PUBLIC_PUSH_TOKEN secret is empty or unset" + else + auth="$(printf 'x-access-token:%s' "${PUBLIC_PUSH_TOKEN}" | base64 -w0)" + echo "::add-mask::${auth}" + git -c http.https://github.com/.extraheader="AUTHORIZATION: basic ${auth}" \ + ls-remote "https://github.com/${PUBLIC_REPO}.git" >/dev/null \ + || say "PUBLIC_PUSH_TOKEN cannot read github.com/${PUBLIC_REPO}" + fi + node ci/releases.mjs forge-probe || say "CI_TOKEN may not write this repository's releases" + if [ -n "${bad}" ] && [ "${PUBLIC}" = "true" ]; then exit 1; fi + exit 0 + - name: Registry login - if: steps.guard.outputs.ready == 'true' shell: bash run: | echo "${{ secrets.CI_TOKEN }}" \ @@ -785,7 +750,6 @@ jobs: - name: Download signed APK artifact # android-release just produced this, on every ref. - if: steps.guard.outputs.ready == 'true' # Consuming half of the pair: stock download-artifact, which works here for # the same reason as the upload (gitea/runner 3.x edits the GHES refusal # out of the bundle). v8 runs on node24, which every CI-runner image @@ -795,8 +759,8 @@ jobs: name: minstrel-apk path: client/ + # Into the export, which is what the image is built from. - name: Stage bundled APK + version sidecar - if: steps.guard.outputs.ready == 'true' shell: bash env: # All three pulled from android-release's outputs so the sidecar the @@ -810,15 +774,15 @@ jobs: # The artifact lands as `app-release.apk` (the original Gradle # output name). The Dockerfile COPYs client/* into /app/client/ # and the server reads minstrel.apk + minstrel.apk.version. - mv client/app-release.apk client/minstrel.apk + mv client/app-release.apk "${EXPORT}/client/minstrel.apk" printf '{"name":"%s","code":%s,"channel":"%s"}\n' \ "${APK_VERSION_NAME}" "${APK_VERSION_CODE}" "${APK_CHANNEL}" \ - > client/minstrel.apk.version - cat client/minstrel.apk.version - ls -lh client/ + > "${EXPORT}/client/minstrel.apk.version" + cat "${EXPORT}/client/minstrel.apk.version" + ls -lh "${EXPORT}/client/" - name: Build and push - if: steps.guard.outputs.ready == 'true' + shell: bash # --pull: the Dockerfile's base images are floating tags (golang:1.26, # debian:bookworm-slim). Without it the runner's daemon reuses # whatever it cached, and the shipped binary can sit on a Go patch @@ -828,83 +792,127 @@ jobs: docker buildx build --pull \ --build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \ --build-arg MINSTREL_CHANNEL="${{ steps.tags.outputs.channel }}" \ - --push ${{ steps.tags.outputs.args }} . + --push ${{ steps.tags.outputs.args }} "${EXPORT}" - # Verifies a tag release actually ended up complete, and names the specific - # thing that's missing if not. - # - # A release can be incomplete while looking fine. If android-release never - # starts (a runner failing to launch), its steps all report `failure` with - # none executed and image-release shows `skipped`. The run is red, but the - # release page renders and main's own push build has already moved - # `:latest`, so a release missing its APK and its image is easy to skim - # past. - # - # This job cannot prevent that; it turns an incomplete release into an - # explicit, named error instead of a row of mystery step failures. - # - # `if: always()` is the whole point: it has to report precisely when the jobs - # above did NOT succeed. - verify-release: - name: Verify release artifacts (tag releases only) - needs: [android-release, release-assets, image-release] - if: ${{ always() && startsWith(github.ref, 'refs/tags/v') }} - runs-on: go-ci - container: - image: git.fabledsword.com/bvandeusen/ci-go:1.26 - - steps: - - name: Release must have an APK attached + # THE PUBLIC RELEASE, a push to main only. The export becomes one commit + # on the public repository's main, replacing its whole tree so removed + # files go too, tagged v. Author, committer and tagger are the + # project's public identity, dated at this commit's time in UTC. + # + # A re-run finds v already there: on the same tree it goes on to the + # image and the releases, on a different tree it stops. A published tag + # is never moved. + - name: Public commit and tag + if: env.PUBLIC == 'true' shell: bash env: - CI_TOKEN: ${{ secrets.CI_TOKEN }} + PUBLIC_PUSH_TOKEN: ${{ secrets.PUBLIC_PUSH_TOKEN }} run: | set -euo pipefail - TAG="${GITHUB_REF#refs/tags/}" - REPO="${GITHUB_REPOSITORY}" - - REL_JSON="$(curl -fsSL \ - -H "Authorization: token ${CI_TOKEN}" \ - "https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}" || true)" - if [ -z "${REL_JSON}" ]; then - echo "::error::no release found for ${TAG} — the tag exists but nothing was published" - exit 1 + auth="$(printf 'x-access-token:%s' "${PUBLIC_PUSH_TOKEN}" | base64 -w0)" + echo "::add-mask::${auth}" + pub="${RUNNER_TEMP}/public" + rm -rf "${pub}" + git init -q -b main "${pub}" + cd "${pub}" + git config http.https://github.com/.extraheader "AUTHORIZATION: basic ${auth}" + git remote add origin "https://github.com/${PUBLIC_REPO}.git" + # An empty repository has no main yet, and its first release starts it. + if [ -n "$(git ls-remote --heads origin main)" ]; then + git fetch -q --depth 1 origin main + git checkout -q -B main FETCH_HEAD fi - - APK="$(printf '%s' "${REL_JSON}" \ - | grep -oP '"browser_download_url":\s*"\K[^"]+' \ - | grep -E '\.apk$' | head -1 || true)" - if [ -z "${APK}" ]; then - echo "::error::release ${TAG} has NO APK attached — in-app update will offer nothing, and the bundled-APK path on future :latest builds has no source." - echo "::error::Fix by RE-RUNNING this workflow run. Do NOT delete and re-create the tag; if it fails again the runner never started the container, and the evidence is in act_runner on the host (Gitea will hold no job log)." - exit 1 + find . -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} + + # A fresh archive, not the build context, which also holds the app. + git -C "${GITHUB_WORKSPACE}" archive HEAD | tar -xf - + # -f: the export exactly, a tracked file a .gitignore matches + # (the generated token CSS) included. + git add -A -f + tree="$(git write-tree)" + when="@$(git -C "${GITHUB_WORKSPACE}" log -1 --format=%ct HEAD) +0000" + if [ -n "$(git ls-remote --tags origin "refs/tags/v${NAME}")" ]; then + git fetch -q --depth 1 origin "refs/tags/v${NAME}:refs/tags/v${NAME}" + if [ "$(git rev-parse "v${NAME}^{tree}")" != "${tree}" ]; then + echo "::error::the public tag v${NAME} holds another tree; a published tag is never moved" + exit 1 + fi + echo "::notice::v${NAME} is already published with this tree" + else + export GIT_AUTHOR_NAME=AmateurDungeoneer GIT_AUTHOR_EMAIL=amateurdungeoneer@fabledsword.com + export GIT_COMMITTER_NAME=AmateurDungeoneer GIT_COMMITTER_EMAIL=amateurdungeoneer@fabledsword.com + export GIT_AUTHOR_DATE="${when}" GIT_COMMITTER_DATE="${when}" + git commit -q -m "Release ${NAME}" + git tag -a "v${NAME}" -m "Release ${NAME}" + git push -q origin main "refs/tags/v${NAME}" fi + echo "REVISION=$(git rev-parse "v${NAME}^{commit}")" >> "$GITHUB_ENV" - echo "::notice::APK attached: ${APK}" + # The same export, built again with the release's name and labels that + # point at the public repository and commit, so nothing in the image + # points back here. Every layer but the stamped binary comes from the + # build above. --provenance=false and no SBOM: an attestation would carry + # this workbench's build details into a public registry. + - name: Public image + if: env.PUBLIC == 'true' + shell: bash + env: + GHCR_USER: ${{ vars.GHCR_USER || secrets.GHCR_USER }} + GHCR_TOKEN: ${{ secrets.GHCR_TOKEN }} + run: | + set -euo pipefail + docker build --provenance=false \ + --build-arg MINSTREL_VERSION="${NAME}" \ + --build-arg MINSTREL_CHANNEL=stable \ + --label "org.opencontainers.image.source=https://github.com/${PUBLIC_REPO}" \ + --label "org.opencontainers.image.revision=${REVISION}" \ + --label "org.opencontainers.image.version=${NAME}" \ + -t "${PUBLIC_IMAGE}:${NAME}" "${EXPORT}" + labelled="$(docker inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "${PUBLIC_IMAGE}:${NAME}")" + test "${labelled}" = "${REVISION}" || { echo "::error::the image names commit ${labelled}, not ${REVISION}"; exit 1; } + printf '%s' "${GHCR_TOKEN}" | docker login ghcr.io -u "${GHCR_USER}" --password-stdin + # : is never re-pushed, so a re-run only moves :latest. + if docker manifest inspect "${PUBLIC_IMAGE}:${NAME}" >/dev/null 2>&1; then + echo "::notice::${PUBLIC_IMAGE}:${NAME} is already published; only :latest moves" + else + docker push "${PUBLIC_IMAGE}:${NAME}" + fi + docker tag "${PUBLIC_IMAGE}:${NAME}" "${PUBLIC_IMAGE}:latest" + docker push "${PUBLIC_IMAGE}:latest" + echo "DIGEST=$(docker inspect --format '{{ index .RepoDigests 0 }}' "${PUBLIC_IMAGE}:${NAME}")" >> "$GITHUB_ENV" - # The other half. Checking only the APK would report success on a release - # whose image push failed. `always()` on this job means it runs even when - # image-release failed, so without this the guard would cheerfully verify - # an incomplete release. - # - # The image checked is the : rollback target, which main's own build - # published for this same commit before the tag was cut (there are no - # version image tags). It catches an image push that silently did not - # happen, and it proves the ORDERING — a tag cut on a commit whose main - # build never completed has no rollback target, and that is worth failing - # on rather than discovering during an incident. - - name: Rollback image must exist for the tagged commit + # The release pages, each created or updated in place: GitHub's with the + # public changelog, this forge's with the private one, tagging this + # commit. Both name the image. No files are attached: the app ships + # inside the image. + - name: Public and private releases + if: env.PUBLIC == 'true' + shell: bash + env: + PUBLIC_PUSH_TOKEN: ${{ secrets.PUBLIC_PUSH_TOKEN }} + FORGE_TOKEN: ${{ secrets.CI_TOKEN }} + run: | + set -euo pipefail + cl="${RUNNER_TEMP}/changelog" + for side in public private; do + { + cat "${cl}/${side}.md" + printf '\nImage: `%s:%s`\n' "${PUBLIC_IMAGE}" "${NAME}" + } > "${cl}/${side}-body.md" + done + echo "GITHUB_RELEASE=$(node ci/releases.mjs github "v${NAME}" "${cl}/public-body.md")" >> "$GITHUB_ENV" + echo "FORGE_RELEASE=$(node ci/releases.mjs forge "v${NAME}" "${cl}/private-body.md" "${GITHUB_SHA}")" >> "$GITHUB_ENV" + + # The record the release task keeps. + - name: Published shell: bash run: | - set -euo pipefail - IMAGE="git.fabledsword.com/bvandeusen/minstrel" - - echo "${{ secrets.CI_TOKEN }}" \ - | docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin - - if ! docker manifest inspect "${IMAGE}:${GITHUB_SHA}" > /dev/null 2>&1; then - echo "::error::image ${IMAGE}:${GITHUB_SHA} does not exist — this commit has no rollback target." - echo "::error::That image is published by the MAIN build of this commit, not by the tag build. If main's build never ran or failed, fix that first; a release whose commit cannot be rolled back to is the thing this check exists to refuse." - exit 1 + echo "pushed ${{ steps.tags.outputs.args }}" + if [ "${PUBLIC}" = "true" ]; then + echo "release v${NAME} of workbench ${GITHUB_SHA}" + echo "public commit ${REVISION}" + echo "image ${DIGEST}" + echo "GitHub release ${GITHUB_RELEASE}" + echo "forge release ${FORGE_RELEASE}" + else + echo "dry run of release v${NAME}: export, changelog and leak gate passed, image built from the export" fi - echo "::notice::rollback target verified: ${IMAGE}:${GITHUB_SHA}" diff --git a/.gitignore b/.gitignore index 97c979c9..1bf1e1ca 100644 --- a/.gitignore +++ b/.gitignore @@ -54,7 +54,7 @@ GEMINI.md .windsurfrules .aider.conf.yml -# Native Android (Kotlin/Compose) — M8 rewrite +# Native Android (Kotlin/Compose) android/.gradle/ android/.kotlin/ android/.idea/ @@ -63,11 +63,11 @@ android/app/build/ android/local.properties android/*.iml android/app/*.iml -# Release signing material — keystore + extracted credentials live local -# only; the canonical copy is the Gitea repo secret (ANDROID_KEYSTORE_B64 -# + the alias/password secrets). Losing the local file is fine; losing -# the secret means rebuilding the keystore + reinstalling all clients. +# Release signing material: a keystore never belongs in the repo. android/*.keystore android/*.keystore.* android/*.jks android/keystore.properties + +# Python bytecode from the tools/ scripts +__pycache__/ diff --git a/Dockerfile b/Dockerfile index d69a99d8..92e7e7bd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,7 +15,7 @@ COPY . . # Overwrite the committed placeholder with the freshly-built SPA assets. COPY --from=web /web/build ./web/build ENV CGO_ENABLED=0 -# Version stamping. release.yml passes the DERIVED version name +# Version stamping. The release build passes the DERIVED version name # (YYYY.MM.DD.HHMM) and the lane's channel; a local `docker build` falls back # to "dev"/"local". Both are surfaced at /healthz. # @@ -27,8 +27,8 @@ ARG MINSTREL_VERSION=dev ARG MINSTREL_CHANNEL=local RUN go build -trimpath \ -ldflags="-s -w \ - -X 'git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo.Version=${MINSTREL_VERSION}' \ - -X 'git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \ + -X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Version=${MINSTREL_VERSION}' \ + -X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \ -o /out/minstrel ./cmd/minstrel FROM debian:bookworm-slim @@ -57,9 +57,8 @@ RUN mkdir -p /app/data /app/client && chown -R minstrel:minstrel /app WORKDIR /app # In-app update channel. client/ in the build context holds -# minstrel.apk + minstrel.apk.version, which release.yml fills on every -# build (dev and tag pushes bundle their own APK, main bundles the latest -# release's); a local build has only .gitkeep + README. Endpoints return +# minstrel.apk + minstrel.apk.version, which the release build fills; a +# local build has only .gitkeep + README. Endpoints return # 404 when the APK files aren't present, so such an image degrades # gracefully. COPY --chown=minstrel:minstrel client/ /app/client/ diff --git a/LICENSE b/LICENSE index b94c4797..be3f7b28 100644 --- a/LICENSE +++ b/LICENSE @@ -1,9 +1,661 @@ -MIT License + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 -Copyright (c) 2026 bvandeusen + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + Preamble -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/Makefile b/Makefile index be1fefb8..8ef937eb 100644 --- a/Makefile +++ b/Makefile @@ -7,8 +7,8 @@ SQLC_VERSION := 1.31.1 generate: docker run --rm -v "$(CURDIR):/src" -w /src sqlc/sqlc:$(SQLC_VERSION) generate -# Same codegen, run as a Go tool instead of a container. This is the CI path: -# the ci-go image already has Go, so it avoids docker-in-docker. Pinned to the +# Same codegen, run as a Go tool instead of a container, for a machine that +# has Go but no Docker. Pinned to the # SAME version as `generate` above so both routes emit identical output. generate-go: go run github.com/sqlc-dev/sqlc/cmd/sqlc@v$(SQLC_VERSION) generate @@ -38,9 +38,10 @@ test-short: test-integration: docker compose up -d postgres -docker compose exec -T postgres createdb -U minstrel minstrel_test - # -p 1: integration packages share one test DB and each TRUNCATEs it; - # concurrent package binaries deadlock on TRUNCATE. Serialize packages. - MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel_test?sslmode=disable go test -p 1 -race ./... + # Only packages with database tests; test-short covers the rest. + # -p 1: they share one test DB and each TRUNCATEs it; concurrent + # package binaries deadlock on TRUNCATE. Serialize packages. + MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel_test?sslmode=disable go test -p 1 -race $$(sh ci/db-test-packages.sh) lint: golangci-lint run ./... diff --git a/README.md b/README.md index acb40640..8f7ea45b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,19 @@ -

Minstrel logo

+

Fabled Minstrel logo

-

Minstrel

+

Fabled Minstrel

A self-hosted music server that picks what to play next.

-Minstrel serves your music library to the web, to its own Android app, and to any Subsonic client. Shuffle, radio, likes and play history are worked out on the server, so every device gets the same mixes and the same history. It can also find, download and file the albums you want, through a search service and a download client you run yourself. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle. +Fabled Minstrel serves your music library to the web, to its own Android app, and to Subsonic apps. Shuffle, radio, likes and play history are worked out on the server, so the web app, the Android app and Subsonic apps get the same mixes and the same history, and what you like and play in a Subsonic app counts too. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle. -Minstrel home — your library at a glance +Minstrel's Home: daily mixes, Songs like, and genre mixes ordered by what you play most + +

+Now playing, with the queue beside it +Home on a phone +

+ +The music in these screenshots is invented: every artist, album, cover and song was generated for them (tools/demo-library). ## Quick start @@ -14,7 +21,7 @@ Minstrel serves your music library to the web, to its own Android app, and to an # compose.yaml services: minstrel: - image: git.fabledsword.com/bvandeusen/minstrel:latest + image: ghcr.io/fabled-sword/minstrel:latest ports: ['4533:4533'] volumes: - ./music:/music # your library; must be writable by uid 1000 @@ -48,10 +55,10 @@ Open `http://:4533/register` and create the first account with that setup 1. **Let the first scan finish.** Minstrel scans the library on startup. Watch it, or scan again, on the **Admin** page (`/admin`). Later scans only pick up what changed. 2. **Install the Android app.** In **Settings** (`/settings`), the *Install the Android app* card downloads the app this server ships. It updates itself from your server after that. -3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token or turn on open registration. Each person gets their own likes, history and recommendations. -4. **Optional: connect services.** Add a search service and a download client in **Admin › Acquisition** (`/admin/acquisition`). Each person adds their own ListenBrainz token in **Settings › Connections**. -The Admin page, where the library scan runs and reports progress + **On an iPhone** there is no Minstrel app; use a Subsonic app such as play:Sub or Amperfy. Make a password for it in **Settings › Connections › Subsonic apps**, and give the app your server's address, your username and that password. Subsonic apps can browse, search, play, like and scrobble, and make and edit playlists. Minstrel's daily mixes appear in them as playlists, and when an app asks the server for random songs or an instant mix it gets Minstrel's smart shuffle and radio. An app that shuffles on the phone instead shuffles at random. +3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token for each person; an invite is the only way to an account. Each person gets their own likes, history and recommendations. +4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**. ## Configuration @@ -64,11 +71,11 @@ The quick start sets everything that's required. These are the settings people m | `MINSTREL_BRANDING_APP_NAME` | The name shown in the header, the browser tab and link previews. | | `MINSTREL_LOG_LEVEL` | `debug`, `info`, `warn` or `error`. | -Search services, download clients, ListenBrainz, email and recommendation tuning are set in the web UI and take effect without a restart. The full file-based surface is in [`config.example.yaml`](./config.example.yaml); to use it, mount your copy at `/etc/smartmusic/config.yaml`. +ListenBrainz, email, metadata sources and recommendation tuning are set in the web UI and take effect without a restart. The full file-based surface is in [`config.example.yaml`](./config.example.yaml); to use it, mount your copy at `/etc/smartmusic/config.yaml`. ## Setup pitfalls -- **The library mount has to be writable by uid 1000.** Minstrel files the albums it downloads into the library, and it deletes a file when an admin asks it to. It never moves, renames or retags files that were already there. Mount the library `:ro` to forbid writes: those actions then refuse and say why. +- **The library mount has to be writable by uid 1000.** Minstrel deletes a file only when an admin asks it to, such as merging duplicates. It never adds, moves, renames or retags files there (album art it finds or fetches is kept in its own data folder), so a tagger or download manager can keep filing into the same folder. Mount the library `:ro` to forbid writes: those actions then refuse and say why. - **`MINSTREL_LIBRARY_SCAN_PATHS` names the path inside the container** (`/music`), not the folder on your host. - **On the internet, put it behind HTTPS.** Plain `http://` is fine on a network you trust. For a public server, bind the port to `127.0.0.1` and put a reverse proxy in front: see [docs/hosting.md](docs/hosting.md). @@ -80,11 +87,10 @@ docker compose pull && docker compose up -d Database migrations run at startup. Image tags: -- `:latest`: the stable release. Most people should run this. -- `:`: one fixed build. Pin one to stop updates, or to roll back. -- `:dev`: the test channel, rebuilt on every change. It may break, and the fix is the next build. +- `:latest`: the newest release. Most people should run this. +- `:`, such as `:2026.12.04.1530`: one release, which never changes. Pin one to stop updates, or to roll back. The [releases page](https://github.com/Fabled-Sword/minstrel/releases) lists each one with what changed. -Every image carries a signed Android app, all with the same key, so a phone can move between channels without reinstalling. Rolling back a SHA tag rolls back the app it carries too. +Every image carries a signed Android app, all with the same key, so a phone can move between versions without reinstalling. Rolling back to an older version rolls back the app it carries too. **Back up the Postgres volume** with `pg_dump`. It holds accounts, likes, play history, playlists and settings, and a migration can only be undone by restoring a dump. The `minstrel-data` volume holds artwork and caches that Minstrel rebuilds if lost. @@ -103,37 +109,32 @@ Every image carries a signed Android app, all with the same key, so a phone can - Duplicates, missing files and suspect copies are found and listed under **Collection** for an admin to fix. - Missing album art and MusicBrainz ids are filled in automatically. -**Getting music** -- A wanted list: requests from the household, artists you follow, and albums whose files went missing. -- Minstrel searches the indexers you configure, hands the best release to your download client, checks what arrives against MusicBrainz, tags it, and files it. A better copy replaces a poor one. -- Off until you add a search service and a download client. - **Clients and accounts** - A full web app, built into the server. - A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server. -- OpenSubsonic-compatible, so existing clients such as DSub, Symfonium and play:Sub connect as they are. +- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, carry a play queue from one device to another, show lyrics (from a `.lrc` file beside the song, or the song's own tags), see the daily mixes, make and edit your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs. - Separate accounts for each person, with invites, and an inbox for what happened while you were away. ## Scope and responsible use -Minstrel indexes the files you point it at and streams them to your own clients. It ships no indexers, no trackers, no torrent, Usenet or NZB engine of its own, and no DRM circumvention. +Minstrel indexes the files you point it at and streams them to your own clients. It does not find or download music, and it does no DRM circumvention. -Getting music is optional and does nothing until you configure it. It searches only the search service (Prowlarr or a Torznab indexer) and the download client (qBittorrent) you add yourself. +What you put in your library is your responsibility. Copyright law applies to your collection as it does to any other software that plays a file; please respect it, and the terms of any service you connect. -What you put in your library, and the sources you configure, are your responsibility. Copyright law applies to your collection as it does to any other software that plays a file; please respect it, and the terms of any service you connect. - -Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz, Prowlarr, qBittorrent or Subsonic. +Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz or Subsonic. ## Development - **Backend:** `docker compose up` in this repo runs Postgres and Minstrel on `:4533`. - **Web:** `cd web && npm install && npm run dev` starts Vite on `:5173`. It proxies `/api/*` and `/rest/*` to `:4533`. -- **Tests:** `make test-short` runs the unit tests. `make test-integration` also runs the database tests, against a separate `minstrel_test` database so your dev data is never truncated. +- **Tests:** `make test-short` runs the unit tests. `make test-integration` runs the database tests, against a separate `minstrel_test` database so your dev data is never truncated. - **Image:** `docker build -t minstrel .` builds the web app and embeds it in the server binary. - **Branches:** work lands on `dev`; `main` changes through pull requests from `dev`. -How accounts and sessions are protected: [docs/security.md](docs/security.md). +How accounts and sessions are protected, and which outside services Minstrel contacts: [docs/security.md](docs/security.md). ## License -MIT. See [LICENSE](./LICENSE). +GNU Affero General Public License v3.0. See [LICENSE](./LICENSE). + +You can run, change and share Minstrel freely. If you run a changed copy that other people use over a network, you must offer those people the source of your changes. diff --git a/android/.idea/.gitignore b/android/.idea/.gitignore deleted file mode 100644 index 26d33521..00000000 --- a/android/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/android/.idea/.name b/android/.idea/.name deleted file mode 100644 index 81ab2e5c..00000000 --- a/android/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -Minstrel \ No newline at end of file diff --git a/android/.idea/AndroidProjectSystem.xml b/android/.idea/AndroidProjectSystem.xml deleted file mode 100644 index 4a53bee8..00000000 --- a/android/.idea/AndroidProjectSystem.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/android/.idea/caches/deviceStreaming.xml b/android/.idea/caches/deviceStreaming.xml deleted file mode 100644 index 5dc2fb2b..00000000 --- a/android/.idea/caches/deviceStreaming.xml +++ /dev/null @@ -1,1857 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android/.idea/codeStyles/Project.xml b/android/.idea/codeStyles/Project.xml deleted file mode 100644 index 7643783a..00000000 --- a/android/.idea/codeStyles/Project.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/android/.idea/codeStyles/codeStyleConfig.xml b/android/.idea/codeStyles/codeStyleConfig.xml deleted file mode 100644 index 79ee123c..00000000 --- a/android/.idea/codeStyles/codeStyleConfig.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/android/.idea/compiler.xml b/android/.idea/compiler.xml deleted file mode 100644 index b86273d9..00000000 --- a/android/.idea/compiler.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android/.idea/deploymentTargetSelector.xml b/android/.idea/deploymentTargetSelector.xml deleted file mode 100644 index ca16a995..00000000 --- a/android/.idea/deploymentTargetSelector.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/android/.idea/deviceManager.xml b/android/.idea/deviceManager.xml deleted file mode 100644 index 91f95584..00000000 --- a/android/.idea/deviceManager.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android/.idea/gradle.xml b/android/.idea/gradle.xml deleted file mode 100644 index 639c779c..00000000 --- a/android/.idea/gradle.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/android/.idea/migrations.xml b/android/.idea/migrations.xml deleted file mode 100644 index f8051a6f..00000000 --- a/android/.idea/migrations.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android/.idea/misc.xml b/android/.idea/misc.xml deleted file mode 100644 index b2c751a3..00000000 --- a/android/.idea/misc.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/android/.idea/runConfigurations.xml b/android/.idea/runConfigurations.xml deleted file mode 100644 index 16660f1d..00000000 --- a/android/.idea/runConfigurations.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android/.idea/vcs.xml b/android/.idea/vcs.xml deleted file mode 100644 index 6c0b8635..00000000 --- a/android/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 0b0cf2a7..3c54f6ad 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -100,6 +100,42 @@ android { } } +// The app's error messages are the web app's: web/src/lib/styles holds the +// copy for each server error code (error-copy.json) and the codes whose +// server message is appended (error-detail-codes.json). Both are copied in as +// Java resources, which ErrorCopy reads, so the two clients say the same thing +// and a new code is added once. +abstract class CopySharedCopyTask : DefaultTask() { + @get:InputFiles + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val sources: ConfigurableFileCollection + + @get:OutputDirectory + abstract val outputDir: DirectoryProperty + + @TaskAction + fun copy() { + val out = outputDir.get().asFile + out.deleteRecursively() + out.mkdirs() + sources.forEach { it.copyTo(File(out, it.name), overwrite = true) } + } +} + +val copySharedCopy = + tasks.register("copySharedCopy") { + sources.from( + rootProject.file("../web/src/lib/styles/error-copy.json"), + rootProject.file("../web/src/lib/styles/error-detail-codes.json"), + ) + } + +androidComponents { + onVariants { variant -> + variant.sources.resources?.addGeneratedSourceDirectory(copySharedCopy, CopySharedCopyTask::outputDir) + } +} + // Kotlin 2.x: `kotlinOptions { ... }` inside `android { }` is gone; the // modern shape is the top-level `kotlin { compilerOptions { ... } }` block, // which works whether Kotlin comes from AGP 9's built-in path or an @@ -196,6 +232,8 @@ dependencies { testImplementation(libs.mockk) testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.okhttp.mockwebserver) + // HeldCertificate: a test-only CA, so the server probe can be driven over real TLS. + testImplementation(libs.okhttp.tls) // kxml2 — provides an org.xmlpull.v1 impl on the JVM unit-test // classpath. Android's stock XmlPullParserFactory resolves to the // android.jar Stub on JVM tests; kxml2 is picked up via service- diff --git a/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt b/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt index cb90f2e4..65c7edf0 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt @@ -24,6 +24,7 @@ import androidx.core.content.ContextCompat import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope +import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.auth.ui.AuthGateViewModel @@ -33,6 +34,7 @@ import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.nav.DetailSeedCache import com.fabledsword.minstrel.nav.LocalDetailSeedCache +import com.fabledsword.minstrel.nav.Login import com.fabledsword.minstrel.nav.MinstrelNavGraph import com.fabledsword.minstrel.nav.Notifications import com.fabledsword.minstrel.nav.NowPlaying @@ -177,6 +179,7 @@ private fun App( navController.navigate(route) { launchSingleTop = true } onOpenedRoute() } + SignInWhenSessionRejected(gate, navController) MinstrelNavGraph( navController = navController, startDestination = resolved, @@ -187,6 +190,24 @@ private fun App( } } +/** + * When the server ends the session while the app is in use, opens the + * sign-in screen rather than leaving the user on screens whose every + * request fails. + */ +@Composable +private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) { + val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle() + LaunchedEffect(sessionRejected, navController) { + if (!sessionRejected) return@LaunchedEffect + navController.navigate(Login) { + popUpTo(0) { inclusive = true } + launchSingleTop = true + } + gate.consumeSessionRejected() + } +} + @Composable private fun BootSplash() { Surface( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt index b1bea272..988f8355 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt @@ -11,9 +11,10 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Read-through accessor for the admin quarantine queue. No Room cache — - * same rationale as AdminRequests. Three resolution actions all delete - * the row from the queue once the server accepts them. + * Read-through accessor for the admin Reports queue. No Room cache: it is an + * admin's live work list, read fresh each time, and its actions go straight + * to the server, so offline they fail with the reason rather than queueing. + * Each action takes the row off the queue once the server accepts it. */ @Singleton class AdminQuarantineRepository @Inject constructor( @@ -25,6 +26,8 @@ class AdminQuarantineRepository @Inject constructor( suspend fun resolve(trackId: String) = api.resolve(trackId) + suspend fun removeFile(trackId: String) = api.removeFile(trackId) + suspend fun deleteFile(trackId: String) = api.deleteFile(trackId) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepository.kt deleted file mode 100644 index 9c4c94cc..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepository.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.fabledsword.minstrel.admin.data - -import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.Retrofit -import retrofit2.create -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Read-through accessor for the admin cross-user requests queue. - * - * No Room caching — admin actions are infrequent and don't benefit - * from offline scrollback. `approve` and `reject` fire direct REST - * (no mutation queue) because admin confirmation is point-and-shoot; - * if the request fails the UI surfaces the error and rolls back. - */ -@Singleton -class AdminRequestsRepository @Inject constructor( - retrofit: Retrofit, -) { - private val api: AdminRequestsApi = retrofit.create() - - suspend fun list(): List = api.list().map { it.toDomain() } - - suspend fun approve(id: String) = api.approve(id) - - suspend fun reject(id: String) = api.reject(id) -} - -private fun RequestWire.toDomain(): RequestRef = RequestRef( - id = id, - userId = userId, - username = username, - status = RequestStatus.fromWire(status), - kind = kind, - artistName = artistName, - albumTitle = albumTitle, - trackTitle = trackTitle, - requestedAt = requestedAt, - decidedAt = decidedAt, - notes = notes, - importedAlbumCount = importedAlbumCount, - importedTrackCount = importedTrackCount, - matchedTrackId = matchedTrackId, - matchedAlbumId = matchedAlbumId, - matchedArtistId = matchedArtistId, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt index b45a2dbe..505c54a7 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt @@ -3,7 +3,6 @@ package com.fabledsword.minstrel.admin.data import com.fabledsword.minstrel.api.endpoints.AdminUsersApi import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody import com.fabledsword.minstrel.api.endpoints.SetAdminBody -import com.fabledsword.minstrel.api.endpoints.SetAutoApproveBody import com.fabledsword.minstrel.models.AdminUserRef import com.fabledsword.minstrel.models.wire.AdminUserWire import retrofit2.Retrofit @@ -27,9 +26,6 @@ class AdminUsersRepository @Inject constructor( suspend fun setAdmin(id: String, isAdmin: Boolean) = api.setAdmin(id, SetAdminBody(isAdmin)) - suspend fun setAutoApprove(id: String, autoApprove: Boolean) = - api.setAutoApprove(id, SetAutoApproveBody(autoApprove)) - suspend fun resetPassword(id: String, newPassword: String) = api.resetPassword(id, ResetPasswordBody(newPassword)) @@ -41,6 +37,5 @@ private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef( username = username, displayName = displayName, isAdmin = isAdmin, - autoApproveRequests = autoApproveRequests, createdAt = createdAt, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt index 9fd6b7dc..ba558f7d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt @@ -26,21 +26,19 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController -import com.composables.icons.lucide.Inbox import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Music import com.composables.icons.lucide.TriangleAlert import com.composables.icons.lucide.Users import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository -import com.fabledsword.minstrel.admin.data.AdminRequestsRepository import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository import com.fabledsword.minstrel.admin.data.AdminUsersRepository -import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.AdminQuarantine -import com.fabledsword.minstrel.nav.AdminRequests import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminUsers +import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.loadUiState import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.LoadingCentered @@ -58,25 +56,21 @@ import javax.inject.Inject // ─── State ─────────────────────────────────────────────────────────── -data class AdminCounts(val requests: Int, val quarantine: Int, val users: Int, val tagSources: Int) +data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int) -sealed interface AdminLandingUiState { - data object Loading : AdminLandingUiState - data class Success(val counts: AdminCounts) : AdminLandingUiState - data class Error(val message: String) : AdminLandingUiState -} +/** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */ +typealias AdminLandingUiState = UiState // ─── ViewModel ─────────────────────────────────────────────────────── @HiltViewModel class AdminLandingViewModel @Inject constructor( - private val requestsRepo: AdminRequestsRepository, private val quarantineRepo: AdminQuarantineRepository, private val usersRepo: AdminUsersRepository, private val tagSourcesRepo: AdminTagSourcesRepository, ) : ViewModel() { - private val internal = MutableStateFlow(AdminLandingUiState.Loading) + private val internal = MutableStateFlow(UiState.Loading) val uiState: StateFlow = internal.asStateFlow() init { @@ -84,22 +78,14 @@ class AdminLandingViewModel @Inject constructor( } fun refresh(): Job = viewModelScope.launch { - internal.value = AdminLandingUiState.Loading - try { - val counts = coroutineScope { - val req = async { requestsRepo.list().size } + internal.value = UiState.Loading + internal.value = loadUiState { + coroutineScope { val qua = async { quarantineRepo.list().size } val usr = async { usersRepo.list().size } val tag = async { tagSourcesRepo.list().count { it.enabled } } - AdminCounts(req.await(), qua.await(), usr.await(), tag.await()) + UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await())) } - internal.value = AdminLandingUiState.Success(counts) - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = AdminLandingUiState.Error( - ErrorCopy.fromThrowable(e), - ) } } } @@ -129,13 +115,13 @@ fun AdminLandingScreen( modifier = Modifier.fillMaxSize().padding(inner), ) { when (val s = state) { - AdminLandingUiState.Loading -> LoadingCentered() - is AdminLandingUiState.Error -> EmptyState( + UiState.Loading, UiState.Empty -> LoadingCentered() + is UiState.Error -> EmptyState( title = "Couldn't load admin counts", body = s.message, ) - is AdminLandingUiState.Success -> SectionList( - counts = s.counts, + is UiState.Success -> SectionList( + counts = s.data, navController = navController, ) } @@ -150,20 +136,11 @@ private fun SectionList(counts: AdminCounts, navController: NavHostController) { contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - item { - SectionCard( - icon = Lucide.Inbox, - title = "Requests", - subtitle = "Approve or reject requests for new music", - count = counts.requests, - onClick = { navController.navigate(AdminRequests) }, - ) - } item { SectionCard( icon = Lucide.TriangleAlert, - title = "Quarantine", - subtitle = "Resolve scan failures", + title = "Reports", + subtitle = "Tracks listeners flagged", count = counts.quarantine, onClick = { navController.navigate(AdminQuarantine) }, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt index 16873f6f..2eb1200a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt @@ -21,7 +21,9 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow @@ -31,6 +33,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.fabledsword.minstrel.models.AdminQuarantineItemRef import com.fabledsword.minstrel.nav.AdminQuarantine +import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry @@ -56,7 +60,7 @@ fun AdminQuarantineScreen( modifier = Modifier.fillMaxSize(), topBar = { MinstrelTopAppBar( - title = "Admin · Quarantine", + title = "Admin · Reports", navController = navController, currentRouteName = AdminQuarantine::class.qualifiedName, onBack = { navController.popBackStack() }, @@ -69,20 +73,21 @@ fun AdminQuarantineScreen( modifier = Modifier.fillMaxSize().padding(inner), ) { when (val s = state) { - AdminQuarantineUiState.Loading -> LoadingCentered() - AdminQuarantineUiState.Empty -> EmptyState( - title = "Queue is empty", - body = "When users flag tracks as bad rips, wrong tags, or " + - "duplicates, their reports get aggregated and surfaced here.", + UiState.Loading -> LoadingCentered() + UiState.Empty -> EmptyState( + title = "No reports", + body = "When listeners flag a track as a bad rip, wrong tags or " + + "a duplicate, their reports gather here.", ) - is AdminQuarantineUiState.Error -> ErrorRetry( + is UiState.Error -> ErrorRetry( title = "Couldn't load queue", message = s.message, onRetry = { viewModel.refresh() }, ) - is AdminQuarantineUiState.Success -> QueueList( - rows = s.rows, + is UiState.Success -> QueueList( + rows = s.data, onResolve = viewModel::resolve, + onRemoveFile = viewModel::removeFile, onDeleteFile = viewModel::deleteFile, ) } @@ -90,28 +95,85 @@ fun AdminQuarantineScreen( } } +/** A confirm asked of the admin before a removal: which one, and of which track. */ +private enum class Removal { File, Library } + +private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal) + @Composable private fun QueueList( rows: List, onResolve: (String) -> Unit, + onRemoveFile: (String) -> Unit, onDeleteFile: (String) -> Unit, ) { + var pending by remember { mutableStateOf(null) } LazyColumn(modifier = Modifier.fillMaxSize()) { items(items = rows, key = { it.trackId }) { row -> QuarantineRow( row = row, onResolve = { onResolve(row.trackId) }, - onDeleteFile = { onDeleteFile(row.trackId) }, + onRemoveFile = { pending = PendingRemoval(row, Removal.File) }, + onDeleteFile = { pending = PendingRemoval(row, Removal.Library) }, ) HorizontalDivider() } } + pending?.let { p -> + RemovalConfirm( + pending = p, + onConfirm = { + pending = null + when (p.kind) { + Removal.File -> onRemoveFile(p.row.trackId) + Removal.Library -> onDeleteFile(p.row.trackId) + } + }, + onDismiss = { pending = null }, + ) + } +} + +/** + * Both removals delete the file, so each asks first. Remove the file keeps the + * track waiting for a good copy, with its likes and plays; Remove from library + * takes the track and its history too. + */ +@Composable +private fun RemovalConfirm( + pending: PendingRemoval, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val title = pending.row.trackTitle + val (heading, body, action) = when (pending.kind) { + Removal.File -> Triple( + "Remove the file?", + "Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " + + "and plays, and takes over a good copy when one is in the library. Its reports are cleared.", + "Remove the file", + ) + Removal.Library -> Triple( + "Remove from library?", + "Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " + + "places. To keep the track for a good copy, remove the file instead.", + "Remove from library", + ) + } + ConfirmDestructiveDialog( + title = heading, + text = body, + confirmLabel = action, + onConfirm = onConfirm, + onDismiss = onDismiss, + ) } @Composable private fun QuarantineRow( row: AdminQuarantineItemRef, onResolve: () -> Unit, + onRemoveFile: () -> Unit, onDeleteFile: () -> Unit, ) { Column( @@ -160,6 +222,7 @@ private fun QuarantineRow( } ActionButtons( onResolve = onResolve, + onRemoveFile = onRemoveFile, onDeleteFile = onDeleteFile, ) } @@ -168,6 +231,7 @@ private fun QuarantineRow( @Composable private fun ActionButtons( onResolve: () -> Unit, + onRemoveFile: () -> Unit, onDeleteFile: () -> Unit, ) { Row( @@ -175,6 +239,7 @@ private fun ActionButtons( horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), ) { TextButton(onClick = onResolve) { Text("Resolve") } - OutlinedButton(onClick = onDeleteFile) { Text("Delete file") } + TextButton(onClick = onDeleteFile) { Text("Remove from library") } + OutlinedButton(onClick = onRemoveFile) { Text("Remove the file") } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt index b233a459..7f668884 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt @@ -8,6 +8,9 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.events.EventsStream import com.fabledsword.minstrel.models.AdminQuarantineItemRef +import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.loadUiState +import com.fabledsword.minstrel.shared.toListState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel @@ -20,12 +23,8 @@ import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import javax.inject.Inject -sealed interface AdminQuarantineUiState { - data object Loading : AdminQuarantineUiState - data object Empty : AdminQuarantineUiState - data class Success(val rows: List) : AdminQuarantineUiState - data class Error(val message: String) : AdminQuarantineUiState -} +/** The Reports queue, as the shared [UiState]. */ +typealias AdminQuarantineUiState = UiState> @HiltViewModel class AdminQuarantineViewModel @Inject constructor( @@ -34,14 +33,13 @@ class AdminQuarantineViewModel @Inject constructor( networkStatus: NetworkStatusController, ) : ViewModel() { - private val internal = MutableStateFlow(AdminQuarantineUiState.Loading) + private val internal = MutableStateFlow(UiState.Loading) val uiState: StateFlow = internal.asStateFlow() /** * One-shot messages for the screen's snackbar. A failed action has to say - * why: the row quietly reappearing reads as a glitch, and for a Delete - * file refused by a read-only library it hides the one thing an - * admin can fix. + * why: the row quietly reappearing reads as a glitch, and for a removal + * refused by a read-only library it hides the one thing an admin can fix. */ private val transientMessagesChannel = Channel(Channel.BUFFERED) val transientMessages: Flow = transientMessagesChannel.receiveAsFlow() @@ -57,41 +55,24 @@ class AdminQuarantineViewModel @Inject constructor( // when server health returns instead of waiting for a manual pull. viewModelScope.launch { networkStatus.recoveries().collect { - if (internal.value is AdminQuarantineUiState.Error) refresh() + if (internal.value is UiState.Error) refresh() } } } fun refresh(): Job = viewModelScope.launch { - internal.value = AdminQuarantineUiState.Loading - try { - val rows = repository.list() - internal.value = if (rows.isEmpty()) { - AdminQuarantineUiState.Empty - } else { - AdminQuarantineUiState.Success(rows) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = AdminQuarantineUiState.Error( - ErrorCopy.fromThrowable(e), - ) - } + internal.value = UiState.Loading + internal.value = loadUiState { repository.list().toListState() } } fun resolve(trackId: String) = act(trackId) { repository.resolve(it) } + fun removeFile(trackId: String) = act(trackId) { repository.removeFile(it) } fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) } private fun act(trackId: String, action: suspend (String) -> Unit) { val before = internal.value - if (before is AdminQuarantineUiState.Success) { - val filtered = before.rows.filterNot { it.trackId == trackId } - internal.value = if (filtered.isEmpty()) { - AdminQuarantineUiState.Empty - } else { - AdminQuarantineUiState.Success(filtered) - } + if (before is UiState.Success) { + internal.value = before.data.filterNot { it.trackId == trackId }.toListState() } viewModelScope.launch { try { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsScreen.kt deleted file mode 100644 index f0269712..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsScreen.kt +++ /dev/null @@ -1,163 +0,0 @@ -package com.fabledsword.minstrel.admin.ui - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material3.AssistChip -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.hilt.navigation.compose.hiltViewModel -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.navigation.NavHostController -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.nav.AdminRequests -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets -import com.fabledsword.minstrel.shared.widgets.EmptyState -import com.fabledsword.minstrel.shared.widgets.ErrorRetry -import com.fabledsword.minstrel.shared.widgets.LoadingCentered -import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar -import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun AdminRequestsScreen( - navController: NavHostController, - viewModel: AdminRequestsViewModel = hiltViewModel(), -) { - val state by viewModel.uiState.collectAsStateWithLifecycle() - Scaffold( - contentWindowInsets = ShellContentWindowInsets, - modifier = Modifier.fillMaxSize(), - topBar = { - MinstrelTopAppBar( - title = "Admin · Requests", - navController = navController, - currentRouteName = AdminRequests::class.qualifiedName, - onBack = { navController.popBackStack() }, - ) - }, - ) { inner -> - PullToRefreshScaffold( - onRefresh = { viewModel.refresh().join() }, - modifier = Modifier.fillMaxSize().padding(inner), - ) { - when (val s = state) { - AdminRequestsUiState.Loading -> LoadingCentered() - AdminRequestsUiState.Empty -> EmptyState( - title = "No requests waiting", - body = "When users ask for new music, their pending " + - "requests show up here for approval.", - ) - is AdminRequestsUiState.Error -> ErrorRetry( - title = "Couldn't load requests", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is AdminRequestsUiState.Success -> RequestList( - rows = s.rows, - onApprove = viewModel::approve, - onReject = viewModel::reject, - ) - } - } - } -} - -@Composable -private fun RequestList( - rows: List, - onApprove: (String) -> Unit, - onReject: (String) -> Unit, -) { - LazyColumn(modifier = Modifier.fillMaxSize()) { - items(items = rows, key = { it.id }) { req -> - AdminRequestRow( - req = req, - requester = req.username.ifEmpty { - req.userId.take(USER_ID_PREFIX_LEN).ifEmpty { "unknown" } - }, - onApprove = { onApprove(req.id) }, - onReject = { onReject(req.id) }, - ) - HorizontalDivider() - } - } -} - -@Composable -private fun AdminRequestRow( - req: RequestRef, - requester: String, - onApprove: () -> Unit, - onReject: () -> Unit, -) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = req.displayName, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - text = "Requested by $requester", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { - AssistChip( - onClick = {}, - enabled = false, - label = { Text(req.kind, style = MaterialTheme.typography.labelSmall) }, - ) - AssistChip( - onClick = {}, - enabled = false, - label = { Text(req.status.wire, style = MaterialTheme.typography.labelSmall) }, - ) - } - if (req.artistName.isNotEmpty() && req.artistName != req.displayName) { - Text( - text = "Artist: ${req.artistName}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), - ) { - OutlinedButton(onClick = onReject) { Text("Reject") } - Button(onClick = onApprove) { Text("Approve") } - } - } -} - -// UUID prefix length used as a friendlier-than-raw-UUID fallback when a -// row comes back without the requester's username. -private const val USER_ID_PREFIX_LEN = 8 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsViewModel.kt deleted file mode 100644 index a01a9509..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsViewModel.kt +++ /dev/null @@ -1,105 +0,0 @@ -package com.fabledsword.minstrel.admin.ui - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.fabledsword.minstrel.admin.data.AdminRequestsRepository -import com.fabledsword.minstrel.api.ErrorCopy -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.recoveries -import com.fabledsword.minstrel.events.EventsStream -import com.fabledsword.minstrel.models.RequestRef -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.launch -import javax.inject.Inject - -private val RELEVANT_EVENT_KINDS = setOf("request.status_changed") - -sealed interface AdminRequestsUiState { - data object Loading : AdminRequestsUiState - data object Empty : AdminRequestsUiState - data class Success(val rows: List) : AdminRequestsUiState - data class Error(val message: String) : AdminRequestsUiState -} - -@HiltViewModel -class AdminRequestsViewModel @Inject constructor( - private val repository: AdminRequestsRepository, - private val eventsStream: EventsStream, - networkStatus: NetworkStatusController, -) : ViewModel() { - - private val internal = MutableStateFlow(AdminRequestsUiState.Loading) - val uiState: StateFlow = internal.asStateFlow() - - init { - refresh() - viewModelScope.launch { - eventsStream.events - .filter { it.kind in RELEVANT_EVENT_KINDS } - .collect { refresh() } - } - // Screen-level auto-recovery: reload a failed list - // when server health returns instead of waiting for a manual pull. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is AdminRequestsUiState.Error) refresh() - } - } - } - - fun refresh(): Job = viewModelScope.launch { - internal.value = AdminRequestsUiState.Loading - try { - val rows = repository.list() - internal.value = if (rows.isEmpty()) { - AdminRequestsUiState.Empty - } else { - AdminRequestsUiState.Success(rows = rows) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = AdminRequestsUiState.Error( - ErrorCopy.fromThrowable(e), - ) - } - } - - fun approve(id: String) = decide(id) { repository.approve(it) } - - fun reject(id: String) = decide(id) { repository.reject(it) } - - /** - * Optimistically removes the decided row from the visible list and - * fires the REST call. On failure, refetches so the UI matches the - * server's view rather than leaving a phantom hole. - */ - private fun decide(id: String, action: suspend (String) -> Unit) { - val before = internal.value - if (before is AdminRequestsUiState.Success) { - val filtered = before.rows.filterNot { it.id == id } - internal.value = if (filtered.isEmpty()) { - AdminRequestsUiState.Empty - } else { - AdminRequestsUiState.Success(rows = filtered) - } - } - viewModelScope.launch { - try { - action(id) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Refetch reconciles whatever the server now says about - // this request; the error is intentionally swallowed - // because the refresh result IS the user-facing signal. - refresh() - } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt index 541130a7..10c77d47 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt @@ -35,6 +35,7 @@ import androidx.navigation.NavHostController import com.fabledsword.minstrel.models.AdminTagSourceRef import com.fabledsword.minstrel.models.TagSourceTestResult import com.fabledsword.minstrel.nav.AdminTagSources +import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry @@ -66,19 +67,19 @@ fun AdminTagSourcesScreen( modifier = Modifier.fillMaxSize().padding(inner), ) { when (val s = state) { - AdminTagSourcesUiState.Loading -> LoadingCentered() - AdminTagSourcesUiState.Empty -> EmptyState( + UiState.Loading -> LoadingCentered() + UiState.Empty -> EmptyState( title = "No tag sources", body = "Tag-enrichment providers register on the server; none are available.", ) - is AdminTagSourcesUiState.Error -> ErrorRetry( + is UiState.Error -> ErrorRetry( title = "Couldn't load tag sources", message = s.message, onRetry = { viewModel.refresh() }, ) - is AdminTagSourcesUiState.Success -> TagSourceList( - providers = s.providers, - testResults = s.testResults, + is UiState.Success -> TagSourceList( + providers = s.data.providers, + testResults = s.data.testResults, onToggle = viewModel::setEnabled, onSaveKey = viewModel::saveApiKey, onTest = viewModel::test, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt index f56039b3..02f9af2e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt @@ -8,6 +8,8 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.models.AdminTagSourceRef import com.fabledsword.minstrel.models.TagSourceTestResult +import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.loadUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow @@ -16,15 +18,14 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject -sealed interface AdminTagSourcesUiState { - data object Loading : AdminTagSourcesUiState - data object Empty : AdminTagSourcesUiState - data class Success( - val providers: List, - val testResults: Map, - ) : AdminTagSourcesUiState - data class Error(val message: String) : AdminTagSourcesUiState -} +/** The tag sources and the last Test answer for each, by provider id. */ +data class AdminTagSources( + val providers: List, + val testResults: Map = emptyMap(), +) + +/** The Tag sources screen, as the shared [UiState]. */ +typealias AdminTagSourcesUiState = UiState @HiltViewModel class AdminTagSourcesViewModel @Inject constructor( @@ -32,7 +33,7 @@ class AdminTagSourcesViewModel @Inject constructor( networkStatus: NetworkStatusController, ) : ViewModel() { - private val internal = MutableStateFlow(AdminTagSourcesUiState.Loading) + private val internal = MutableStateFlow(UiState.Loading) val uiState: StateFlow = internal.asStateFlow() init { @@ -41,34 +42,28 @@ class AdminTagSourcesViewModel @Inject constructor( // health returns instead of waiting for a manual pull. viewModelScope.launch { networkStatus.recoveries().collect { - if (internal.value is AdminTagSourcesUiState.Error) refresh() + if (internal.value is UiState.Error) refresh() } } } fun refresh(): Job = viewModelScope.launch { - internal.value = AdminTagSourcesUiState.Loading - try { + internal.value = UiState.Loading + internal.value = loadUiState { val providers = repository.list() - internal.value = if (providers.isEmpty()) { - AdminTagSourcesUiState.Empty - } else { - AdminTagSourcesUiState.Success(providers, emptyMap()) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = AdminTagSourcesUiState.Error(ErrorCopy.fromThrowable(e)) + if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers)) } } fun setEnabled(id: String, enabled: Boolean) { - val before = internal.value as? AdminTagSourcesUiState.Success ?: return + val before = (internal.value as? UiState.Success)?.data ?: return // Optimistic toggle; reconcile via refresh() if the server rejects. - internal.value = before.copy( - providers = before.providers.map { - if (it.id == id) it.copy(enabled = enabled) else it - }, + internal.value = UiState.Success( + before.copy( + providers = before.providers.map { + if (it.id == id) it.copy(enabled = enabled) else it + }, + ), ) viewModelScope.launch { try { @@ -102,15 +97,17 @@ class AdminTagSourcesViewModel @Inject constructor( ) { TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e)) } - val current = internal.value as? AdminTagSourcesUiState.Success ?: return@launch - internal.value = current.copy(testResults = current.testResults + (id to result)) + val current = (internal.value as? UiState.Success)?.data ?: return@launch + internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result))) } } private fun replaceProvider(updated: AdminTagSourceRef) { - val current = internal.value as? AdminTagSourcesUiState.Success ?: return - internal.value = current.copy( - providers = current.providers.map { if (it.id == updated.id) updated else it }, + val current = (internal.value as? UiState.Success)?.data ?: return + internal.value = UiState.Success( + current.copy( + providers = current.providers.map { if (it.id == updated.id) updated else it }, + ), ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt index 2b232a27..6bbb9741 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt @@ -31,6 +31,7 @@ import androidx.compose.material3.TextButton import android.content.ClipData import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.LocalClipboard +import com.fabledsword.minstrel.auth.PasswordRules import com.fabledsword.minstrel.models.Invite import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -49,6 +50,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.fabledsword.minstrel.models.AdminUserRef import com.fabledsword.minstrel.nav.AdminUsers +import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold @@ -81,7 +84,6 @@ fun AdminUsersScreen( invitesViewModel.refresh() }, onSetAdmin = viewModel::setAdmin, - onSetAutoApprove = viewModel::setAutoApprove, onAskResetPassword = { resetPasswordFor = it }, onAskDelete = { deleteCandidate = it }, onAskGenerateInvite = { showGenerateInvite = true }, @@ -121,7 +123,6 @@ private fun AdminUsersScaffold( invitesState: AdminInvitesUiState, onRefresh: suspend () -> Unit, onSetAdmin: (String, Boolean) -> Unit, - onSetAutoApprove: (String, Boolean) -> Unit, onAskResetPassword: (AdminUserRef) -> Unit, onAskDelete: (AdminUserRef) -> Unit, onAskGenerateInvite: () -> Unit, @@ -148,7 +149,6 @@ private fun AdminUsersScaffold( usersSection( state = usersState, onSetAdmin = onSetAdmin, - onSetAutoApprove = onSetAutoApprove, onAskResetPassword = onAskResetPassword, onAskDelete = onAskDelete, ) @@ -195,19 +195,17 @@ private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = n private fun androidx.compose.foundation.lazy.LazyListScope.usersSection( state: AdminUsersUiState, onSetAdmin: (String, Boolean) -> Unit, - onSetAutoApprove: (String, Boolean) -> Unit, onAskResetPassword: (AdminUserRef) -> Unit, onAskDelete: (AdminUserRef) -> Unit, ) { when (state) { - AdminUsersUiState.Loading -> item { CenteredHint("Loading users…") } - AdminUsersUiState.Empty -> item { CenteredHint("No registered users.") } - is AdminUsersUiState.Error -> item { CenteredHint(state.message) } - is AdminUsersUiState.Success -> items(items = state.users, key = { it.id }) { user -> + UiState.Loading -> item { CenteredHint("Loading users…") } + UiState.Empty -> item { CenteredHint("No registered users.") } + is UiState.Error -> item { CenteredHint(state.message) } + is UiState.Success -> items(items = state.data, key = { it.id }) { user -> UserRow( user = user, onSetAdmin = { onSetAdmin(user.id, it) }, - onSetAutoApprove = { onSetAutoApprove(user.id, it) }, onResetPassword = { onAskResetPassword(user) }, onDelete = { onAskDelete(user) }, ) @@ -397,7 +395,6 @@ private fun PendingDialogs( private fun UserRow( user: AdminUserRef, onSetAdmin: (Boolean) -> Unit, - onSetAutoApprove: (Boolean) -> Unit, onResetPassword: () -> Unit, onDelete: () -> Unit, ) { @@ -420,11 +417,6 @@ private fun UserRow( color = MaterialTheme.colorScheme.onSurfaceVariant, ) ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin) - ToggleRow( - label = "Auto-approve requests", - checked = user.autoApproveRequests, - onChange = onSetAutoApprove, - ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End), @@ -480,6 +472,7 @@ private fun ResetPasswordDialog( value = newPassword, onValueChange = { newPassword = it }, label = { Text("New password") }, + supportingText = { Text(PasswordRules.HINT) }, singleLine = true, visualTransformation = PasswordVisualTransformation(), ) @@ -488,7 +481,7 @@ private fun ResetPasswordDialog( confirmButton = { TextButton( onClick = { onConfirm(newPassword) }, - enabled = newPassword.isNotEmpty(), + enabled = PasswordRules.isLongEnough(newPassword), ) { Text("Reset") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, @@ -501,39 +494,14 @@ private fun DeleteConfirmDialog( onDismiss: () -> Unit, onConfirm: () -> Unit, ) { - var typed by remember { mutableStateOf("") } - val confirmed = typed.trim().equals(DELETE_CONFIRM_WORD, ignoreCase = true) - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Delete user?") }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text( - "Delete @${user.username}? This removes the account and all " + - "their data. Type $DELETE_CONFIRM_WORD to confirm.", - ) - OutlinedTextField( - value = typed, - onValueChange = { typed = it }, - label = { Text("Type $DELETE_CONFIRM_WORD") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - } - }, - confirmButton = { - TextButton(onClick = onConfirm, enabled = confirmed) { - Text( - "Delete", - color = if (confirmed) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - ) - } - }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ConfirmDestructiveDialog( + title = "Delete user?", + text = "Delete @${user.username}? This removes the account and all " + + "their data. Type $DELETE_CONFIRM_WORD to confirm.", + confirmLabel = "Delete", + onConfirm = onConfirm, + onDismiss = onDismiss, + confirmWord = DELETE_CONFIRM_WORD, ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt index 000d86c7..ac1d8388 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt @@ -3,10 +3,12 @@ package com.fabledsword.minstrel.admin.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fabledsword.minstrel.admin.data.AdminUsersRepository -import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.models.AdminUserRef +import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.loadUiState +import com.fabledsword.minstrel.shared.toListState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow @@ -15,12 +17,8 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject -sealed interface AdminUsersUiState { - data object Loading : AdminUsersUiState - data object Empty : AdminUsersUiState - data class Success(val users: List) : AdminUsersUiState - data class Error(val message: String) : AdminUsersUiState -} +/** The Users screen's list, as the shared [UiState]. */ +typealias AdminUsersUiState = UiState> @HiltViewModel class AdminUsersViewModel @Inject constructor( @@ -28,7 +26,7 @@ class AdminUsersViewModel @Inject constructor( networkStatus: NetworkStatusController, ) : ViewModel() { - private val internal = MutableStateFlow(AdminUsersUiState.Loading) + private val internal = MutableStateFlow(UiState.Loading) val uiState: StateFlow = internal.asStateFlow() init { @@ -37,36 +35,20 @@ class AdminUsersViewModel @Inject constructor( // when server health returns instead of waiting for a manual pull. viewModelScope.launch { networkStatus.recoveries().collect { - if (internal.value is AdminUsersUiState.Error) refresh() + if (internal.value is UiState.Error) refresh() } } } fun refresh(): Job = viewModelScope.launch { - internal.value = AdminUsersUiState.Loading - try { - val users = repository.list() - internal.value = if (users.isEmpty()) { - AdminUsersUiState.Empty - } else { - AdminUsersUiState.Success(users) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = AdminUsersUiState.Error(ErrorCopy.fromThrowable(e)) - } + internal.value = UiState.Loading + internal.value = loadUiState { repository.list().toListState() } } fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) { repository.setAdmin(it, isAdmin) } - fun setAutoApprove(id: String, autoApprove: Boolean) = - patch(id, { it.copy(autoApproveRequests = autoApprove) }) { - repository.setAutoApprove(it, autoApprove) - } - fun resetPassword(id: String, newPassword: String) { viewModelScope.launch { runCatching { repository.resetPassword(id, newPassword) } @@ -75,13 +57,8 @@ class AdminUsersViewModel @Inject constructor( fun delete(id: String) { val before = internal.value - if (before is AdminUsersUiState.Success) { - val filtered = before.users.filterNot { it.id == id } - internal.value = if (filtered.isEmpty()) { - AdminUsersUiState.Empty - } else { - AdminUsersUiState.Success(filtered) - } + if (before is UiState.Success) { + internal.value = before.data.filterNot { it.id == id }.toListState() } viewModelScope.launch { try { @@ -100,9 +77,9 @@ class AdminUsersViewModel @Inject constructor( action: suspend (String) -> Unit, ) { val before = internal.value - if (before is AdminUsersUiState.Success) { - internal.value = AdminUsersUiState.Success( - before.users.map { if (it.id == id) mutate(it) else it }, + if (before is UiState.Success) { + internal.value = UiState.Success( + before.data.map { if (it.id == id) mutate(it) else it }, ) } viewModelScope.launch { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt index b31d21ef..4c721863 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt @@ -8,9 +8,9 @@ import javax.inject.Singleton /** * Attaches the session cookie from [AuthStore] to Minstrel-server - * requests, captures Set-Cookie from successful responses (login - * flow), and clears the store on 401 so downstream code can react - * to logout. + * requests (waiting for the stored one to load at launch), captures + * Set-Cookie from successful responses (login flow), and signs out when + * the server refuses the cookie a request carried. * * Scoped to the [BaseUrlInterceptor.PLACEHOLDER_HOST] sentinel host * the same way BaseUrlInterceptor is. The shared OkHttpClient also @@ -32,7 +32,7 @@ class AuthCookieInterceptor @Inject constructor( // session. Pass through untouched. return chain.proceed(original) } - val cookie = authStore.sessionCookie.value + val cookie = authStore.sessionCookieForRequest() val request = original.newBuilder().apply { if (!cookie.isNullOrEmpty()) header("Cookie", cookie) }.build() @@ -40,7 +40,11 @@ class AuthCookieInterceptor @Inject constructor( val response = chain.proceed(request) if (response.code == HTTP_UNAUTHORIZED) { - authStore.setSessionCookie(null) + // Only a refusal of the cookie this request carried ends the + // session. A request sent without one says nothing about the + // stored login, and a refusal of an older cookie must not + // discard one a sign-in has stored since. + if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie) } else if (response.isSuccessful) { // Capture the first Set-Cookie pair on login; subsequent // responses that include Set-Cookie keep the store fresh. diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt index 1c4be42d..2a732f7a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt @@ -24,7 +24,7 @@ import javax.inject.Singleton * rewritten. Absolute external URLs — artwork from * artwork.musicbrainz.org / coverartarchive.org, for example — must * reach their authored host unchanged: rewritten to the Minstrel host - * they 404, and Discover suggestions show no covers. + * they 404, and the art never shows. * * No-op when the stored base URL is unparseable (falls through to * whatever Retrofit had) — that case shows up as a transport-level diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt index 19cd5771..3cf1d50b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt @@ -44,13 +44,15 @@ object ErrorCopy { } /** - * Codes whose server message carries specifics an admin needs in - * order to act — which directory, which uid — that fixed copy cannot say. - * For these the message follows the copy. Kept to a named set on - * purpose: most server messages are internal detail. Mirrors web's - * errors.ts. + * Codes whose server message carries specifics an admin needs in order + * to act (which directory, which uid) that fixed copy cannot say. For + * these the message follows the copy. Kept to a named set on purpose: + * most server messages are internal detail. The set is the web app's + * error-detail-codes.json. */ - private val DETAIL_CODES = setOf("library_not_writable", "file_delete_failed") + private val DETAIL_CODES: Set by lazy { + json.decodeFromString>(sharedResource("error-detail-codes.json")).toSet() + } private fun fromHttp(e: HttpException): String { val body = bodyFromHttp(e) @@ -69,53 +71,17 @@ object ErrorCopy { .getOrNull() ?: Body() } - private val TABLE: Map = mapOf( - "unknown" to "Something went wrong.", - "unauthenticated" to "Your session has ended. Please sign in again.", - "auth_required" to "You need to sign in to do that.", - "forbidden" to "You don't have permission to do that.", - "not_authorized" to "You don't have permission to do that.", - "invalid_credentials" to "Wrong username or password.", - "rate_limited" to "Too many attempts. Wait a few minutes and try again.", - "wrong_password" to "Current password is incorrect.", - "password_too_short" to "Password must be at least 8 characters.", - "username_invalid" to "That username isn't valid.", - "username_taken" to "That username is already taken.", - "email_invalid" to "Enter a valid email address.", - "email_taken" to "That email is already in use.", - "invalid_token" to "That link has expired or already been used. Request a new one.", - "invite_invalid" to "That invite has expired or already been used.", - "invite_required" to "An invite is required to register on this server.", - "last_admin" to "Can't demote or delete the last admin.", - "no_email_on_file" to "No email is associated with that account.", - "not_configured" to "This integration isn't set up yet.", - "validation" to "Some fields aren't valid. Check and try again.", - "missing_fields" to "Required fields are missing.", - "missing_query" to "Search needs at least one keyword.", - "invalid_id" to "Invalid identifier.", - "invalid_body" to "Couldn't read the request.", - "bad_request" to "Invalid request.", - "bad_body" to "Couldn't read the request.", - "bad_kind" to "Invalid request type.", - "bad_paging" to "Invalid page size or offset.", - "bad_reason" to "Invalid quarantine reason.", - "mbid_required" to "An MBID is required for this lookup.", - "system_playlist_readonly" to "System playlists can't be edited directly.", - "connection_refused" to "Couldn't reach the server. Check the URL and try again.", - "cleartext_public" to - "This server is on the internet, so its URL must start with https://. " + - "Plain http:// only works on your home network.", - "request_not_pending" to "This request is no longer pending.", - "request_not_found" to "That request no longer exists.", - "not_followable" to "Various Artists and MusicBrainz placeholders can't be followed.", - "profile_not_found" to "That release-type profile no longer exists.", - "track_not_found" to "That track no longer exists.", - "library_not_writable" to "The music library isn't writable by the server.", - "file_delete_failed" to "The file couldn't be deleted.", - "album_not_found" to "That album no longer exists.", - "artist_not_found" to "That artist no longer exists.", - "playlist_not_found" to "That playlist no longer exists.", - "user_not_found" to "That user no longer exists.", - "not_found" to "That no longer exists.", - ) + /** + * The copy for each error code: the web app's error-copy.json, copied + * into the app's resources at build time (app/build.gradle.kts, + * copySharedCopy), so both clients word every error the same way. + */ + private val TABLE: Map by lazy { + json.decodeFromString>(sharedResource("error-copy.json")) + } + + private fun sharedResource(name: String): String = + checkNotNull(ErrorCopy::class.java.getResourceAsStream("/$name")) { + "$name is missing from the app's resources (copySharedCopy in app/build.gradle.kts)" + }.use { it.reader().readText() } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt index cde7fba6..ec1116c5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt @@ -8,9 +8,11 @@ import retrofit2.http.Path /** * Retrofit interface for `/api/admin/quarantine`. * - * Two resolution endpoints: - * - `resolve` → admin reviewed, no action taken (clears flags). - * - `delete-file` → delete the track's file and row. + * Three resolution endpoints: + * - `resolve` → admin reviewed, no action taken (clears the reports). + * - `remove-file` → delete the track's file and keep the track, which waits + * for a good copy with its likes and plays. + * - `delete-file` → remove the track from the library, file and history. */ interface AdminQuarantineApi { @GET("api/admin/quarantine") @@ -19,6 +21,9 @@ interface AdminQuarantineApi { @POST("api/admin/quarantine/{trackId}/resolve") suspend fun resolve(@Path("trackId") trackId: String) + @POST("api/admin/quarantine/{trackId}/remove-file") + suspend fun removeFile(@Path("trackId") trackId: String) + @POST("api/admin/quarantine/{trackId}/delete-file") suspend fun deleteFile(@Path("trackId") trackId: String) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminRequestsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminRequestsApi.kt deleted file mode 100644 index ef0db4d8..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminRequestsApi.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.fabledsword.minstrel.api.endpoints - -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.http.GET -import retrofit2.http.POST -import retrofit2.http.Path - -/** - * Retrofit interface for `/api/admin/requests`. - * - * Server returns the same `requestView` shape as the user-side - * `/api/requests`, so RequestWire is reused. Different listing scope — - * admin sees all users' requests, not just the caller's. - */ -interface AdminRequestsApi { - @GET("api/admin/requests") - suspend fun list(): List - - @POST("api/admin/requests/{id}/approve") - suspend fun approve(@Path("id") id: String) - - @POST("api/admin/requests/{id}/reject") - suspend fun reject(@Path("id") id: String) -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt index b6ef8172..0064f792 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt @@ -9,14 +9,7 @@ import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path -/** - * Retrofit interface for `/api/admin/users`. - * - * Note: the PUT-auto-approve body field is `auto_approve`, NOT - * `auto_approve_requests` — the request shape differs from the - * response field name. Verified against `internal/api/admin_users.go - * adminAutoApproveReq` (May 2026). - */ +/** Retrofit interface for `/api/admin/users`. */ interface AdminUsersApi { @GET("api/admin/users") suspend fun list(): AdminUsersListWire @@ -24,9 +17,6 @@ interface AdminUsersApi { @PUT("api/admin/users/{id}/admin") suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody) - @PUT("api/admin/users/{id}/auto-approve") - suspend fun setAutoApprove(@Path("id") id: String, @Body body: SetAutoApproveBody) - @POST("api/admin/users/{id}/reset-password") suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody) @@ -39,10 +29,5 @@ data class SetAdminBody( @kotlinx.serialization.SerialName("is_admin") val isAdmin: Boolean, ) -@Serializable -data class SetAutoApproveBody( - @kotlinx.serialization.SerialName("auto_approve") val autoApprove: Boolean, -) - @Serializable data class ResetPasswordBody(val password: String) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiscoverApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiscoverApi.kt deleted file mode 100644 index 899b9bd0..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiscoverApi.kt +++ /dev/null @@ -1,62 +0,0 @@ -package com.fabledsword.minstrel.api.endpoints - -import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire -import com.fabledsword.minstrel.models.wire.CreateRequestBody -import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire -import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody -import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire -import retrofit2.http.Body -import retrofit2.http.DELETE -import retrofit2.http.GET -import retrofit2.http.POST -import retrofit2.http.Path -import retrofit2.http.Query - -/** - * Retrofit interface for Discover / catalogue search / request creation. - * - * `/api/catalogue/search` asks MusicBrainz, which allows one request a - * second, so the Discover screen searches when the query is submitted, - * not on every keystroke. - * - * Cancel + my-requests-list endpoints live on RequestsApi, not here. - */ -interface DiscoverApi { - @GET("api/discover/suggestions") - suspend fun listSuggestions(): List - - @GET("api/catalogue/search") - suspend fun search( - @Query("q") query: String, - @Query("kind") kind: String, - ): List - - @POST("api/requests") - suspend fun createRequest(@Body body: CreateRequestBody) - - /** - * Parks a suggestion — "not right now", NOT a dislike. Time-boxed - * server-side (90 days) and never fed into the taste profile. - * - * [body] must carry the artist's name: candidates are out-of-library, so - * the server has no local row to resolve a display name from and returns - * 400 without it. - */ - @POST("api/discover/suggestions/{mbid}/snooze") - suspend fun snoozeSuggestion( - @Path("mbid") mbid: String, - @Body body: SnoozeSuggestionBody, - ) - - /** Brings a parked suggestion back. 404 when it wasn't snoozed. */ - @DELETE("api/discover/suggestions/{mbid}/snooze") - suspend fun unsnoozeSuggestion(@Path("mbid") mbid: String) - - /** - * Currently-parked suggestions. Server filters expired rows, so every - * row returned is still snoozed. This is the only route back to an - * un-snooze once the card has left the deck. - */ - @GET("api/discover/snoozes") - suspend fun listSnoozes(): List -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt index ce6d6589..bf089a4a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt @@ -82,12 +82,15 @@ data class UpdateProfileRequest( ) /** - * Body for `PUT /api/me/password`. Both fields required. + * Body for `PUT /api/me/password`. Both passwords required. + * [signOutSubsonic] also ends every Subsonic app's access: the API token and + * Subsonic password stop working. */ @Serializable data class ChangePasswordRequest( @SerialName("current_password") val currentPassword: String, @SerialName("new_password") val newPassword: String, + @SerialName("sign_out_subsonic") val signOutSubsonic: Boolean = false, ) /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt index 5bb8a9a5..520ab623 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt @@ -5,8 +5,11 @@ import com.fabledsword.minstrel.models.wire.PlaylistsListWire import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import retrofit2.http.Body +import retrofit2.http.DELETE import retrofit2.http.GET +import retrofit2.http.PATCH import retrofit2.http.POST +import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Query @@ -27,11 +30,41 @@ interface PlaylistsApi { suspend fun get(@Path("id") id: String): PlaylistDetailWire /** - * POST /api/playlists/{id}/tracks — append the given track IDs to - * the owner's playlist. Server is idempotent at the (playlist_id, - * track_id) pair level; re-firing the same payload yields no - * duplicates. + * POST /api/playlists — make a playlist under the id the app chose, + * so a create queued offline and sent again finds the same list. */ + @POST("api/playlists") + suspend fun create(@Body body: CreatePlaylistRequest) + + /** PATCH /api/playlists/{id} — rename, or make public or private. Null fields stay as they are. */ + @PATCH("api/playlists/{id}") + suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest) + + @DELETE("api/playlists/{id}") + suspend fun delete(@Path("id") id: String) + + /** + * DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song + * expected there; if another song has moved into that place the server + * removes nothing and answers 409, so a removal sent twice takes out + * one song, not two. + */ + @DELETE("api/playlists/{id}/tracks/{position}") + suspend fun removeTrack( + @Path("id") id: String, + @Path("position") position: Int, + @Query("track_id") trackId: String?, + ) + + /** + * PUT /api/playlists/{id}/tracks with the songs in their new order. + * Entries not named keep their places, and the same order sent twice + * changes nothing the second time. + */ + @PUT("api/playlists/{id}/tracks") + suspend fun reorder(@Path("id") id: String, @Body body: ReorderTracksRequest) + + /** POST /api/playlists/{id}/tracks — append the given track IDs to the owner's playlist. */ @POST("api/playlists/{id}/tracks") suspend fun appendTracks( @Path("id") playlistId: String, @@ -60,12 +93,14 @@ interface PlaylistsApi { } /** - * POST /api/playlists/{id}/tracks body. The server expects snake_case - * `track_ids`. + * POST /api/playlists/{id}/tracks body. [requestId] names the append: the + * server applies an id once per playlist, so sending it again after a lost + * reply adds nothing more. */ @Serializable data class AppendTracksRequest( @SerialName("track_ids") val trackIds: List, + @SerialName("request_id") val requestId: String? = null, ) /** @@ -77,3 +112,22 @@ data class AppendTracksRequest( data class RefreshSystemResponse( @SerialName("playlist_id") val playlistId: String? = null, ) + +@Serializable +data class CreatePlaylistRequest( + val id: String, + val name: String, + @SerialName("is_public") val isPublic: Boolean = false, +) + +/** PATCH body; a null field is left out, so the server leaves it alone. */ +@Serializable +data class UpdatePlaylistRequest( + val name: String? = null, + @SerialName("is_public") val isPublic: Boolean? = null, +) + +@Serializable +data class ReorderTracksRequest( + @SerialName("track_ids") val trackIds: List, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/RequestsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/RequestsApi.kt deleted file mode 100644 index 700b92a8..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/RequestsApi.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.fabledsword.minstrel.api.endpoints - -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.http.DELETE -import retrofit2.http.GET -import retrofit2.http.Path - -/** - * Retrofit interface for the user-side `/api/requests`. - * - * Server scopes results to the caller — admins see only their own - * requests through this endpoint. The cross-user admin view lives on - * a separate `/api/admin/requests` route. - * - * The DELETE endpoint returns the cancelled row (not 204) so the UI - * can patch local state without a refetch. - */ -interface RequestsApi { - @GET("api/requests") - suspend fun listMine(): List - - @DELETE("api/requests/{id}") - suspend fun cancel(@Path("id") id: String): RequestWire -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt index eb70e0a9..ad7046b5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.Json import retrofit2.Retrofit import retrofit2.create @@ -89,8 +90,11 @@ class AuthController @Inject constructor( * + persisted userJson. Carries account-level flags (debug mode) * that aren't in the login response. Best-effort: a network failure * leaves the cached identity untouched. No-op when signed out. + * Waits for the stored login to load first: at launch this runs before + * it has, and would otherwise read the user as signed out and skip. */ suspend fun refreshProfile() { + authStore.awaitSessionHydrated() if (!isSignedIn) return val p = runCatching { meApi.getProfile() }.getOrNull() ?: return val user = UserRef( @@ -104,18 +108,35 @@ class AuthController @Inject constructor( } /** - * Clears the local session immediately and best-effort hits - * `/api/auth/logout` so the server can drop its session row. - * Network errors are swallowed — the user is already locally - * signed out and a stale server session times out on its own. + * Signs out here at once and ends the session on the server too. + * + * The app shows signed-out straight away, then calls + * `/api/auth/logout` while the session cookie is still set: the cookie + * is what tells the server which session to drop, so the call has to go + * before the cookie is cleared. The call waits at most + * [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared + * anyway and the server session expires on its own. It runs in the + * application scope, so the screen that asked closing as the app shows + * signed-out can't cancel it halfway. */ suspend fun signOut() { currentUserState.value = null - authStore.setSessionCookie(null) authStore.setUserJson(null) - runCatching { api.logout() } + scope.launch { + try { + withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } } + } finally { + authStore.setSessionCookie(null) + } + }.join() } private fun decodeUser(raw: String): UserRef? = runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull() + + private companion object { + // Long enough for a logout on a slow connection, short enough that + // signing out offline doesn't seem to hang. + const val LOGOUT_TIMEOUT_MS = 5_000L + } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt index e4fb4c4f..f4f5e1ce 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull @@ -87,6 +88,17 @@ class AuthStore @Inject constructor( private val backgroundDeliveryState = MutableStateFlow(true) val backgroundDelivery: StateFlow = backgroundDeliveryState.asStateFlow() + // The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId). + // Null while the stored row is still loading, and before any account + // has been adopted; [settingsLoaded] tells the two apart. + private val cacheOwnerState = MutableStateFlow(null) + val cacheOwnerUserId: StateFlow = cacheOwnerState.asStateFlow() + + private val settingsLoadedState = MutableStateFlow(false) + + /** True once the stored settings row has been read at least once. */ + val settingsLoaded: StateFlow = settingsLoadedState.asStateFlow() + private val json = Json { ignoreUnknownKeys = true } // Serialises every cookie persist with the one-time hydration, so a @@ -111,6 +123,8 @@ class AuthStore @Inject constructor( diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false normalizationState.value = decodeNormalization(row?.normalizationJson) backgroundDeliveryState.value = row?.backgroundDelivery ?: true + cacheOwnerState.value = row?.cacheOwnerUserId + settingsLoadedState.value = true } } } @@ -148,6 +162,49 @@ class AuthStore @Inject constructor( scope.launch { cookieLock.withLock { storeCookie(value) } } } + /** + * The cookie to attach to an outgoing request. Blocks the calling + * (OkHttp) thread until the stored cookie has loaded, up to + * [HYDRATION_DEADLINE_MS], so a request made in the first moment after + * launch carries the login instead of going out without it. Once + * hydration has finished this is a plain read. + */ + fun sessionCookieForRequest(): String? { + if (!cookieHydration.isCompleted) { + runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } } + } + return sessionCookieState.value + } + + /** + * True once the server has refused the current session (see + * [dropRejectedSessionCookie]) and the UI has not yet sent the user to + * sign in. Held rather than fired, so a refusal that lands while the app + * is in the background is still acted on when it comes back. A sign-out + * the user asked for does not set it. + */ + private val sessionRejectedState = MutableStateFlow(false) + val sessionRejected: StateFlow = sessionRejectedState.asStateFlow() + + /** The UI has opened the sign-in screen for a refused session. */ + fun consumeSessionRejected() { + sessionRejectedState.value = false + } + + /** + * Signs out because the server answered 401 to a request that carried + * [rejected]. Does nothing when the store has since moved on to another + * cookie (a sign-in landed meanwhile), so a refusal of an old session + * never discards a new one. What is persisted is read inside the lock, + * so a sign-in racing this call is the value that ends up stored. + */ + fun dropRejectedSessionCookie(rejected: String) { + if (!sessionCookieState.compareAndSet(rejected, null)) return + cookieTouched = true + scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } } + sessionRejectedState.value = true + } + private suspend fun hydrateSessionCookie() = cookieLock.withLock { val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull() if (cookieTouched) return@withLock @@ -223,6 +280,25 @@ class AuthStore @Inject constructor( } } + /** + * Records which account the cached data now belongs to. Suspends until + * it is stored, so a caller that has just cleared the old account's + * data can't have the adoption lost to a crash in between. + */ + suspend fun setCacheOwnerUserId(value: String?) { + cacheOwnerState.value = value + if (dao.get() == null) { + dao.upsert(currentEntity().copy(cacheOwnerUserId = value)) + } else { + dao.setCacheOwnerUserId(value) + } + } + + /** Forgets the newest notice announced, so the next account starts fresh. */ + suspend fun clearNotifiedUpTo() { + if (dao.get() != null) dao.setNotifiedUpTo(null) + } + private suspend fun persistLegacyCookie(value: String?) { if (dao.get() == null) { dao.upsert(currentEntity().copy(sessionCookie = value)) @@ -306,6 +382,7 @@ class AuthStore @Inject constructor( normalizationState.value, ), backgroundDelivery = backgroundDeliveryState.value, + cacheOwnerUserId = cacheOwnerState.value, ) companion object { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/PasswordRules.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/PasswordRules.kt new file mode 100644 index 00000000..be6ae321 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/PasswordRules.kt @@ -0,0 +1,24 @@ +package com.fabledsword.minstrel.auth + +import com.fabledsword.minstrel.api.ErrorCopy + +/** + * The rules every new-password field shares (Settings › Password, an admin + * resetting someone's password), worded as the web app words them + * (web/src/lib/auth/password.ts). The server enforces the same minimum and + * answers password_too_short; checking here only saves the round trip. + */ +object PasswordRules { + const val MIN_LENGTH = 8 + + /** The hint under a new-password field. */ + const val HINT = "At least $MIN_LENGTH characters." + + /** Said when a new password is shorter than [MIN_LENGTH]: the server's own wording for it. */ + val TOO_SHORT: String get() = ErrorCopy.messageFor("password_too_short") + + /** Said when a password and its confirmation differ. */ + const val DIFFER = "Passwords do not match." + + fun isLongEnough(password: String): Boolean = password.length >= MIN_LENGTH +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt new file mode 100644 index 00000000..57d4d881 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt @@ -0,0 +1,180 @@ +package com.fabledsword.minstrel.auth + +import com.fabledsword.minstrel.api.CleartextToPublicHostException +import com.fabledsword.minstrel.api.MinstrelServerRequest +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import okhttp3.Call +import okhttp3.Callback +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import java.io.IOException +import java.net.UnknownHostException +import java.security.GeneralSecurityException +import java.util.concurrent.TimeUnit +import javax.inject.Inject +import javax.net.ssl.SSLPeerUnverifiedException +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException + +/** + * Finds the Minstrel server behind an address the user typed. + * + * With no scheme typed it tries `https://` first. It falls back to `http://` + * only when https could not connect at all (refused, timed out, or no TLS on + * that port). A certificate that fails to verify stops the probe instead: + * falling back then would let anyone on the network path force a quiet + * downgrade. A scheme the user typed is used as typed, and still probed, so a + * wrong address fails here rather than at sign-in. + * + * Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor] + * on [client], so the fallback can only succeed on a home-network address. + */ +class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) { + + // Each attempt is short: a probe that stalls holds the sign-in screen. + @Inject constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS) + + private val client: OkHttpClient = client.newBuilder() + .connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) + .callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) + .build() + + sealed interface Result { + /** Minstrel answered at [baseUrl], which includes its scheme. */ + data class Found(val baseUrl: String) : Result + + data class Failed(val message: String) : Result + } + + suspend fun find(input: String): Result { + val address = input.trim().trimEnd('/') + val lower = address.lowercase() + return when { + address.isEmpty() -> Result.Failed("Enter your server's address.") + lower.startsWith("https://") || lower.startsWith("http://") -> probeTyped(address) + "://" in address -> Result.Failed("Only https:// and http:// addresses are supported.") + else -> probeBare(address) + } + } + + private suspend fun probeTyped(baseUrl: String): Result = + when (val outcome = attempt(baseUrl)) { + Outcome.Minstrel -> Result.Found(baseUrl) + is Outcome.Stop -> Result.Failed(outcome.message) + is Outcome.Unreachable -> + if (outcome.publicCleartext) { + Result.Failed( + "Plain http:// is only allowed to a server on your home network. " + + "Use https:// for this address.", + ) + } else { + Result.Failed("Couldn't reach $baseUrl.") + } + } + + private suspend fun probeBare(address: String): Result { + val https = "https://$address" + return when (val secure = attempt(https)) { + Outcome.Minstrel -> Result.Found(https) + is Outcome.Stop -> Result.Failed(secure.message) + is Outcome.Unreachable -> { + val http = "http://$address" + when (val plain = attempt(http)) { + Outcome.Minstrel -> Result.Found(http) + is Outcome.Stop -> Result.Failed(plain.message) + // A public host over plain http: say only that https + // failed, so the message never points the user at http. + is Outcome.Unreachable -> Result.Failed("Couldn't reach $https.") + } + } + } + } + + private sealed interface Outcome { + data object Minstrel : Outcome + + /** Nothing answered: the next scheme may be tried. */ + data class Unreachable(val publicCleartext: Boolean = false) : Outcome + + /** Something answered, or TLS failed to verify: stop here. */ + data class Stop(val message: String) : Outcome + } + + private suspend fun attempt(baseUrl: String): Outcome { + val url = "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull() + ?: return Outcome.Stop("That doesn't look like a server address.") + val request = Request.Builder() + .url(url) + // Lets CleartextGuardInterceptor treat the probe as a Minstrel + // server request, as it treats sign-in. + .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) + .build() + return try { + client.newCall(request).await().use { response -> + if (isMinstrel(response)) { + Outcome.Minstrel + } else { + Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.") + } + } + } catch (@Suppress("SwallowedException") e: CleartextToPublicHostException) { + Outcome.Unreachable(publicCleartext = true) + } catch (@Suppress("SwallowedException") e: UnknownHostException) { + Outcome.Stop("Couldn't find a server named ${url.host}.") + } catch (e: IOException) { + if (isCertificateFailure(e)) { + Outcome.Stop( + "$baseUrl answered, but its certificate couldn't be verified, " + + "so the app won't connect to it.", + ) + } else { + Outcome.Unreachable() + } + } + } + + // GET /api/auth/setup-status answers {"setup_required": bool} with no + // sign-in, and only Minstrel answers it that way. + private fun isMinstrel(response: Response): Boolean { + val body = if (response.isSuccessful) response.body?.string() else null + val json = body?.let { runCatching { Json.parseToJsonElement(it) }.getOrNull() } as? JsonObject + return (json?.get("setup_required") as? JsonPrimitive)?.booleanOrNull != null + } + + // An unverifiable certificate surfaces as SSLPeerUnverifiedException + // (hostname) or as an SSLHandshakeException caused by a + // CertificateException or CertPathValidatorException (trust). A port + // with no TLS fails the handshake too, but with no such cause. + private fun isCertificateFailure(e: IOException): Boolean = + generateSequence(e) { it.cause } + .take(MAX_CAUSE_DEPTH) + .any { it is SSLPeerUnverifiedException || it is GeneralSecurityException } + + private suspend fun Call.await(): Response = + suspendCancellableCoroutine { continuation -> + continuation.invokeOnCancellation { cancel() } + enqueue( + object : Callback { + override fun onResponse(call: Call, response: Response) { + if (continuation.isActive) continuation.resume(response) else response.close() + } + + override fun onFailure(call: Call, e: IOException) { + if (continuation.isActive) continuation.resumeWithException(e) + } + }, + ) + } + + private companion object { + const val SETUP_STATUS_PATH = "/api/auth/setup-status" + const val CALL_TIMEOUT_MILLIS = 8_000L + const val MAX_CAUSE_DEPTH = 8 + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt index 39d228bb..b8b86a1f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt @@ -38,6 +38,15 @@ class AuthGateViewModel @Inject constructor( private val internal = MutableStateFlow(null) val startDestination: StateFlow = internal.asStateFlow() + /** + * True when the server has ended the session while the app was in use; + * the root NavHost answers by opening the sign-in screen, then calls + * [consumeSessionRejected]. + */ + val sessionRejected: StateFlow = authStore.sessionRejected + + fun consumeSessionRejected() = authStore.consumeSessionRejected() + init { viewModelScope.launch { authStore.awaitSessionHydrated() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt index 04d90763..8b78a134 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt @@ -5,13 +5,16 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -26,9 +29,11 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.auth.ServerProbe import com.fabledsword.minstrel.nav.Login import com.fabledsword.minstrel.nav.ServerUrl import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -40,7 +45,7 @@ import javax.inject.Inject data class ServerUrlFormState( val url: String = "", - val saving: Boolean = false, + val probing: Boolean = false, val saved: Boolean = false, val errorMessage: String? = null, ) @@ -48,6 +53,7 @@ data class ServerUrlFormState( @HiltViewModel class ServerUrlViewModel @Inject constructor( private val authStore: AuthStore, + private val probe: ServerProbe, ) : ViewModel() { private val internal = MutableStateFlow( @@ -55,8 +61,8 @@ class ServerUrlViewModel @Inject constructor( // the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is // an internal HTTP-client fallback, not something a user // typed. Leaving the field empty lets the OutlinedTextField's - // placeholder ("https://minstrel.example.com") show through - // so the user can just type without first having to clear. + // placeholder ("minstrel.example.com") show through so the user + // can just type without first having to clear. ServerUrlFormState( url = authStore.baseUrl.value .takeIf { it != AuthStore.DEFAULT_BASE_URL } @@ -65,29 +71,39 @@ class ServerUrlViewModel @Inject constructor( ) val state: StateFlow = internal.asStateFlow() + private var probeJob: Job? = null + fun setUrl(value: String) { internal.update { it.copy(url = value, errorMessage = null) } } + /** + * Looks for Minstrel at the typed address ([ServerProbe]) and saves the + * full URL that answered, scheme included, so every caller of + * [AuthStore.baseUrl] still receives a complete URL. + */ fun submit() { - val raw = internal.value.url.trim().trimEnd('/') - if (raw.isEmpty()) { - internal.update { it.copy(errorMessage = "Enter a server URL.") } - return - } - if (!raw.startsWith("http://") && !raw.startsWith("https://")) { - internal.update { - it.copy(errorMessage = "URL must start with http:// or https://") + if (internal.value.probing) return + val typed = internal.value.url + probeJob = viewModelScope.launch { + internal.update { it.copy(probing = true, errorMessage = null) } + when (val result = probe.find(typed)) { + is ServerProbe.Result.Found -> { + authStore.setBaseUrl(result.baseUrl) + internal.update { it.copy(probing = false, saved = true) } + } + is ServerProbe.Result.Failed -> + internal.update { it.copy(probing = false, errorMessage = result.message) } } - return - } - viewModelScope.launch { - internal.update { it.copy(saving = true, errorMessage = null) } - authStore.setBaseUrl(raw) - internal.update { it.copy(saving = false, saved = true) } } } + fun cancelProbe() { + probeJob?.cancel() + probeJob = null + internal.update { it.copy(probing = false) } + } + fun consumeSaved() { internal.update { it.copy(saved = false) } } @@ -120,6 +136,7 @@ fun ServerUrlScreen( state = state, onUrlChange = viewModel::setUrl, onSubmit = viewModel::submit, + onCancel = viewModel::cancelProbe, ) } } @@ -129,6 +146,7 @@ private fun ServerUrlForm( state: ServerUrlFormState, onUrlChange: (String) -> Unit, onSubmit: () -> Unit, + onCancel: () -> Unit, ) { Column( modifier = Modifier @@ -143,7 +161,7 @@ private fun ServerUrlForm( color = MaterialTheme.colorScheme.onBackground, ) Text( - text = "Enter the URL of your Minstrel server.", + text = "Enter the address of your Minstrel server.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -151,10 +169,13 @@ private fun ServerUrlForm( value = state.url, onValueChange = onUrlChange, modifier = Modifier.fillMaxWidth(), - label = { Text("Server URL") }, - placeholder = { Text("https://minstrel.example.com") }, + label = { Text("Server address") }, + placeholder = { Text("minstrel.example.com") }, + supportingText = { + Text("No need for https://. The app tries https first, then http on your home network.") + }, singleLine = true, - enabled = !state.saving, + enabled = !state.probing, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done, @@ -168,10 +189,39 @@ private fun ServerUrlForm( style = MaterialTheme.typography.bodySmall, ) } - Button( - onClick = onSubmit, - enabled = !state.saving && state.url.isNotBlank(), - modifier = Modifier.fillMaxWidth(), - ) { Text("Continue") } + ProbeButtons( + probing = state.probing, + canSubmit = state.url.isNotBlank(), + onSubmit = onSubmit, + onCancel = onCancel, + ) + } +} + +/** Continue, which shows progress while the address is probed, and Cancel beside it. */ +@Composable +private fun ProbeButtons( + probing: Boolean, + canSubmit: Boolean, + onSubmit: () -> Unit, + onCancel: () -> Unit, +) { + Button( + onClick = onSubmit, + enabled = !probing && canSubmit, + modifier = Modifier.fillMaxWidth(), + ) { + if (probing) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp), + color = MaterialTheme.colorScheme.onPrimary, + strokeWidth = 2.dp, + ) + } else { + Text("Continue") + } + } + if (probing) { + TextButton(onClick = onCancel) { Text("Cancel") } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt new file mode 100644 index 00000000..b7bd0bdd --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt @@ -0,0 +1,109 @@ +package com.fabledsword.minstrel.cache.account + +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.di.ApplicationScope +import com.fabledsword.minstrel.player.PlayerController +import dagger.Lazy +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.launch +import timber.log.Timber +import javax.inject.Inject +import javax.inject.Singleton + +/** What [AccountCache] does about the signed-in account and the cache's owner. */ +internal enum class OwnerStep { + /** Nobody is signed in, or the stored owner hasn't loaded yet. */ + WAIT, + + /** + * The cache has no owner yet (a fresh install, or one updated from + * before owners): adopt the account, keeping the data. + */ + ADOPT, + + /** Another account's data is cached: clear it, then adopt this account. */ + SWITCH, + + /** The signed-in account owns the cache. */ + OWNED, +} + +internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when { + !loaded || signedInUserId == null -> OwnerStep.WAIT + ownerUserId == null -> OwnerStep.ADOPT + ownerUserId != signedInUserId -> OwnerStep.SWITCH + else -> OwnerStep.OWNED +} + +/** + * Keeps one account's cached data from reaching another account on a + * shared device. + * + * The device caches data that belongs to whoever is signed in: their + * queued offline writes (likes, plays, quarantine flags, playlist adds, + * settings), Home, history, quarantine list, notifications and the queue + * the player resumes. Likes and playlists carry a user id of their own; + * these don't. So the cache has an owner, stored with the device's + * settings. When a different account signs in, that data is cleared and + * the player emptied before the new account is adopted, however the last + * one left: by signing out, or by the server refusing its session. + * + * The same person signing back in keeps everything, queued writes + * included, so a session that expires offline loses nothing. + * + * [ownedBySignedInUser] gates the offline-write replayer: queued writes + * are sent only while their owner is the one signed in, so they never go + * out under another account's session. + */ +@Singleton +class AccountCache @Inject constructor( + private val authStore: AuthStore, + authController: AuthController, + private val tables: AccountTables, + private val player: Lazy, + @ApplicationScope scope: CoroutineScope, +) { + private val ownedState = MutableStateFlow(false) + + /** True while the signed-in account is the one the cached data belongs to. */ + val ownedBySignedInUser: StateFlow = ownedState.asStateFlow() + + init { + scope.launch { + combine( + authStore.settingsLoaded, + authController.currentUser, + authStore.cacheOwnerUserId, + ) { loaded, user, owner -> Triple(loaded, user?.id, owner) } + .distinctUntilChanged() + .collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) } + } + } + + private suspend fun step(step: OwnerStep, userId: String?) { + when (step) { + OwnerStep.WAIT -> ownedState.value = false + // The stored owner changes next, and that emission reports OWNED. + OwnerStep.ADOPT -> authStore.setCacheOwnerUserId(userId) + OwnerStep.SWITCH -> { + ownedState.value = false + clearAccountData() + authStore.setCacheOwnerUserId(userId) + } + OwnerStep.OWNED -> ownedState.value = true + } + } + + private suspend fun clearAccountData() { + Timber.i("account cache: another account signed in; clearing the last one's data") + tables.clear() + authStore.clearNotifiedUpTo() + player.get().clearQueue() + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt new file mode 100644 index 00000000..164ee0c8 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt @@ -0,0 +1,28 @@ +package com.fabledsword.minstrel.cache.account + +import androidx.room.withTransaction +import com.fabledsword.minstrel.cache.db.AppDatabase +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The cached tables that hold one account's data and carry no user id of + * their own, cleared together by [AccountCache] when another account signs + * in. A new table of that kind belongs in [clear]; one keyed by user id + * (likes, playlists) or shared by every account (the library) does not. + */ +@Singleton +class AccountTables @Inject constructor(private val db: AppDatabase) { + /** Clears them in one transaction, so a crash can't leave half of them. */ + suspend fun clear() { + db.withTransaction { + db.cachedMutationDao().clear() + db.cachedHomeIndexDao().clear() + db.cachedHistorySnapshotDao().clear() + db.cachedQuarantineDao().clear() + db.cachedResumeStateDao().clear() + db.cachedNotificationDao().clear() + db.cachedNotificationDao().clearSettings() + } + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt index 90433c9d..c11d1c14 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt @@ -67,6 +67,14 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity CachedNotificationEntity::class, CachedNotificationSettingsEntity::class, ], + // v15: + auth_session.cacheOwnerUserId, the account the cached data + // belongs to. MIGRATION_14_15 adds it empty; AccountCache adopts the + // signed-in account. + // v14: + cached_playlists.shelfRank, a system mix's place on its Home + // shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it. + // v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's + // shelves draw each playlist tile's picture from and when a mix was + // rebuilt. MIGRATION_12_13 adds both empty; the next list refresh fills them. // v12: + auth_session.backgroundDelivery and notifiedUpTo, the device's // background-delivery choice and its shade high-water mark. // v11: + cached_notifications and cached_notification_settings, the @@ -87,7 +95,7 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity // on auth_session. Versions before v8 rebuild destructively, which is // right for them: the next sync refills every row with the new // columns populated, so there is nothing to migrate by hand. - version = 12, + version = 15, exportSchema = true, ) @TypeConverters(MinstrelTypeConverters::class) @@ -162,3 +170,35 @@ val MIGRATION_11_12: Migration = object : Migration(11, 12) { db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER") } } + +/** + * v12 → v13: a playlist's cover albums and creation time. Both start empty; + * Home refreshes the playlist list on open, which fills them. + */ +val MIGRATION_12_13: Migration = object : Migration(12, 13) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''") + db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''") + } +} + +/** + * v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked); + * Home refreshes the playlist list on open, which fills it. + */ +val MIGRATION_13_14: Migration = object : Migration(13, 14) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0") + } +} + +/** + * v14 → v15: the account the cached data belongs to. Starts empty, and + * AccountCache adopts whoever is signed in without clearing anything, so + * an update keeps the signed-in person's queued writes and cache. + */ +val MIGRATION_14_15: Migration = object : Migration(14, 15) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT") + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt index 8e04a44c..506161f9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt @@ -37,7 +37,15 @@ object DatabaseModule { // and rebuilds. The sync controller refills the cache from the // server on first launch, so a rebuild loses only the unsynced // mutation queue. - .addMigrations(MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12) + .addMigrations( + MIGRATION_8_9, + MIGRATION_9_10, + MIGRATION_10_11, + MIGRATION_11_12, + MIGRATION_12_13, + MIGRATION_13_14, + MIGRATION_14_15, + ) .fallbackToDestructiveMigration(dropAllTables = true) .build() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt index d5b6f245..1e4b4ca8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt @@ -59,4 +59,7 @@ interface AuthSessionDao { /** Partial update: change only the shade's high-water mark. */ @Query("UPDATE auth_session SET notifiedUpTo = :upTo WHERE id = 0") suspend fun setNotifiedUpTo(upTo: Instant?) + + @Query("UPDATE auth_session SET cacheOwnerUserId = :userId WHERE id = 0") + suspend fun setCacheOwnerUserId(userId: String?) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt index 737a2729..0d4e6b20 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt @@ -15,4 +15,7 @@ interface CachedHistorySnapshotDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsert(row: CachedHistorySnapshotEntity) + + @Query("DELETE FROM cached_history_snapshot") + suspend fun clear() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt index 71f37b13..e13cc24d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt @@ -48,4 +48,7 @@ interface CachedNotificationDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertSettings(row: CachedNotificationSettingsEntity) + + @Query("DELETE FROM cached_notification_settings") + suspend fun clearSettings() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt index 88e78401..9ab89204 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt @@ -14,12 +14,12 @@ interface CachedPlaylistDao { @Query("SELECT * FROM cached_playlists ORDER BY name COLLATE NOCASE ASC") fun observeAll(): Flow> - /** User playlists only (systemVariant IS NULL) — for the add-to-playlist sheet. */ + /** [userId]'s own playlists, not mixes: the lists they can add a song to. */ @Query( "SELECT * FROM cached_playlists " + - "WHERE systemVariant IS NULL ORDER BY name COLLATE NOCASE ASC", + "WHERE systemVariant IS NULL AND userId = :userId ORDER BY name COLLATE NOCASE ASC", ) - fun observeUserPlaylists(): Flow> + fun observeOwnedUserPlaylists(userId: String): Flow> /** System playlists for the home screen. */ @Query( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt index f769d926..15e05458 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt @@ -61,7 +61,15 @@ data class AuthSessionEntity( /** * The newest notice this device has announced in the shade. A catch-up * announces only what is newer, so a reboot or a reconnect never - * re-announces a backlog. Cleared on sign-out. + * re-announces a backlog. Cleared when another account signs in. */ val notifiedUpTo: Instant? = null, + /** + * The account the device's cached data belongs to: its queued offline + * writes, Home, history, quarantine list, notifications and resume + * queue. When a different account signs in, AccountCache clears that + * data before adopting the new account, so one person never sees or + * sends another's. Null until an account has been adopted. + */ + val cacheOwnerUserId: String? = null, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedArtistEntity.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedArtistEntity.kt index fa8d13d3..bb2de1ed 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedArtistEntity.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedArtistEntity.kt @@ -9,7 +9,7 @@ import kotlinx.datetime.Instant * Cache row for one artist. * * Column names follow Kotlin idiom (camelCase) — the schema is purely - * internal to the app; the sync controller exchanges snake_case JSON + * internal to the app; the sync controller trades snake_case JSON * with the server and our mappers translate at the boundary. */ @Entity(tableName = "cached_artists") diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt index 7730fa4a..7b51dca7 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt @@ -1,5 +1,6 @@ package com.fabledsword.minstrel.cache.db.entities +import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.datetime.Clock @@ -25,4 +26,16 @@ data class CachedPlaylistEntity( val durationSec: Int = 0, val systemVariant: String? = null, val fetchedAt: Instant = Clock.System.now(), + /** + * The playlist's cover albums, comma-joined (album ids are UUIDs and + * carry no commas). Empty until the list is next refreshed. + */ + @ColumnInfo(defaultValue = "''") + val coverAlbumIds: String = "", + /** ISO-8601 creation time; for a system mix, when it was last rebuilt. */ + @ColumnInfo(defaultValue = "''") + val createdAt: String = "", + /** Place on its Home shelf, 1 first; 0 when unranked. */ + @ColumnInfo(defaultValue = "0") + val shelfRank: Int = 0, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt index a78a61cc..c2ea1ac1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt @@ -19,16 +19,15 @@ private const val QUEUED_MESSAGE = "Saved — will sync when online" /** * Stable mutation kinds the queue knows how to replay. Strings are * persisted in `cached_mutations.kind` so renaming a variant breaks - * the on-disk queue — only ever add new kinds, never rename. + * the on-disk queue — never rename one. A kind can be removed: the + * replayer drops rows of a kind it doesn't know. */ object MutationKind { const val LIKE_TOGGLE: String = "like_toggle" - const val REQUEST_CREATE: String = "request_create" const val QUARANTINE_UNFLAG: String = "quarantine_unflag" const val PLAYLIST_APPEND: String = "playlist_append" const val QUARANTINE_FLAG: String = "quarantine_flag" const val PLAY_OFFLINE: String = "play_offline" - const val REQUEST_CANCEL: String = "request_cancel" const val PLAYBACK_ERROR_REPORT: String = "playback_error_report" // Durable close-by-id for a play whose server row is already open @@ -37,12 +36,6 @@ object MutationKind { // background would duplicate the open row and leave it orphaned. const val PLAY_ENDED: String = "play_ended" - // Suggestion snooze. ONE toggle kind rather than separate - // snooze/unsnooze kinds, mirroring LIKE_TOGGLE, so a snooze followed by - // an undo collapses to the latest intent instead of replaying as two - // opposed calls whose order decides the outcome. - const val SUGGESTION_SNOOZE_TOGGLE: String = "suggestion_snooze_toggle" - // Loudness-normalization preference. The payload is the whole // preference, a target state like the toggles above, so queued changes // collapse to the last one and an older one can never be replayed last. @@ -58,6 +51,16 @@ object MutationKind { // Per-kind notification channel. One row per (kind, channel) target // state, collapsed on that pair, so the newest choice is the one sent. const val NOTIFICATION_SETTING_SET: String = "notification_setting_set" + + // A listener's own playlists. Each is safe to send twice: a create + // carries the app's own id for the list, a removal names the song it + // expects at that place, and a reorder is the whole new order (a + // target state, so queued reorders of one list collapse to the last). + const val PLAYLIST_CREATE: String = "playlist_create" + const val PLAYLIST_UPDATE: String = "playlist_update" + const val PLAYLIST_DELETE: String = "playlist_delete" + const val PLAYLIST_REMOVE_TRACK: String = "playlist_remove_track" + const val PLAYLIST_REORDER: String = "playlist_reorder" } /** @@ -73,23 +76,6 @@ data class LikeTogglePayload( val desiredState: Boolean, ) -/** - * Persisted payload for `MutationKind.REQUEST_CREATE` (a Discover - * request that landed during a connectivity hiccup). Optional - * fields stay null when not applicable; the replayer rebuilds the - * `CreateRequestBody` from these. - */ -@Serializable -data class RequestCreatePayload( - val kind: String, - val artistMbid: String, - val artistName: String, - val albumMbid: String? = null, - val albumTitle: String? = null, - val trackMbid: String? = null, - val trackTitle: String? = null, -) - /** * Write side of the offline mutation queue; [MutationReplayer] drains it. * @@ -137,11 +123,6 @@ class MutationQueue @Inject constructor( ), ) - suspend fun enqueueRequestCreate(payload: RequestCreatePayload): Long = insertUserDriven( - MutationKind.REQUEST_CREATE, - json.encodeToString(RequestCreatePayload.serializer(), payload), - ) - suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven( MutationKind.QUARANTINE_UNFLAG, json.encodeToString( @@ -150,17 +131,83 @@ class MutationQueue @Inject constructor( ), ) - suspend fun enqueuePlaylistAppend( - playlistId: String, - trackIds: List, - ): Long = insertUserDriven( + suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven( MutationKind.PLAYLIST_APPEND, - json.encodeToString( - PlaylistAppendPayload.serializer(), - PlaylistAppendPayload(playlistId, trackIds), - ), + json.encodeToString(PlaylistAppendPayload.serializer(), payload), ) + suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven( + MutationKind.PLAYLIST_CREATE, + json.encodeToString(PlaylistCreatePayload.serializer(), payload), + ) + + suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = insertUserDriven( + MutationKind.PLAYLIST_UPDATE, + json.encodeToString(PlaylistUpdatePayload.serializer(), payload), + ) + + suspend fun enqueuePlaylistDelete(playlistId: String): Long = insertUserDriven( + MutationKind.PLAYLIST_DELETE, + json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)), + ) + + suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = insertUserDriven( + MutationKind.PLAYLIST_REMOVE_TRACK, + json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload), + ) + + suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = insertUserDriven( + MutationKind.PLAYLIST_REORDER, + json.encodeToString(PlaylistReorderPayload.serializer(), payload), + ) + + /** + * Ids of playlists made on this device that the server hasn't been + * sent yet. A list refresh keeps them, so a playlist made offline + * doesn't vanish before its create goes out. + */ + suspend fun pendingPlaylistCreateIds(): Set = dao.getAll() + .asSequence() + .filter { it.kind == MutationKind.PLAYLIST_CREATE } + .mapNotNull { row -> + runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) } + .getOrNull()?.id + } + .toSet() + + /** + * The like state each still-queued like toggle sets, by + * [likeToggleKey], the newest toggle winning. A toggle for an entity + * found here must queue behind it rather than go live, or the older + * one replays after it and undoes it; and a refresh keeps these states + * over the server's, which hasn't seen them yet. + */ + suspend fun pendingLikeStates(): Map = buildMap { + dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row -> + runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) } + .getOrNull() + ?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) } + } + } + + /** + * Whether each track with a quarantine flag or unflag still queued ends + * up flagged (true) or not, the newest winning. Read for the same two + * reasons as [pendingLikeStates]. + */ + suspend fun pendingQuarantineStates(): Map = buildMap { + dao.getAll().forEach { row -> + when (row.kind) { + MutationKind.QUARANTINE_FLAG -> runCatching { + json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload) + }.getOrNull()?.let { put(it.trackId, true) } + MutationKind.QUARANTINE_UNFLAG -> runCatching { + json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload) + }.getOrNull()?.let { put(it.trackId, false) } + } + } + } + suspend fun enqueueQuarantineFlag( trackId: String, reason: String, @@ -173,25 +220,6 @@ class MutationQueue @Inject constructor( ), ) - /** - * Queues a suggestion snooze (or its undo) for replay. [desiredSnoozed] - * is the TARGET state, so repeated taps collapse to one replay. - * - * [name] is carried even for an un-snooze, where the server ignores it, - * so a single payload shape serves both directions. - */ - suspend fun enqueueSuggestionSnoozeToggle( - mbid: String, - name: String, - desiredSnoozed: Boolean, - ): Long = insertUserDriven( - MutationKind.SUGGESTION_SNOOZE_TOGGLE, - json.encodeToString( - SuggestionSnoozeTogglePayload.serializer(), - SuggestionSnoozeTogglePayload(mbid, name, desiredSnoozed), - ), - ) - /** Queues the user's whole normalization preference for replay. */ suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven( MutationKind.NORMALIZATION_SET, @@ -217,14 +245,6 @@ class MutationQueue @Inject constructor( json.encodeToString(NotificationSettingPayload.serializer(), payload), ) - suspend fun enqueueRequestCancel(requestId: String): Long = insertUserDriven( - MutationKind.REQUEST_CANCEL, - json.encodeToString( - RequestCancelPayload.serializer(), - RequestCancelPayload(requestId), - ), - ) - suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert( CachedMutationEntity( kind = MutationKind.PLAY_OFFLINE, @@ -257,21 +277,6 @@ class MutationQueue @Inject constructor( } } -/** - * Persisted payload for `MutationKind.SUGGESTION_SNOOZE_TOGGLE`. - * `desiredSnoozed` is the *target* state, matching [LikeTogglePayload], so - * the replayer can collapse repeated toggles for one candidate down to the - * last intent. Both directions are idempotent server-side: re-snoozing - * extends the window, and un-snoozing something already back is a 404 the - * replayer treats as permanent (nothing left to do). - */ -@Serializable -data class SuggestionSnoozeTogglePayload( - val mbid: String, - val name: String, - val desiredSnoozed: Boolean, -) - /** * Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the * `DELETE /api/quarantine/{trackId}` call lost during a connectivity @@ -280,16 +285,60 @@ data class SuggestionSnoozeTogglePayload( @Serializable data class QuarantineUnflagPayload(val trackId: String) +/** The key [MutationQueue.pendingLikeStates] files a like toggle under. */ +fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId" + /** * Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to - * append to one playlist. The server is idempotent at the - * (playlist_id, track_id) pair level — re-firing the same payload yields - * no duplicates. + * append to one playlist. [requestId] is the id the live send carried, so + * the server can tell a replay of an append it already applied (its reply + * was lost) from a new one. Rows queued before it existed have none and + * append on every send, as they always did. */ @Serializable data class PlaylistAppendPayload( val playlistId: String, val trackIds: List, + val requestId: String? = null, +) + +/** Persisted payload for `MutationKind.PLAYLIST_CREATE`; [id] is the one the app chose. */ +@Serializable +data class PlaylistCreatePayload( + val id: String, + val name: String, + val isPublic: Boolean = false, +) + +/** Persisted payload for `MutationKind.PLAYLIST_UPDATE`; a null field is left as it is. */ +@Serializable +data class PlaylistUpdatePayload( + val playlistId: String, + val name: String? = null, + val isPublic: Boolean? = null, +) + +/** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */ +@Serializable +data class PlaylistDeletePayload(val playlistId: String) + +/** + * Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is + * the song at [position] when the listener removed it; null for an entry + * whose song has left the library. + */ +@Serializable +data class PlaylistRemoveTrackPayload( + val playlistId: String, + val position: Int, + val trackId: String? = null, +) + +/** Persisted payload for `MutationKind.PLAYLIST_REORDER`: the songs in their new order. */ +@Serializable +data class PlaylistReorderPayload( + val playlistId: String, + val trackIds: List, ) /** @@ -337,15 +386,6 @@ data class PlayEndedPayload( val durationPlayedMs: Long, ) -/** - * Persisted payload for `MutationKind.REQUEST_CANCEL` — the - * `POST /api/requests/{id}/cancel` call lost during a connectivity - * hiccup. Server is idempotent on re-cancel (already-cancelled - * request stays cancelled). - */ -@Serializable -data class RequestCancelPayload(val requestId: String) - /** * Persisted payload for `MutationKind.PLAYBACK_ERROR_REPORT` — the * `POST /api/playback-errors` call lost during a connectivity hiccup. diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt index 5a28f9b7..96c1f400 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt @@ -3,7 +3,7 @@ package com.fabledsword.minstrel.cache.mutations import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest -import com.fabledsword.minstrel.api.endpoints.DiscoverApi +import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest import com.fabledsword.minstrel.api.endpoints.EventsApi import com.fabledsword.minstrel.api.endpoints.FlagRequest import com.fabledsword.minstrel.api.endpoints.LikesApi @@ -15,19 +15,19 @@ import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi import com.fabledsword.minstrel.api.endpoints.PlaylistsApi import com.fabledsword.minstrel.api.endpoints.QuarantineApi -import com.fabledsword.minstrel.api.endpoints.RequestsApi +import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest +import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.models.wire.PlayEndedRequest import com.fabledsword.minstrel.models.wire.PlayOfflineRequest -import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.cache.account.AccountCache import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.settings.data.NormalizationPrefs -import com.fabledsword.minstrel.models.wire.CreateRequestBody import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter @@ -56,10 +56,16 @@ import javax.inject.Singleton * - RETRY — transient (transport, 5xx, 408, 429) → leave queued, bump * attempts, retry on the next trigger. * + * Queued writes belong to the account that made them, and are sent only + * while [AccountCache] reports that account is the one signed in; when + * another account signs in, AccountCache clears them instead. + * * Triggered by: * - app start (MinstrelApplication @Inject forces the singleton's init) * - AuthStore.sessionCookie transitioning to non-null (sign-in / cold * start with a persisted cookie) + * - AccountCache confirming the signed-in account owns the queue (just + * after a sign-in, once the account is known) * - NetworkStatusController recovering to Healthy (server reachable again * mid-session — covers offline→online without needing a cold start) * @@ -72,17 +78,16 @@ import javax.inject.Singleton class MutationReplayer @Inject constructor( private val dao: CachedMutationDao, private val authStore: AuthStore, + private val accountCache: AccountCache, private val json: Json, @ApplicationScope private val scope: CoroutineScope, networkStatus: NetworkStatusController, retrofit: Retrofit, ) { private val likesApi: LikesApi = retrofit.create() - private val discoverApi: DiscoverApi = retrofit.create() private val quarantineApi: QuarantineApi = retrofit.create() private val playlistsApi: PlaylistsApi = retrofit.create() private val eventsApi: EventsApi = retrofit.create() - private val requestsApi: RequestsApi = retrofit.create() private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create() private val meApi: MeApi = retrofit.create() private val notificationsApi: NotificationsApi = retrofit.create() @@ -98,6 +103,11 @@ class MutationReplayer @Inject constructor( .distinctUntilChanged() .collect { drainSafe() } } + scope.launch { + accountCache.ownedBySignedInUser + .filter { it } + .collect { drainSafe() } + } // Server-reachable-again: replay queued writes the moment the // health signal recovers, so an offline→online transition mid- // session doesn't wait for the next cold start / re-auth. @@ -121,21 +131,40 @@ class MutationReplayer @Inject constructor( } private suspend fun drain() { + // Another account's writes must not go out under this session. + if (!accountCache.ownedBySignedInUser.value) return val rows = dao.getAll() - // Collapse superseded toggles (likes, suggestion snoozes): only the - // latest desired state per entity is replayed; older toggles for the - // same entity are dropped unsent. Without this, partial-failure + + // Collapse superseded toggles (likes, settings): only the latest + // desired state per entity is replayed; older toggles for the same + // entity are dropped unsent. Without this, partial-failure + // differential retry could replay an older toggle last and invert the - // final state — a snooze the user already undid would come back. + // final state — an unlike the user already made would be undone. val superseded = supersededToggleIds(rows, json) + // A playlist's changes go out in the order they were made: once one + // has to wait, the rest for that list wait behind it, so an add + // never reaches the server before the create of its list. + val waiting = HashSet() for (row in rows) { - if (row.id in superseded) { - dao.delete(row.id) - continue - } - when (outcomeFor(row)) { + replayRow(row, superseded = row.id in superseded, waiting = waiting) + } + } + + /** + * Sends one row, or drops it when a later row has superseded it, or + * leaves it queued when an earlier change to the same playlist is still + * waiting. A row that has to retry makes its playlist wait in [waiting]. + */ + private suspend fun replayRow(row: CachedMutationEntity, superseded: Boolean, waiting: MutableSet) { + val playlistId = playlistIdOf(row, json) + when { + superseded -> dao.delete(row.id) + playlistId != null && playlistId in waiting -> Unit + else -> when (outcomeFor(row)) { Outcome.SENT, Outcome.DROP -> dao.delete(row.id) - Outcome.RETRY -> dao.recordAttempt(row.id, Clock.System.now()) + Outcome.RETRY -> { + dao.recordAttempt(row.id, Clock.System.now()) + playlistId?.let(waiting::add) + } } } } @@ -152,10 +181,8 @@ class MutationReplayer @Inject constructor( Outcome.RETRY } - /** 4xx are permanent except the two "retry me" statuses. */ - private fun isPermanent(code: Int): Boolean = - code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX && - code != HTTP_TIMEOUT && code != HTTP_TOO_MANY + /** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */ + private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code) /** * Returns the outcome of replaying one row. SENT on a 2xx; DROP for an @@ -164,15 +191,18 @@ class MutationReplayer @Inject constructor( */ private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) { MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload) - MutationKind.REQUEST_CREATE -> dispatchRequestCreate(row.payload) MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload) - MutationKind.PLAYLIST_APPEND -> dispatchPlaylistAppend(row.payload) + MutationKind.PLAYLIST_APPEND, + MutationKind.PLAYLIST_CREATE, + MutationKind.PLAYLIST_UPDATE, + MutationKind.PLAYLIST_DELETE, + MutationKind.PLAYLIST_REMOVE_TRACK, + MutationKind.PLAYLIST_REORDER, + -> dispatchPlaylist(row) MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload) MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload) MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload) - MutationKind.REQUEST_CANCEL -> dispatchRequestCancel(row.payload) MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload) - MutationKind.SUGGESTION_SNOOZE_TOGGLE -> dispatchSuggestionSnoozeToggle(row.payload) MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload) MutationKind.NOTIFICATION_READ, MutationKind.NOTIFICATIONS_READ_ALL, @@ -206,34 +236,49 @@ class MutationReplayer @Inject constructor( return Outcome.SENT } - private suspend fun dispatchRequestCreate(payload: String): Outcome { - val decoded = json.decodeFromString(RequestCreatePayload.serializer(), payload) - discoverApi.createRequest( - CreateRequestBody( - kind = decoded.kind, - artistMbid = decoded.artistMbid, - artistName = decoded.artistName, - albumMbid = decoded.albumMbid, - albumTitle = decoded.albumTitle, - trackMbid = decoded.trackMbid, - trackTitle = decoded.trackTitle, - ), - ) - return Outcome.SENT - } - private suspend fun dispatchQuarantineUnflag(payload: String): Outcome { val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload) quarantineApi.unflag(decoded.trackId) return Outcome.SENT } - private suspend fun dispatchPlaylistAppend(payload: String): Outcome { - val decoded = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) - playlistsApi.appendTracks( - playlistId = decoded.playlistId, - body = AppendTracksRequest(trackIds = decoded.trackIds), - ) + /** + * A listener's own playlists, split out to keep [dispatch] simple. A + * 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since, + * and nothing is left to do. + */ + private suspend fun dispatchPlaylist(row: CachedMutationEntity): Outcome { + val payload = row.payload + when (row.kind) { + MutationKind.PLAYLIST_APPEND -> { + val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) + playlistsApi.appendTracks( + p.playlistId, + AppendTracksRequest(trackIds = p.trackIds, requestId = p.requestId), + ) + } + MutationKind.PLAYLIST_CREATE -> { + val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload) + playlistsApi.create(CreatePlaylistRequest(id = p.id, name = p.name, isPublic = p.isPublic)) + } + MutationKind.PLAYLIST_UPDATE -> { + val p = json.decodeFromString(PlaylistUpdatePayload.serializer(), payload) + playlistsApi.update(p.playlistId, UpdatePlaylistRequest(name = p.name, isPublic = p.isPublic)) + } + MutationKind.PLAYLIST_DELETE -> { + val p = json.decodeFromString(PlaylistDeletePayload.serializer(), payload) + playlistsApi.delete(p.playlistId) + } + MutationKind.PLAYLIST_REMOVE_TRACK -> { + val p = json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), payload) + playlistsApi.removeTrack(p.playlistId, p.position, p.trackId) + } + MutationKind.PLAYLIST_REORDER -> { + val p = json.decodeFromString(PlaylistReorderPayload.serializer(), payload) + playlistsApi.reorder(p.playlistId, ReorderTracksRequest(trackIds = p.trackIds)) + } + else -> return Outcome.DROP + } return Outcome.SENT } @@ -275,30 +320,6 @@ class MutationReplayer @Inject constructor( return Outcome.SENT } - private suspend fun dispatchRequestCancel(payload: String): Outcome { - val decoded = json.decodeFromString(RequestCancelPayload.serializer(), payload) - requestsApi.cancel(decoded.requestId) - return Outcome.SENT - } - - /** - * Replays a suggestion snooze in whichever direction the payload asks for. - * - * The un-snooze branch can legitimately 404 (the row already lapsed, or a - * previous attempt landed and the response was lost). [outcomeFor] classes - * 404 as permanent → DROP, which is right: the user's intended end state - * already holds, so there is nothing left to send. - */ - private suspend fun dispatchSuggestionSnoozeToggle(payload: String): Outcome { - val decoded = json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), payload) - if (decoded.desiredSnoozed) { - discoverApi.snoozeSuggestion(decoded.mbid, SnoozeSuggestionBody(name = decoded.name)) - } else { - discoverApi.unsnoozeSuggestion(decoded.mbid) - } - return Outcome.SENT - } - /** * Sends the queued normalization preference. The device already shows * it, so the server's echo is not written back: a change made since the @@ -342,19 +363,12 @@ class MutationReplayer @Inject constructor( ) return Outcome.SENT } - - private companion object { - const val HTTP_CLIENT_ERR_MIN = 400 - const val HTTP_CLIENT_ERR_MAX = 499 - const val HTTP_TIMEOUT = 408 - const val HTTP_TOO_MANY = 429 - } } /** * Row ids of desired-state toggles superseded by a later toggle for the same * entity. Applies to every kind whose payload encodes a TARGET state rather - * than an action — like-toggles, suggestion snoozes and the + * than an action — like-toggles, notification settings and the * normalization preference — because * replaying a stale one last would invert the final state. * @@ -388,14 +402,15 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when ( json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" } - MutationKind.SUGGESTION_SNOOZE_TOGGLE -> runCatching { - json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), row.payload) - }.getOrNull()?.let { "${row.kind}:${it.mbid}" } - MutationKind.NOTIFICATION_SETTING_SET -> runCatching { json.decodeFromString(NotificationSettingPayload.serializer(), row.payload) }.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" } + // A reorder is the list's whole new order, so only the last one counts. + MutationKind.PLAYLIST_REORDER -> runCatching { + json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload) + }.getOrNull()?.let { "${row.kind}:${it.playlistId}" } + // One preference per user, so every normalization row shares one key. MutationKind.NORMALIZATION_SET -> runCatching { json.decodeFromString(NormalizationPrefs.serializer(), row.payload) @@ -403,3 +418,25 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when ( else -> null } + +/** + * The playlist a queued row changes, or null for a row that isn't a + * playlist change (or won't decode, which its dispatcher then DROPs). + */ +internal fun playlistIdOf(row: CachedMutationEntity, json: Json): String? = runCatching { + when (row.kind) { + MutationKind.PLAYLIST_APPEND -> + json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_CREATE -> + json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id + MutationKind.PLAYLIST_UPDATE -> + json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_DELETE -> + json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_REMOVE_TRACK -> + json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_REORDER -> + json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId + else -> null + } +}.getOrNull() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/WriteOutcome.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/WriteOutcome.kt new file mode 100644 index 00000000..a49863d6 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/WriteOutcome.kt @@ -0,0 +1,58 @@ +package com.fabledsword.minstrel.cache.mutations + +import kotlinx.coroutines.CancellationException +import retrofit2.HttpException + +/** Whether a write reached the server, waits in the offline queue, or was refused. */ +enum class WriteOutcome { Synced, Queued, Refused } + +private const val HTTP_CLIENT_ERR_MIN = 400 +private const val HTTP_CLIENT_ERR_MAX = 499 +private const val HTTP_TIMEOUT = 408 +private const val HTTP_TOO_MANY = 429 + +/** + * Whether a server's HTTP error is worth trying again later: a 5xx (the + * server's trouble), 408 (timed out) or 429 (too many requests). Any other + * 4xx is the server saying no, and asking again gets the same answer. + * The replayer and [sendOrQueue] both decide by this. + */ +fun isRetryableStatus(code: Int): Boolean = + code !in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX || code == HTTP_TIMEOUT || code == HTTP_TOO_MANY + +/** + * Sends a write now, or queues it for the replayer when the server can't + * take it yet. The one rule every offline-first repository write follows: + * + * - The server took it: [WriteOutcome.Synced]. + * - No answer (offline, a dropped connection), or an error worth retrying + * ([isRetryableStatus]): [queue] runs and the result is Queued. + * - The server refused it (any other 4xx): nothing is queued, since a + * replay would be refused too. [onRefused] decides what the caller sees; + * by default the refusal is thrown, so the caller can say why. + * + * Cancellation passes through. + */ +suspend fun sendOrQueue( + send: suspend () -> Unit, + queue: suspend () -> Unit, + onRefused: (HttpException) -> WriteOutcome = { throw it }, +): WriteOutcome = + try { + send() + WriteOutcome.Synced + } catch (e: CancellationException) { + throw e + } catch (e: HttpException) { + if (isRetryableStatus(e.code())) { + queue() + WriteOutcome.Queued + } else { + onRefused(e) + } + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + queue() + WriteOutcome.Queued + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt b/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt index b51571a1..a19622c4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt @@ -70,6 +70,9 @@ class DiagnosticsUploader @Inject constructor( /** Coalesces concurrent triggers via tryLock — a drain in flight wins. */ private suspend fun drainSafe() { + // A trigger at launch can fire before the stored login has loaded; + // wait for it, so a signed-in user is not read as signed out. + authStore.awaitSessionHydrated() val clientId = authStore.clientId.value // Signed out / no client id yet → nothing to do. Single guard keeps // the return count within the detekt gate. diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/data/DiscoverRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/data/DiscoverRepository.kt deleted file mode 100644 index 96e08bec..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/data/DiscoverRepository.kt +++ /dev/null @@ -1,199 +0,0 @@ -package com.fabledsword.minstrel.discover.data - -import com.fabledsword.minstrel.api.endpoints.DiscoverApi -import com.fabledsword.minstrel.cache.mutations.MutationQueue -import com.fabledsword.minstrel.cache.mutations.RequestCreatePayload -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.RequestKind -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SeedContributionRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire -import com.fabledsword.minstrel.models.wire.CreateRequestBody -import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire -import com.fabledsword.minstrel.models.wire.SeedContributionWire -import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody -import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire -import retrofit2.HttpException -import retrofit2.Retrofit -import retrofit2.create -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Outcome of a `createRequest` call — discriminates "server accepted" - * from "network down, queued for later replay". The UI uses this to - * pick between "Requested" and "Queued" snackbars. - */ -enum class RequestOutcome { ACCEPTED, QUEUED } - -/** - * Read-through Discover surface: catalogue search, suggestion feed, and - * the request-creation write path. Writes never go fire-and-forget, so - * `createRequest` falls back to the MutationQueue on transport failure. - * - * Reads are not cached locally — discovery results are inherently - * transient (60s server-side LRU), so a local cache would win little. - */ -@Singleton -class DiscoverRepository @Inject constructor( - private val mutationQueue: MutationQueue, - retrofit: Retrofit, -) { - private val api: DiscoverApi = retrofit.create() - - suspend fun listSuggestions(): List = - api.listSuggestions().map { it.toDomain() } - - suspend fun listSnoozes(): List = - api.listSnoozes().map { it.toDomain() } - - /** - * Parks a suggestion ("not right now"). Offline-first: on - * transport failure the target state is queued for the replayer rather - * than dropped. - * - * Always reports success to the caller. Unlike a request, a snooze has no - * meaningful failed state to show — the user asked for a card to go away, - * and it will, either now or when the queue drains. - */ - suspend fun snoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze( - mbid = mbid, - name = name, - desiredSnoozed = true, - ) { api.snoozeSuggestion(mbid, SnoozeSuggestionBody(name = name)) } - - /** Brings a parked suggestion back. Same offline-first contract. */ - suspend fun unsnoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze( - mbid = mbid, - name = name, - desiredSnoozed = false, - ) { api.unsnoozeSuggestion(mbid) } - - private suspend fun toggleSnooze( - mbid: String, - name: String, - desiredSnoozed: Boolean, - call: suspend () -> Unit, - ) { - try { - call() - } catch (e: HttpException) { - // A 4xx is the server's considered answer, not a lost call, so - // queueing it would be wrong twice over: the replay is guaranteed - // to fail again, and the enqueue would raise a "will sync when - // online" snackbar for something already settled. The common case - // is a 404 from un-snoozing a row that already lapsed — which is - // the end state the user wanted anyway. - if (!isPermanent(e.code())) { - mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed) - } - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Transport failure — intentional swallow, same offline-first - // rationale as createRequest above. The queue carries the desired - // STATE, so a later undo supersedes this rather than fighting it - // on replay. - mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed) - } - } - - /** - * Mirrors MutationReplayer's classification so the enqueue decision here - * and the drop decision there can't disagree: 4xx is permanent except the - * two "retry me" statuses. - */ - private fun isPermanent(code: Int): Boolean = - code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX && - code != HTTP_TIMEOUT && code != HTTP_TOO_MANY - - suspend fun search(query: String, kind: RequestKind): List = - api.search(query = query, kind = kind.wire).map { it.toDomain() } - - /** - * Fires `POST /api/requests`; on transport failure enqueues a - * `RequestCreatePayload` for the Phase-12.2 replayer to drain. - * Returns [RequestOutcome.ACCEPTED] when the server responded - * 2xx, [RequestOutcome.QUEUED] when the call was buffered. - */ - suspend fun createRequest( - kind: RequestKind, - artistMbid: String, - artistName: String, - albumMbid: String? = null, - albumTitle: String? = null, - trackMbid: String? = null, - trackTitle: String? = null, - ): RequestOutcome { - val payload = RequestCreatePayload( - kind = kind.wire, - artistMbid = artistMbid, - artistName = artistName, - albumMbid = albumMbid?.ifEmpty { null }, - albumTitle = albumTitle?.ifEmpty { null }, - trackMbid = trackMbid?.ifEmpty { null }, - trackTitle = trackTitle?.ifEmpty { null }, - ) - return try { - api.createRequest(payload.toBody()) - RequestOutcome.ACCEPTED - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Intentional swallow — see LikesRepository.toggleLike for - // the same offline-first rationale. - mutationQueue.enqueueRequestCreate(payload) - RequestOutcome.QUEUED - } - } - - private companion object { - const val HTTP_CLIENT_ERR_MIN = 400 - const val HTTP_CLIENT_ERR_MAX = 499 - const val HTTP_TIMEOUT = 408 - const val HTTP_TOO_MANY = 429 - } -} - -// ── Mappers (internal — wire types stay out of UI) ── - -private fun CatalogueSearchResultWire.toDomain(): CatalogueResultRef = CatalogueResultRef( - mbid = mbid, - name = name, - secondaryText = secondaryText, - imageUrl = imageUrl, - artistMbid = artistMbid, - albumMbid = albumMbid, - inLibrary = inLibrary, - requested = requested, -) - -private fun ArtistSuggestionWire.toDomain(): ArtistSuggestionRef = ArtistSuggestionRef( - mbid = mbid, - name = name, - imageUrl = imageUrl, - attribution = attribution.map { it.toDomain() }, - matchedTags = matchedTags, -) - -private fun SeedContributionWire.toDomain(): SeedContributionRef = SeedContributionRef( - name = name, - isLiked = isLiked, -) - -private fun SuggestionSnoozeWire.toDomain(): SuggestionSnoozeRef = SuggestionSnoozeRef( - mbid = mbid, - name = name, - snoozedUntil = snoozedUntil, -) - -private fun RequestCreatePayload.toBody(): CreateRequestBody = CreateRequestBody( - kind = kind, - artistMbid = artistMbid, - artistName = artistName, - albumMbid = albumMbid, - albumTitle = albumTitle, - trackMbid = trackMbid, - trackTitle = trackTitle, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverScreen.kt deleted file mode 100644 index ade53f2a..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverScreen.kt +++ /dev/null @@ -1,353 +0,0 @@ -package com.fabledsword.minstrel.discover.ui - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.unit.dp -import androidx.hilt.navigation.compose.hiltViewModel -import androidx.navigation.NavHostController -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.Search as LucideSearch -import com.fabledsword.minstrel.discover.data.RequestOutcome -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.RequestKind -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import com.fabledsword.minstrel.nav.Discover -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets -import com.fabledsword.minstrel.shared.widgets.ErrorRetry -import com.fabledsword.minstrel.shared.widgets.LoadingCentered -import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar -import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold -import kotlinx.coroutines.launch - -// ─── Screen ────────────────────────────────────────────────────────── - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun DiscoverScreen( - navController: NavHostController, - viewModel: DiscoverViewModel = hiltViewModel(), -) { - val state by viewModel.state.collectAsStateWithLifecycle() - val snackbar = remember { SnackbarHostState() } - val scope = rememberCoroutineScope() - - Scaffold( - contentWindowInsets = ShellContentWindowInsets, - modifier = Modifier.fillMaxSize(), - topBar = { - MinstrelTopAppBar( - title = "Discover", - navController = navController, - currentRouteName = Discover::class.qualifiedName, - onBack = { navController.popBackStack() }, - ) - }, - snackbarHost = { SnackbarHost(snackbar) }, - ) { inner -> - DiscoverBody( - inner = inner, - state = state, - viewModel = viewModel, - snackbar = snackbar, - scope = scope, - ) - } -} - -@Composable -private fun DiscoverBody( - inner: androidx.compose.foundation.layout.PaddingValues, - state: DiscoverState, - viewModel: DiscoverViewModel, - snackbar: SnackbarHostState, - scope: kotlinx.coroutines.CoroutineScope, -) { - Column(modifier = Modifier.fillMaxSize().padding(inner)) { - SearchBar( - query = state.query, - onQueryChange = viewModel::setQuery, - onSubmit = viewModel::runSearch, - ) - KindChips(kind = state.kind, onChange = viewModel::setKind) - PullToRefreshScaffold( - onRefresh = { viewModel.loadSuggestions().join() }, - modifier = Modifier.fillMaxSize(), - ) { - when (val r = state.results) { - ResultsState.Idle -> SuggestionsPane( - state = state.suggestions, - locallyRequestedMbids = state.locallyRequestedMbids, - snoozeUi = SnoozeUi( - locallySnoozedMbids = state.locallySnoozedMbids, - snoozes = state.snoozes, - // No snackbar on snooze: the row itself flips to "Not - // right now" with an Undo, so a snackbar would only - // repeat what the user can already see — and cover the - // next row while doing it. - onSnooze = { s -> scope.launch { viewModel.snoozeSuggestion(s) } }, - onUnsnooze = { mbid, name -> - scope.launch { viewModel.unsnoozeSuggestion(mbid, name) } - }, - ), - onRequest = { s -> - scope.launch { - val outcome = viewModel.requestSuggestion(s) - snackbar.showSnackbar(snackbarFor(outcome, s.name)) - } - }, - onRetry = { viewModel.loadSuggestions() }, - ) - ResultsState.Loading -> LoadingCentered() - is ResultsState.Loaded -> ResultsList( - rows = r.items, - locallyRequestedMbids = state.locallyRequestedMbids, - onRequest = { row -> - scope.launch { - val outcome = viewModel.requestRow(row) - snackbar.showSnackbar(snackbarFor(outcome, row.name)) - } - }, - ) - is ResultsState.Error -> ErrorRetry( - title = "Search failed", - message = r.message, - onRetry = viewModel::runSearch, - ) - } - } - } -} - -@Composable -private fun SearchBar( - query: String, - onQueryChange: (String) -> Unit, - onSubmit: () -> Unit, -) { - OutlinedTextField( - value = query, - onValueChange = onQueryChange, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - singleLine = true, - placeholder = { Text("Search MusicBrainz for new music") }, - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - keyboardActions = KeyboardActions(onSearch = { onSubmit() }), - trailingIcon = { - IconButton(onClick = onSubmit) { - Icon(Lucide.LucideSearch, contentDescription = "Search") - } - }, - ) -} - -@Composable -private fun KindChips(kind: RequestKind, onChange: (RequestKind) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 4.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - FilterChip( - selected = kind == RequestKind.ARTIST, - onClick = { onChange(RequestKind.ARTIST) }, - label = { Text("Artists") }, - ) - FilterChip( - selected = kind == RequestKind.ALBUM, - onClick = { onChange(RequestKind.ALBUM) }, - label = { Text("Albums") }, - ) - } -} - -/** - * The snooze surface's data and callbacks, bundled rather than threaded - * through as separate parameters: the pane carries three actions, and the - * signatures stop being readable otherwise. - */ -private data class SnoozeUi( - val locallySnoozedMbids: Set, - val snoozes: List, - val onSnooze: (ArtistSuggestionRef) -> Unit, - val onUnsnooze: (String, String) -> Unit, -) - -@Composable -private fun SuggestionsPane( - state: SuggestionState, - locallyRequestedMbids: Set, - snoozeUi: SnoozeUi, - onRequest: (ArtistSuggestionRef) -> Unit, - onRetry: () -> Unit, -) { - when (state) { - SuggestionState.Loading -> LoadingCentered() - is SuggestionState.Error -> ErrorRetry( - title = "Couldn't load suggestions", - message = state.message, - onRetry = onRetry, - ) - is SuggestionState.Loaded -> SuggestionsList( - items = state.items.filter { it.mbid !in locallyRequestedMbids }, - snoozeUi = snoozeUi, - onRequest = onRequest, - ) - } -} - -@Composable -private fun SuggestionsList( - items: List, - snoozeUi: SnoozeUi, - onRequest: (ArtistSuggestionRef) -> Unit, -) { - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(bottom = 16.dp), - ) { - item { SuggestionsHeader() } - if (items.isEmpty()) { - // An empty deck means one of two things — no listening signal yet, - // or "you parked them all" — and telling the second user to go - // listen to something would be wrong advice. - item { - CenteredMessage( - if (snoozeUi.snoozes.isEmpty()) { - "Listen to or like an artist to fill this in." - } else { - "Nothing new right now — the artists you've parked are below." - }, - ) - } - } else { - items(items = items, key = { it.mbid }) { s -> - SuggestionTile( - s = s, - snoozed = s.mbid in snoozeUi.locallySnoozedMbids, - onRequest = { onRequest(s) }, - onSnooze = { snoozeUi.onSnooze(s) }, - onUnsnooze = { snoozeUi.onUnsnooze(s.mbid, s.name) }, - ) - HorizontalDivider() - } - } - // Parked candidates live at the bottom of the same scroll, not behind a - // separate screen: it's a short list the user rarely needs, but it must - // be reachable — a snoozed candidate is gone from the deck above, so - // this is the only way back to it. - if (snoozeUi.snoozes.isNotEmpty()) { - item { SnoozedHeader() } - items(items = snoozeUi.snoozes, key = { "snoozed-${it.mbid}" }) { row -> - SnoozedTile( - row = row, - onUnsnooze = { snoozeUi.onUnsnooze(row.mbid, row.name) }, - ) - HorizontalDivider() - } - } - } -} - -@Composable -private fun SnoozedHeader() { - Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) { - HorizontalDivider(modifier = Modifier.padding(bottom = 12.dp)) - Text( - text = "Not right now", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onBackground, - ) - Text( - text = "These come back on their own. Nothing here counts against your taste profile.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -@Composable -private fun SuggestionsHeader() { - Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) { - Text( - text = "Suggested for you", - style = MaterialTheme.typography.titleLarge, - color = MaterialTheme.colorScheme.onBackground, - ) - Text( - text = "Out-of-library artists drawn from what you've liked and played.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -@Composable -private fun ResultsList( - rows: List, - locallyRequestedMbids: Set, - onRequest: (CatalogueResultRef) -> Unit, -) { - if (rows.isEmpty()) { - CenteredMessage("Nothing to add for that search yet.") - return - } - LazyColumn(modifier = Modifier.fillMaxSize()) { - items(items = rows, key = { it.mbid }) { row -> - ResultTile( - row = row, - locallyRequested = row.mbid in locallyRequestedMbids, - onRequest = { onRequest(row) }, - ) - HorizontalDivider() - } - } -} - -@Composable -private fun CenteredMessage(text: String) { - Box(modifier = Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) { - Text( - text = text, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -private fun snackbarFor(outcome: RequestOutcome, name: String): String = when (outcome) { - RequestOutcome.ACCEPTED -> "Requested: $name" - RequestOutcome.QUEUED -> "Request queued: $name" -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverTiles.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverTiles.kt deleted file mode 100644 index 334d3427..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverTiles.kt +++ /dev/null @@ -1,191 +0,0 @@ -package com.fabledsword.minstrel.discover.ui - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.AssistChip -import androidx.compose.material3.Button -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.composables.icons.lucide.Clock -import com.composables.icons.lucide.Disc3 -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.User -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import com.fabledsword.minstrel.shared.widgets.ServerImage - -@Composable -internal fun SuggestionTile( - s: ArtistSuggestionRef, - snoozed: Boolean, - onRequest: () -> Unit, - onSnooze: () -> Unit, - onUnsnooze: () -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Avatar(imageUrl = s.imageUrl, fallback = Lucide.User, circular = true) - Column(modifier = Modifier.weight(1f)) { - Text( - text = s.name, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - // Once parked, the "because you liked X" line is no longer the - // useful thing to say — confirming what just happened is. - val secondary = - if (snoozed) "Not right now — hidden for a while" else s.reasonText - if (secondary.isNotEmpty()) { - Text( - text = secondary, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - } - if (snoozed) { - TextButton(onClick = onUnsnooze) { Text("Undo") } - } else { - Button(onClick = onRequest) { Text("Request") } - IconButton(onClick = onSnooze) { - Icon( - imageVector = Lucide.Clock, - // The label states what happens and passes no judgement on the - // music: never "not for me". - contentDescription = "Not right now — hide ${s.name} for a while", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } -} - -/** - * One row of the parked list. This exists because a snoozed candidate is by - * definition absent from the deck above, so without it there is no route back - * to an un-snooze once the card has gone. - */ -@Composable -internal fun SnoozedTile(row: SuggestionSnoozeRef, onUnsnooze: () -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = row.name, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - text = "Back ${row.returnsIn()}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - TextButton(onClick = onUnsnooze) { Text("Bring back") } - } -} - -@Composable -internal fun ResultTile( - row: CatalogueResultRef, - locallyRequested: Boolean, - onRequest: () -> Unit, -) { - val effectivelyRequested = row.requested || locallyRequested - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Avatar(imageUrl = row.imageUrl, fallback = Lucide.Disc3, circular = false) - Column(modifier = Modifier.weight(1f)) { - Text( - text = row.name, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (row.secondaryText.isNotEmpty()) { - Text( - text = row.secondaryText, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - when { - row.inLibrary -> AssistChip(onClick = {}, enabled = false, label = { Text("In library") }) - effectivelyRequested -> - AssistChip(onClick = {}, enabled = false, label = { Text("Requested") }) - else -> Button(onClick = onRequest) { Text("Request") } - } - } -} - -@Composable -private fun Avatar(imageUrl: String, fallback: ImageVector, circular: Boolean) { - val clip = if (circular) CircleShape else RoundedCornerShape(6.dp) - Box( - modifier = Modifier - .size(56.dp) - .clip(clip) - .background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - // The server hands back its own art endpoint (relative), - // which answers 404 when no source has an image: ServerImage resolves - // the path and shows the icon while loading and on a miss. - ServerImage( - url = imageUrl, - contentDescription = null, - modifier = Modifier.fillMaxSize(), - ) { - Icon( - imageVector = fallback, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverViewModel.kt deleted file mode 100644 index bce9f3c9..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverViewModel.kt +++ /dev/null @@ -1,206 +0,0 @@ -package com.fabledsword.minstrel.discover.ui - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.fabledsword.minstrel.api.ErrorCopy -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.recoveries -import com.fabledsword.minstrel.discover.data.DiscoverRepository -import com.fabledsword.minstrel.discover.data.RequestOutcome -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.RequestKind -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import javax.inject.Inject - -// ─── State ─────────────────────────────────────────────────────────── - -data class DiscoverState( - val query: String = "", - val kind: RequestKind = RequestKind.ARTIST, - val suggestions: SuggestionState = SuggestionState.Loading, - val results: ResultsState = ResultsState.Idle, - val locallyRequestedMbids: Set = emptySet(), - /** - * Parked candidates, for the manage list under the feed. Empty is the - * normal case and hides the section entirely. - */ - val snoozes: List = emptyList(), - /** - * Just-snoozed MBIDs. These keep their row visible showing an Undo rather - * than yanking it out from under the user's finger; the row is gone on the - * next load, and [snoozes] is the way back after that. - */ - val locallySnoozedMbids: Set = emptySet(), -) - -sealed interface SuggestionState { - data object Loading : SuggestionState - data class Loaded(val items: List) : SuggestionState - data class Error(val message: String) : SuggestionState -} - -sealed interface ResultsState { - /** No active search — the screen shows the suggestion feed. */ - data object Idle : ResultsState - data object Loading : ResultsState - data class Loaded(val items: List) : ResultsState - data class Error(val message: String) : ResultsState -} - -// ─── ViewModel ─────────────────────────────────────────────────────── - -@HiltViewModel -class DiscoverViewModel @Inject constructor( - private val repository: DiscoverRepository, - networkStatus: NetworkStatusController, -) : ViewModel() { - - private val internal = MutableStateFlow(DiscoverState()) - val state: StateFlow = internal.asStateFlow() - - init { - loadSuggestions() - // Screen-level auto-recovery: re-run whichever pane - // failed while the server was unreachable once health returns. - viewModelScope.launch { - networkStatus.recoveries().collect { - val s = internal.value - if (s.suggestions is SuggestionState.Error) loadSuggestions() - if (s.results is ResultsState.Error) runSearch() - } - } - } - - fun setQuery(value: String) { - internal.update { - // Clearing the box returns to the suggestion feed. - val newResults = if (value.isBlank()) ResultsState.Idle else it.results - it.copy(query = value, results = newResults) - } - } - - fun setKind(kind: RequestKind) { - internal.update { it.copy(kind = kind) } - if (internal.value.query.isNotBlank()) runSearch() - } - - fun loadSuggestions(): Job = viewModelScope.launch { - internal.update { it.copy(suggestions = SuggestionState.Loading) } - try { - val items = repository.listSuggestions() - internal.update { it.copy(suggestions = SuggestionState.Loaded(items)) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - suggestions = SuggestionState.Error( - ErrorCopy.fromThrowable(e), - ), - ) - } - } - // Refresh the parked list alongside the deck: a snooze made on another - // client should show up here, and one whose window lapsed should drop - // off. Sequenced after the deck load rather than raced with it so the - // two panes can't disagree about a candidate mid-refresh. - loadSnoozes() - } - - /** - * Loads the parked list. Failure is deliberately silent: this is a - * secondary pane, and an error banner for it would sit above the suggestion - * feed the user actually came for. The list stays as-is and the next - * refresh retries. - */ - private suspend fun loadSnoozes() { - try { - val rows = repository.listSnoozes() - internal.update { it.copy(snoozes = rows) } - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Keep whatever we last showed rather than blanking the section. - } - } - - /** - * Parks a suggestion. Flips the row locally first so the tap registers - * immediately; the repository handles the offline case, so there is no - * failure branch to revert here — unlike the web client, where the fetch - * either lands or doesn't. - */ - suspend fun snoozeSuggestion(s: ArtistSuggestionRef) { - internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids + s.mbid) } - repository.snoozeSuggestion(s.mbid, s.name) - loadSnoozes() - } - - /** Brings a parked suggestion back, from either the card or the list. */ - suspend fun unsnoozeSuggestion(mbid: String, name: String) { - internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids - mbid) } - repository.unsnoozeSuggestion(mbid, name) - loadSnoozes() - } - - fun runSearch() { - val q = internal.value.query.trim() - if (q.isEmpty()) { - internal.update { it.copy(results = ResultsState.Idle) } - return - } - viewModelScope.launch { - internal.update { it.copy(results = ResultsState.Loading) } - try { - val rows = repository.search(q, internal.value.kind) - internal.update { it.copy(results = ResultsState.Loaded(rows)) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy(results = ResultsState.Error(ErrorCopy.fromThrowable(e))) - } - } - } - } - - /** - * Request a search-result row. Returns the outcome (ACCEPTED vs - * QUEUED) so the screen can pick the snackbar wording and update - * the local "requested" overlay. - */ - suspend fun requestRow(row: CatalogueResultRef): RequestOutcome { - val kind = internal.value.kind - val outcome = repository.createRequest( - kind = kind, - artistMbid = if (kind == RequestKind.ARTIST) row.mbid else row.artistMbid, - artistName = if (kind == RequestKind.ARTIST) row.name else row.secondaryText, - albumMbid = if (kind == RequestKind.ALBUM) row.mbid else null, - albumTitle = if (kind == RequestKind.ALBUM) row.name else null, - ) - markRequested(row.mbid) - return outcome - } - - suspend fun requestSuggestion(s: ArtistSuggestionRef): RequestOutcome { - val outcome = repository.createRequest( - kind = RequestKind.ARTIST, - artistMbid = s.mbid, - artistName = s.name, - ) - markRequested(s.mbid) - return outcome - } - - private fun markRequested(mbid: String) { - internal.update { it.copy(locallyRequestedMbids = it.locallyRequestedMbids + mbid) } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt index db1fcf4b..dfcd1997 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt @@ -36,7 +36,6 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost @@ -50,24 +49,25 @@ import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController -import coil3.compose.AsyncImage import com.composables.icons.lucide.Heart import com.composables.icons.lucide.History import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.Music import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.home.data.HomeRepository import com.fabledsword.minstrel.library.data.LibraryRepository +import com.fabledsword.minstrel.library.data.playAlbumFromStart +import com.fabledsword.minstrel.library.data.shufflePlayArtist import com.fabledsword.minstrel.library.widgets.AlbumCard import com.fabledsword.minstrel.library.widgets.ArtistCard import com.fabledsword.minstrel.models.AlbumRef @@ -80,11 +80,18 @@ import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.nav.Home import com.fabledsword.minstrel.nav.PlaylistDetail +import com.fabledsword.minstrel.playlists.assignShelfCovers +import com.fabledsword.minstrel.playlists.byShelfRank import com.fabledsword.minstrel.playlists.data.PlaylistsRepository import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled +import com.fabledsword.minstrel.playlists.shelfMeta import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard -import com.fabledsword.minstrel.playlists.widgets.PlaylistCard +import com.fabledsword.minstrel.playlists.widgets.GenreBandCard +import com.fabledsword.minstrel.playlists.widgets.PlaceholderShape import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard +import com.fabledsword.minstrel.playlists.widgets.SongsLikeCard +import com.fabledsword.minstrel.playlists.widgets.TallPlaylistCard +import com.fabledsword.minstrel.playlists.widgets.WidePlaylistCard import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.UpdateVeilController import com.fabledsword.minstrel.shared.VeilOutcome @@ -102,6 +109,7 @@ import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader +import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb import com.fabledsword.minstrel.update.ui.UpdateNotices import com.fabledsword.minstrel.update.ui.UpdateViewModel import dagger.hilt.android.lifecycle.HiltViewModel @@ -268,44 +276,18 @@ class HomeViewModel @Inject constructor( */ suspend fun playAlbum(albumId: String) { viewModelScope.launch { - try { - val detail = libraryRepository.refreshAlbumDetail(albumId) - if (detail.tracks.isEmpty()) { - snackbarMessages.trySend("This album has no tracks to play.") - } else { - player.setQueue(detail.tracks, initialIndex = 0, source = "album:$albumId") - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - snackbarMessages.trySend( - "Couldn't start playback: ${ErrorCopy.fromThrowable(e)}", - ) - } + playAlbumFromStart(albumId, libraryRepository, player) { snackbarMessages.trySend(it) } }.join() } /** * Tap the artist play-button overlay: fetch every track across the - * artist's albums, Fisher-Yates shuffle, play from index 0. Empty + - * error semantics follow [playAlbum]. + * artist's albums, shuffle, play from index 0 (shufflePlayArtist, as + * the Artist page's Play does). */ suspend fun playArtistShuffled(artistId: String) { viewModelScope.launch { - try { - val tracks = libraryRepository.fetchArtistTracks(artistId).shuffled() - if (tracks.isEmpty()) { - snackbarMessages.trySend("This artist has no tracks to play.") - } else { - player.setQueue(tracks, initialIndex = 0, source = "artist:$artistId") - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - snackbarMessages.trySend( - "Couldn't start playback: ${ErrorCopy.fromThrowable(e)}", - ) - } + shufflePlayArtist(artistId, libraryRepository, player) { snackbarMessages.trySend(it) } }.join() } @@ -763,6 +745,7 @@ private fun HomeSuccessContent( // pool cards lead the row. Songs-like has its own row below. PlaylistsRow( title = "Playlists", + shape = ShelfShape.WIDE, rowItems = buildPlaylistsRow(sections.playlists, systemStatus, offline), offline = offline, onPlaylistClick = onPlaylistClick, @@ -781,6 +764,13 @@ private fun HomeSuccessContent( onPlayPool = onPlayPool, onPlayPlaylist = onPlayPlaylist, ) + genreMixSection( + playlists = sections.playlists, + offline = offline, + onPlaylistClick = onPlaylistClick, + onPlayPool = onPlayPool, + onPlayPlaylist = onPlayPlaylist, + ) youMightLikeSection( albums = sections.youMightLikeAlbums, artists = sections.youMightLikeArtists, @@ -824,6 +814,33 @@ private fun LazyListScope.songsLikeSection( item { PlaylistsRow( title = "Songs like…", + shape = ShelfShape.ROUND, + rowItems = rowItems, + offline = offline, + onPlaylistClick = onPlaylistClick, + onPlayPool = onPlayPool, + onPlayPlaylist = onPlayPlaylist, + ) + } +} + +/** + * The "Your genres" row: one mix per genre the user listens to. Hidden + * when there is nothing to show, built or cached. + */ +private fun LazyListScope.genreMixSection( + playlists: List, + offline: Boolean, + onPlaylistClick: (String) -> Unit, + onPlayPool: (OfflinePoolKind) -> Unit, + onPlayPlaylist: suspend (PlaylistRef) -> Unit, +) { + val rowItems = buildGenreMixRow(playlists, offline) + if (rowItems.isEmpty()) return + item { + PlaylistsRow( + title = "Your genres", + shape = ShelfShape.BAND, rowItems = rowItems, offline = offline, onPlaylistClick = onPlaylistClick, @@ -1088,28 +1105,41 @@ private fun AlbumsRow( items(items = albums, key = { it.id }) { tile -> val album = tile.value if (album == null) { - SkeletonAlbumTile() + SkeletonAlbumTile(artSize = SECONDARY_ALBUM_ART) } else { AlbumCard( album = album, onClick = { onAlbumClick(album.id) }, onPlay = { onPlayAlbum(album.id) }, + artSize = SECONDARY_ALBUM_ART, ) } } } } +/** + * A shelf of playlist tiles in one [shape]. Each tile gets cover albums no + * tile before it already shows (assignShelfCovers), and the size and refresh + * time the shelf's mixes share go beside the title once (shelfMeta). + */ @Composable private fun PlaylistsRow( title: String, + shape: ShelfShape, rowItems: List, offline: Boolean, onPlaylistClick: (String) -> Unit, onPlayPool: (OfflinePoolKind) -> Unit, onPlayPlaylist: suspend (PlaylistRef) -> Unit, ) { - HorizontalScrollRow(title = title) { + val reals = rowItems.filterIsInstance().map { it.playlist } + val covers = remember(reals, shape) { + reals.map { it.id }.zip(assignShelfCovers(reals, shape.coversPerTile)).toMap() + } + val meta = remember(reals) { shelfMeta(reals) } + val tallWidth = tallCardWidth(shape) + HorizontalScrollRow(title = title, meta = meta) { itemsIndexed(items = rowItems) { _, item -> when (item) { is PlaylistRowItem.OfflinePool -> OfflinePoolCard( @@ -1117,28 +1147,78 @@ private fun PlaylistsRow( icon = iconForPool(item.kind), onClick = { onPlayPool(item.kind) }, ) - is PlaylistRowItem.Real -> { + is PlaylistRowItem.Real -> ShelfTile( + shape = shape, + tallWidth = tallWidth, + playlist = item.playlist, + covers = covers[item.playlist.id].orEmpty(), // Greyed offline when the tile needs the live server or // isn't fully cached — dimmed but still tappable into the // detail to shuffle whatever subset is cached. - val greyed = offline && item.playlist.unavailableOffline - PlaylistCard( - playlist = item.playlist, - onClick = { onPlaylistClick(item.playlist.id) }, - onPlay = { onPlayPlaylist(item.playlist) }, - playEnabled = item.playlist.trackCount > 0 && !greyed, - greyed = greyed, - ) - } + greyed = offline && item.playlist.unavailableOffline, + onClick = { onPlaylistClick(item.playlist.id) }, + onPlay = { onPlayPlaylist(item.playlist) }, + ) is PlaylistRowItem.Placeholder -> PlaylistPlaceholderCard( label = item.label, variant = item.variant, + shape = if (tallWidth != null) PlaceholderShape.TALL else shape.placeholder, + modifier = if (tallWidth != null) Modifier.width(tallWidth) else Modifier, ) } } } } +/** + * On a narrow screen (a phone held upright) the wide shelf would leave one + * playlist in view, so it switches to tall cards sized for two whole cards + * and a glimpse of the third. Null keeps the shelf's own shape. + */ +@Composable +private fun tallCardWidth(shape: ShelfShape): Dp? { + val screen = LocalConfiguration.current.screenWidthDp.dp + return if (shape == ShelfShape.WIDE && screen < COMPACT_WIDTH) { + // Row padding at the start, two gaps between cards, the third's glimpse. + (screen - ROW_EDGE - ROW_GAP * 2 - NEXT_CARD_GLIMPSE) / 2 + } else { + null + } +} + +/** One playlist tile in its shelf's shape; a wide one turns tall at [tallWidth]. */ +@Composable +private fun ShelfTile( + shape: ShelfShape, + tallWidth: Dp?, + playlist: PlaylistRef, + covers: List, + greyed: Boolean, + onClick: () -> Unit, + onPlay: suspend () -> Unit, +) { + val playEnabled = playlist.trackCount > 0 + when { + tallWidth != null -> TallPlaylistCard(playlist, covers, tallWidth, onClick, onPlay, playEnabled, greyed) + shape == ShelfShape.WIDE -> WidePlaylistCard(playlist, covers, onClick, onPlay, playEnabled, greyed) + shape == ShelfShape.ROUND -> SongsLikeCard(playlist, covers, onClick, onPlay, playEnabled, greyed) + else -> GenreBandCard(playlist, covers, onClick, onPlay, playEnabled, greyed) + } +} + +/** + * The tile shape a Home playlist shelf uses, so shelves read apart at a + * glance: wide cards for the main mixes and playlists, circles for Songs + * like (the shape artists have everywhere), colour bands with a fan of + * covers for genres. [coversPerTile] is how many distinct covers a tile + * shows; [placeholder] is the shape a not-yet-built mix takes on the shelf. + */ +internal enum class ShelfShape(val coversPerTile: Int, val placeholder: PlaceholderShape) { + WIDE(coversPerTile = 1, placeholder = PlaceholderShape.WIDE), + ROUND(coversPerTile = 1, placeholder = PlaceholderShape.ROUND), + BAND(coversPerTile = 3, placeholder = PlaceholderShape.SQUARE), +} + private fun iconForPool(kind: OfflinePoolKind) = when (kind) { OfflinePoolKind.RECENTLY_PLAYED -> Lucide.History OfflinePoolKind.LIKED -> Lucide.Heart @@ -1233,6 +1313,25 @@ internal fun buildSongsLikeRow( } } +/** + * Builds the "Your genres" row: every genre mix, the genres the listener + * plays most first ([byShelfRank], the server's shelf_rank). No + * placeholders — a genre mix needs listening history or a genre-tagged + * library, so none built means nothing to show. Offline, fully-cached mixes come first and the rest are + * greyed. Mirrors the web Home's genreMixPlaylists. + */ +internal fun buildGenreMixRow( + owned: List, + offline: Boolean, +): List { + val mixes = owned + .filter { it.systemVariant == "genre_mix" } + .sortedWith(byShelfRank) + if (!offline) return mixes.map { PlaylistRowItem.Real(it) } + val (available, greyed) = mixes.partition { !it.unavailableOffline } + return (available + greyed).map { PlaylistRowItem.Real(it) } +} + /** * Curated real-playlist order (system primaries, then secondary, then user). * Must mirror [buildOnlineRow]'s slot order — the offline row reuses this and @@ -1263,6 +1362,20 @@ private fun variantFor(slot: String, s: SystemPlaylistsStatus): String = when { // once generated, are shown in full, uncapped. private const val SONGS_LIKE_PLACEHOLDER_SLOTS = 3 +// Below this width (a phone held upright) the Playlists shelf uses tall +// cards; the 600dp line is Material's compact width class. +private val COMPACT_WIDTH = 600.dp +private val ROW_EDGE = 16.dp +private val ROW_GAP = 8.dp +private val NEXT_CARD_GLIMPSE = 20.dp + +// Home's shelves step down in size below the playlists, as on web: Recently +// added keeps the full 144dp album cover, the You might like and Rediscover +// album shelves are smaller, and artist shelves smaller again. The ratios +// follow web's 176 / 144 / 128px minimum tile widths. +private val SECONDARY_ALBUM_ART = 120.dp +private val ARTIST_ART = 104.dp + /** * The 5 system playlist kinds the server generates that aren't pinned * to Home's primary slots. Order matches `systemPlaylistRegistry` in @@ -1287,12 +1400,13 @@ private fun ArtistsRow( items(items = artists, key = { it.id }) { tile -> val artist = tile.value if (artist == null) { - SkeletonArtistTile() + SkeletonArtistTile(artSize = ARTIST_ART) } else { ArtistCard( artist = artist, onClick = { onArtistClick(artist.id) }, onPlay = { onPlayArtist(artist.id) }, + artSize = ARTIST_ART, ) } } @@ -1401,29 +1515,11 @@ private fun CompactTrackTile( .padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, ) { - Box( - modifier = Modifier - .size(MOST_PLAYED_COVER_DP.dp) - .clip(RoundedCornerShape(4.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - if (track.coverUrl.isEmpty()) { - Icon( - imageVector = Lucide.Music, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(20.dp), - ) - } else { - AsyncImage( - model = track.coverUrl, - contentDescription = track.title, - modifier = Modifier.fillMaxSize(), - contentScale = ContentScale.Crop, - ) - } - } + TrackCoverThumb( + coverUrl = track.coverUrl, + contentDescription = track.title, + size = MOST_PLAYED_COVER_DP.dp, + ) Spacer(Modifier.width(8.dp)) Column( modifier = Modifier diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt index b90e9359..31847105 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryMappers.kt @@ -6,6 +6,7 @@ import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.models.TrackRef +import com.fabledsword.minstrel.models.artistImagePath import com.fabledsword.minstrel.models.wire.AlbumDetailWire import com.fabledsword.minstrel.models.wire.AlbumWire import com.fabledsword.minstrel.models.wire.ArtistDetailWire @@ -66,11 +67,14 @@ fun AlbumDetailWire.toAlbumEntity(): CachedAlbumEntity = // source of truth for cache-first reads; mapping to a domain type here // keeps Room types out of the UI layer. +// An artist whose picture the server fetched shows it; the rest fall back +// to an album cover through [coverAlbumId]. fun CachedArtistEntity.toDomain(coverAlbumId: String = ""): ArtistRef = ArtistRef( id = id, name = name, sortName = sortName, + coverUrl = if (artistThumbPath.isNullOrEmpty()) "" else artistImagePath(id), coverAlbumId = coverAlbumId, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryPlayback.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryPlayback.kt new file mode 100644 index 00000000..54af4893 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryPlayback.kt @@ -0,0 +1,58 @@ +package com.fabledsword.minstrel.library.data + +import com.fabledsword.minstrel.api.ErrorCopy +import com.fabledsword.minstrel.player.PlayerController +import kotlinx.coroutines.CancellationException + +/** + * Fetch an artist's tracks across all their albums and play them shuffled. + * Pressing Play on an artist means "shuffle this artist", not "play album + * by album in tracklist order". Home's artist tiles and the Artist page's + * Play button both start here, so they behave and word their messages + * the same. + * + * An empty artist or a failed fetch reaches [onMessage] for the caller to + * show as a snackbar. + */ +suspend fun shufflePlayArtist( + artistId: String, + repository: LibraryRepository, + player: PlayerController, + onMessage: (String) -> Unit, +) = playOrSay(onMessage, empty = "This artist has no tracks to play.") { + val tracks = repository.fetchArtistTracks(artistId).shuffled() + if (tracks.isNotEmpty()) player.setQueue(tracks, initialIndex = 0, source = "artist:$artistId") + tracks.isNotEmpty() +} + +/** + * Fetch an album and play it from its first track, in tracklist order. + * For an album tile's play button, where the album isn't loaded yet. + */ +suspend fun playAlbumFromStart( + albumId: String, + repository: LibraryRepository, + player: PlayerController, + onMessage: (String) -> Unit, +) = playOrSay(onMessage, empty = "This album has no tracks to play.") { + val tracks = repository.refreshAlbumDetail(albumId).tracks + if (tracks.isNotEmpty()) player.setQueue(tracks, initialIndex = 0, source = "album:$albumId") + tracks.isNotEmpty() +} + +/** Runs [start]; says [empty] when it found nothing to play, and why when it failed. */ +private suspend fun playOrSay( + onMessage: (String) -> Unit, + empty: String, + start: suspend () -> Boolean, +) { + try { + if (!start()) onMessage(empty) + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + onMessage("Couldn't start playback: ${ErrorCopy.fromThrowable(e)}") + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt index ee428610..9978e220 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt @@ -4,7 +4,6 @@ package com.fabledsword.minstrel.library.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -17,7 +16,6 @@ import androidx.compose.animation.Crossfade import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api @@ -34,7 +32,6 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel @@ -51,15 +48,16 @@ import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.shared.formatDuration +import com.fabledsword.minstrel.shared.plural +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon +import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold -import com.fabledsword.minstrel.shared.widgets.ServerImage import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton -import com.fabledsword.minstrel.theme.FabledSwordFlatTokens @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -267,32 +265,17 @@ private fun AlbumHeader( @Composable private fun AlbumCover(album: AlbumRef) { - Box( - modifier = Modifier - .size(120.dp) - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) - .background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - if (album.id.isEmpty()) { - Icon( - imageVector = Lucide.Disc3, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(56.dp), - ) - } else { - ServerImage( - url = album.displayCoverUrl, - contentDescription = album.title, - modifier = Modifier.fillMaxSize(), - ) - } - } + CoverTile( + url = album.displayCoverUrl, + contentDescription = album.title, + size = 120.dp, + background = MaterialTheme.colorScheme.surfaceVariant, + fallback = { CoverFallbackIcon(Lucide.Disc3) }, + ) } private fun trackCountLine(album: AlbumRef): String { - val tracks = if (album.trackCount == 1) "1 track" else "${album.trackCount} tracks" + val tracks = plural(album.trackCount, "track", "tracks") return if (album.year != null) "$tracks · ${album.year}" else tracks } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt index 6a6ad4a9..4673b634 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt @@ -9,6 +9,7 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.library.data.LibraryRepository import com.fabledsword.minstrel.likes.data.LikesRepository +import com.fabledsword.minstrel.likes.data.toggleTrackLike import com.fabledsword.minstrel.models.AlbumDetailRef import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.nav.AlbumDetail @@ -133,9 +134,6 @@ class AlbumDetailViewModel @Inject constructor( } fun toggleLikeTrack(trackId: String) { - val desired = trackId !in likedTrackIds.value - viewModelScope.launch { - likes.toggleLike(LikesRepository.ENTITY_TRACK, trackId, desired) - } + viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt index d4eaf3bb..e7760375 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt @@ -56,6 +56,8 @@ import com.fabledsword.minstrel.models.albumCoverPath import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.shared.formatDuration +import com.fabledsword.minstrel.shared.plural +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow @@ -329,19 +331,12 @@ private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) { url = model, contentDescription = artist.name, modifier = Modifier.fillMaxSize(), - ) { - Icon( - imageVector = Lucide.User, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(40.dp), - ) - } + ) { CoverFallbackIcon(Lucide.User, size = 40.dp) } } } private fun albumCountLine(artist: ArtistRef): String = - if (artist.albumCount == 1) "1 album" else "${artist.albumCount} albums" + plural(artist.albumCount, "album", "albums") @Composable private fun EmptyAlbumsHint() { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt index ee27ba6d..76ec2991 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt @@ -8,6 +8,7 @@ import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.library.data.LibraryRepository +import com.fabledsword.minstrel.library.data.shufflePlayArtist import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.models.ArtistDetailRef import com.fabledsword.minstrel.models.ArtistRef @@ -145,24 +146,7 @@ class ArtistDetailViewModel @Inject constructor( */ fun playArtist() { viewModelScope.launch { - try { - val tracks = repository.fetchArtistTracks(artistId).shuffled() - if (tracks.isEmpty()) { - transientMessagesChannel.trySend("No tracks to play for this artist.") - } else { - player.setQueue( - tracks = tracks, - initialIndex = 0, - source = "artist:$artistId", - ) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - transientMessagesChannel.trySend( - "Couldn't start playback: ${ErrorCopy.fromThrowable(e)}", - ) - } + shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt index 998b05b8..19205a0d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt @@ -14,12 +14,13 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.composables.icons.lucide.Disc3 import com.composables.icons.lucide.Lucide -import androidx.compose.material3.Icon import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.nav.LocalDetailSeedCache +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.PlayCircleButton import androidx.compose.ui.Alignment @@ -34,6 +35,9 @@ import androidx.compose.ui.Alignment * circular play button is overlaid at the bottom-right of the cover. * Only Home wires it currently; Library / Discover / detail surfaces * leave it null. + * + * [artSize] is the cover's side; the tile is 32dp wider for its padding. + * Home shrinks it on shelves that rank below Recently added. */ @Composable fun AlbumCard( @@ -41,11 +45,12 @@ fun AlbumCard( onClick: () -> Unit, modifier: Modifier = Modifier, onPlay: (suspend () -> Unit)? = null, + artSize: Dp = 144.dp, ) { val seedCache = LocalDetailSeedCache.current Surface( modifier = modifier - .width(176.dp) + .width(artSize + 32.dp) .clickable { seedCache.stashAlbum(album) onClick() @@ -56,16 +61,9 @@ fun AlbumCard( CoverTile( url = album.displayCoverUrl, contentDescription = album.title, - size = 144.dp, + size = artSize, background = MaterialTheme.colorScheme.surfaceVariant, - fallback = { - Icon( - imageVector = Lucide.Disc3, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(56.dp), - ) - }, + fallback = { CoverFallbackIcon(Lucide.Disc3) }, overlay = { if (onPlay != null) { PlayCircleButton( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt index e426a5d0..fee0c6af 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt @@ -8,7 +8,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text @@ -18,11 +17,13 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.User import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.nav.LocalDetailSeedCache +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.PlayCircleButton @@ -35,6 +36,9 @@ import com.fabledsword.minstrel.shared.widgets.PlayCircleButton * circular play button is overlaid at the bottom-right of the avatar. * Only Home wires it currently. Padding is 4dp instead of 6dp because * the circular avatar pulls the button visually inward at the corner. + * + * [artSize] is the avatar's diameter; the tile is 16dp wider for its + * padding. Home shrinks it on shelves that rank below the album shelves. */ @Composable fun ArtistCard( @@ -42,11 +46,12 @@ fun ArtistCard( onClick: () -> Unit, modifier: Modifier = Modifier, onPlay: (suspend () -> Unit)? = null, + artSize: Dp = 128.dp, ) { val seedCache = LocalDetailSeedCache.current Surface( modifier = modifier - .width(144.dp) + .width(artSize + 16.dp) .clickable { seedCache.stashArtist(artist) onClick() @@ -60,16 +65,9 @@ fun ArtistCard( CoverTile( url = artist.displayCoverUrl, contentDescription = artist.name, - size = 128.dp, + size = artSize, shape = CircleShape, - fallback = { - Icon( - imageVector = Lucide.User, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(56.dp), - ) - }, + fallback = { CoverFallbackIcon(Lucide.User) }, overlay = { if (onPlay != null) { PlayCircleButton( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt index 05adf9cc..b16ad99a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt @@ -1,5 +1,7 @@ package com.fabledsword.minstrel.likes.data +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.likeToggleKey import com.fabledsword.minstrel.api.endpoints.LikesApi import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao @@ -8,6 +10,7 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.library.data.toDomain import com.fabledsword.minstrel.models.AlbumRef @@ -28,6 +31,7 @@ import retrofit2.create import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.milliseconds +import timber.log.Timber /** * Cache-first reads + offline-first writes for likes. @@ -164,20 +168,25 @@ class LikesRepository @Inject constructor( } else { likeDao.delete(uid, entityType, entityId) } + // An older toggle for this entity is still queued: going live would + // let it replay after this one and undo it. Queue behind it instead; + // the replayer sends only the newest toggle per entity. + if (mutationQueue.pendingLikeStates().containsKey(likeToggleKey(entityType, entityId))) { + mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) + return false + } // 2. Best-effort REST call; 3. enqueue on failure. val kindPath = serverPathFor(entityType) - return try { - if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) - true - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Intentional swallow: the queue replays this later; surfacing - // the network error here would force callers (UI) to handle it - // even though it's already been buffered. - mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) - false - } + // A refusal isn't surfaced: the heart buttons don't wait on this call, + // and the next likes refresh puts the server's answer back on screen. + return sendOrQueue( + send = { if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) }, + queue = { mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) }, + onRefused = { e -> + Timber.i(e, "likes: %s %s refused (%d)", entityType, entityId, e.code()) + WriteOutcome.Refused + }, + ) == WriteOutcome.Synced } /** @@ -194,17 +203,28 @@ class LikesRepository @Inject constructor( * The server lists each kind most recently liked first but sends no * times, so the rows are stamped a millisecond apart in that order; * `likedAt` then sorts the way the server does. + * + * A like or unlike still queued here wins over the server's answer, + * which hasn't seen it yet: taking the server's would undo it on + * screen until the replay landed. */ suspend fun refreshIds() { val uid = currentUserId() val wire = api.ids() + val pending = mutationQueue.pendingLikeStates() val now = Clock.System.now() fun rowsOf(type: String, ids: List) = - ids.mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) } + ids.filter { pending[likeToggleKey(type, it)] != false } + .mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) } val rows = mutableListOf() rows += rowsOf(ENTITY_ARTIST, wire.artistIds) rows += rowsOf(ENTITY_ALBUM, wire.albumIds) rows += rowsOf(ENTITY_TRACK, wire.trackIds) + val listed = rows.mapTo(HashSet()) { likeToggleKey(it.entityType, it.entityId) } + pending.filterValues { it }.keys.filter { it !in listed }.forEach { key -> + val (type, id) = key.split(":", limit = 2) + rows += CachedLikeEntity(uid, type, id, likedAt = now) + } likeDao.replaceAllForUser(uid, rows) } @@ -226,3 +246,11 @@ class LikesRepository @Inject constructor( } } } + +/** + * Flips a track's like, reading whether it is liked now from [likedIds], the + * set the screen is already showing. The heart buttons on track lists (an + * album, a playlist, the player) call this. + */ +suspend fun LikesRepository.toggleTrackLike(trackId: String, likedIds: Set): Boolean = + toggleLike(LikesRepository.ENTITY_TRACK, trackId, desiredState = trackId !in likedIds) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt index 0d19b4ec..4e44a69c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt @@ -1,8 +1,7 @@ package com.fabledsword.minstrel.models /** - * One admin-side user row. The - * admin-scoped variant exposes `autoApproveRequests` and the + * One admin-side user row. The admin-scoped variant carries the * canonical `createdAt` that the user-scoped /me response omits. */ data class AdminUserRef( @@ -10,6 +9,5 @@ data class AdminUserRef( val username: String, val displayName: String? = null, val isAdmin: Boolean = false, - val autoApproveRequests: Boolean = false, val createdAt: String = "", ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt index 432dcff8..d92a62a2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt @@ -9,3 +9,11 @@ package com.fabledsword.minstrel.models */ fun albumCoverPath(albumId: String): String = if (albumId.isEmpty()) "" else "http://placeholder.invalid/api/albums/$albumId/cover" + +/** + * Absolute URL of an artist's image, or "" when [artistId] is blank. The + * server answers with the artist's picture, or else their newest album + * cover, through the same placeholder host as [albumCoverPath]. + */ +fun artistImagePath(artistId: String): String = + if (artistId.isEmpty()) "" else "http://placeholder.invalid/api/artists/$artistId/image" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/Discover.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/Discover.kt deleted file mode 100644 index b320ee11..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/Discover.kt +++ /dev/null @@ -1,157 +0,0 @@ -package com.fabledsword.minstrel.models - -import kotlinx.datetime.Instant -import kotlin.math.roundToInt - -/** - * Kind of request being created. Wire form is the lowercase - * enum name; the helper [wire] keeps that mapping in one place. - */ -enum class RequestKind { - ARTIST, ALBUM, TRACK; - - val wire: String get() = name.lowercase() -} - -/** - * Catalogue search hit — `mbid` is the result's own MBID; `artistMbid` - * and `albumMbid` are filled when the row is an album/track and the - * UI needs the parent IDs to build the request. - * - * `inLibrary` and `requested` together cover the "already-handled" - * cases — UI greys the row + swaps the Request button for a pill. - */ -data class CatalogueResultRef( - val mbid: String, - val name: String, - val secondaryText: String = "", - val imageUrl: String = "", - val artistMbid: String = "", - val albumMbid: String = "", - val inLibrary: Boolean = false, - val requested: Boolean = false, -) - -/** - * Per-seed attribution string for a suggestion — "you liked X" / - * "you played Y". `isLiked = true` discriminates the verb. - */ -data class SeedContributionRef( - val name: String, - val isLiked: Boolean, -) - -/** - * Out-of-library artist suggestion from `GET /api/discover/suggestions`. - * `attributionText` names up to 3 seeds with an Oxford comma so the - * subtitle reads naturally. - */ -data class ArtistSuggestionRef( - val mbid: String, - val name: String, - val imageUrl: String = "", - val attribution: List = emptyList(), - /** Taste-profile tags this candidate matches, strongest first. */ - val matchedTags: List = emptyList(), -) { - val attributionText: String - get() { - if (attribution.isEmpty()) return "" - val phrases = attribution - .take(MAX_ATTRIBUTION_PHRASES) - .map { "${if (it.isLiked) "liked" else "played"} ${it.name}" } - return when (phrases.size) { - 1 -> "Because you ${phrases[0]}." - 2 -> "Because you ${phrases[0]} and ${phrases[1]}." - else -> "Because you ${phrases[0]}, ${phrases[1]}, and ${phrases[2]}." - } - } - - /** - * The subtitle line for the card. - * - * Prefers the taste-tag reason over seed attribution when we have one, - * because it describes the MUSIC ("sounds like what you like") rather than - * the graph ("adjacent to something you played"). Falls back to - * attribution, which is the common case: tag coverage for out-of-library - * artists is partial by nature, so most candidates have no matched tags. - * - * Kept in lockstep with the web client's reasonText() in - * SuggestionFeed.svelte — same wording, same Oxford comma. - */ - val reasonText: String - get() { - val tags = matchedTags.take(MAX_ATTRIBUTION_PHRASES) - return when (tags.size) { - 0 -> attributionText - 1 -> "Matches your taste in ${tags[0]}." - 2 -> "Matches your taste in ${tags[0]} and ${tags[1]}." - else -> "Matches your taste in ${tags[0]}, ${tags[1]}, and ${tags[2]}." - } - } - - companion object { - private const val MAX_ATTRIBUTION_PHRASES = 3 - } -} - -/** - * A suggestion the user parked with "not right now". - * - * Deliberately NOT a dislike: it carries no verdict on the artist, expires on - * its own, and never reaches the taste profile. Anything that treats this as - * negative preference signal is a bug. - * - * [snoozedUntil] is the raw RFC3339 string from the wire. Only the server - * decides whether a snooze is still in effect — every row the client receives - * already is — so this is read purely to phrase "back in about 3 months". - */ -data class SuggestionSnoozeRef( - val mbid: String, - val name: String, - val snoozedUntil: String, -) { - /** - * Relative return phrase for the manage list. Relative rather than a - * calendar date because the exact day a 90-day snooze lapses is noise the - * user never asked for. - * - * [nowMs] is injectable so this is testable without freezing the clock. - * Returns "shortly" for an unparseable or already-past timestamp: the row - * is on screen, so the server still considers it snoozed, and guessing is - * better than rendering an empty line. - */ - fun returnsIn(nowMs: Long = System.currentTimeMillis()): String { - val remainingMs = runCatching { Instant.parse(snoozedUntil).toEpochMilliseconds() } - .getOrNull()?.minus(nowMs) - // Two ways to have nothing to state: an unparseable timestamp, or one - // already lapsed by our clock though the server still returned the row - // (the two disagree). Neither is "today", which would read as a real - // prediction. - if (remainingMs == null || remainingMs <= 0) return "shortly" - val days = (remainingMs.toDouble() / MILLIS_PER_DAY).roundToInt() - return when { - days < 1 -> "today" - days == 1 -> "tomorrow" - days < DAYS_BEFORE_MONTHS -> "in $days days" - else -> { - val months = (days.toDouble() / DAYS_PER_MONTH).roundToInt() - if (months == 1) "in about a month" else "in about $months months" - } - } - } - - private companion object { - const val MILLIS_PER_DAY = 86_400_000.0 - - // Below this, days read more naturally than a rounded month count. - // - // Must be <= DAYS_PER_MONTH, or the singular "in about a month" is - // unreachable: a rounded month count of 1 needs 15..44 days, and any - // threshold above 30 sends all of those down the days branch instead. - // This was 45 and the singular branch was dead code — the unit test - // for it is what surfaced that. - const val DAYS_BEFORE_MONTHS = 30 - const val DAYS_PER_MONTH = 30.0 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt index 17af814a..ab12f7b6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt @@ -21,15 +21,25 @@ data class PlaylistRef( val ownerUsername: String = "", /** All member tracks resident in the audio cache — playable fully offline. */ val fullyCached: Boolean = false, + /** + * Albums whose covers can stand for this playlist, in playlist order. Home + * gives each tile one the tiles before it do not already show. + */ + val coverAlbumIds: List = emptyList(), + /** ISO-8601. A system mix is rebuilt in place, so this is when it was last refreshed. */ + val createdAt: String = "", + /** Place on its Home shelf, 1 first; 0 when the app orders it itself. See playlists/Shelf.kt byShelfRank. */ + val shelfRank: Int = 0, ) { val isSystem: Boolean get() = systemVariant != null /** * Whether the "Regenerate" affordance applies: every system playlist - * EXCEPT songs_like_artist (the server's songs-like family exposes no - * refresh trigger; rebuilds are scheduler-driven). + * EXCEPT the kinds with several playlists per user (songs_like_artist, + * genre_mix), which the server can't address by kind; those rebuild on + * the daily schedule and play by playlist id. */ - val refreshable: Boolean get() = isSystem && systemVariant != "songs_like_artist" + val refreshable: Boolean get() = isSystem && systemVariant !in PER_PLAYLIST_SYSTEM_VARIANTS /** * Can't be relied on while offline — either it needs the live server to @@ -39,6 +49,9 @@ data class PlaylistRef( val unavailableOffline: Boolean get() = refreshable || !fullyCached } +/** System kinds with several playlists per user, played by playlist id. */ +private val PER_PLAYLIST_SYSTEM_VARIANTS = setOf("songs_like_artist", "genre_mix") + /** * One row of a playlist's tracks. * diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/Request.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/Request.kt deleted file mode 100644 index 29b59394..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/Request.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.fabledsword.minstrel.models - -/** - * Status of a request. Stored on the wire as a plain string; - * the typed enum keeps switch / when blocks exhaustive and lets the - * UI map directly to a status pill color without raw-string matches. - */ -enum class RequestStatus { - PENDING, APPROVED, REJECTED, COMPLETED, FAILED, UNKNOWN; - - companion object { - fun fromWire(s: String): RequestStatus = when (s) { - "pending" -> PENDING - "approved" -> APPROVED - "rejected" -> REJECTED - "completed" -> COMPLETED - "failed" -> FAILED - else -> UNKNOWN - } - } - - val wire: String get() = name.lowercase() -} - -/** - * One request the user has submitted, shared between the user-side - * `/api/requests` view and the admin cross-user view since the wire - * shape is identical. - * - * `displayName` picks the right field based on kind: - * - album → albumTitle (fallback artistName) - * - track → trackTitle (fallback artistName) - * - artist → artistName - * - * `listenHrefId` returns the most-specific matched library ID once the - * request completes (track → album → artist) so the "Listen" CTA can - * navigate to the right detail screen. Returns null until the - * server's ingest job populates the matched_* fields. - */ -data class RequestRef( - val id: String, - val userId: String, - val username: String = "", - val status: RequestStatus, - val kind: String, - val artistName: String, - val albumTitle: String? = null, - val trackTitle: String? = null, - val requestedAt: String, - val decidedAt: String? = null, - val notes: String? = null, - val importedAlbumCount: Int = 0, - val importedTrackCount: Int = 0, - val matchedTrackId: String? = null, - val matchedAlbumId: String? = null, - val matchedArtistId: String? = null, -) { - val displayName: String - get() = when (kind) { - "album" -> albumTitle ?: artistName - "track" -> trackTitle ?: artistName - else -> artistName - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt index 18fe9227..dc93d7ac 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt @@ -6,8 +6,8 @@ import kotlinx.serialization.Serializable /** * One admin-side user row. Mirrors `adminUserView` from * `internal/api/admin_users.go`. Distinct from the user-scoped /me - * profile shape because admin endpoints expose `auto_approve_requests` - * and the canonical `created_at`. + * profile shape because admin endpoints expose the canonical + * `created_at`. */ @Serializable data class AdminUserWire( @@ -15,7 +15,6 @@ data class AdminUserWire( val username: String = "", @SerialName("display_name") val displayName: String? = null, @SerialName("is_admin") val isAdmin: Boolean = false, - @SerialName("auto_approve_requests") val autoApproveRequests: Boolean = false, @SerialName("created_at") val createdAt: String = "", ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/DiscoverWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/DiscoverWire.kt deleted file mode 100644 index 60de2119..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/DiscoverWire.kt +++ /dev/null @@ -1,100 +0,0 @@ -package com.fabledsword.minstrel.models.wire - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -/** - * One row of `GET /api/catalogue/search` (the MusicBrainz search). Mirrors - * `web/src/lib/api/types.ts` CatalogueSearchResult. `imageUrl` is the - * server's own art endpoint, relative, so it goes through ServerImage. - * - * `inLibrary` and `requested` let the UI greyout rows the user can't - * act on (already imported / already awaiting review). All defaults - * empty so missing keys don't throw on decode. - */ -@Serializable -data class CatalogueSearchResultWire( - val mbid: String = "", - val name: String = "", - @SerialName("secondary_text") val secondaryText: String = "", - @SerialName("image_url") val imageUrl: String = "", - @SerialName("artist_mbid") val artistMbid: String = "", - @SerialName("album_mbid") val albumMbid: String = "", - @SerialName("in_library") val inLibrary: Boolean = false, - val requested: Boolean = false, -) - -/** - * `GET /api/discover/suggestions` row — an out-of-library artist - * surfaced from ListenBrainz-derived seeds. `imageUrl` may be empty. - */ -@Serializable -data class ArtistSuggestionWire( - val mbid: String = "", - val name: String = "", - @SerialName("image_url") val imageUrl: String = "", - val attribution: List = emptyList(), - /** - * Tags this candidate shares with the user's taste profile, strongest - * first (max 3). Absent for most candidates — tag coverage for - * out-of-library artists is partial by nature — so the default - * empty list is the common case, not an error. - */ - @SerialName("matched_tags") val matchedTags: List = emptyList(), -) - -/** - * Per-seed attribution for an ArtistSuggestion — "because you liked X" - * / "because you played Y". `isLiked = true` means the seed came from - * the user's likes; false means a played-but-not-liked play. - */ -@Serializable -data class SeedContributionWire( - val name: String = "", - @SerialName("is_liked") val isLiked: Boolean = false, -) - -/** - * One row of `GET /api/discover/snoozes` — a suggestion the user parked - * with "not right now". The server only returns rows that are still in - * effect, so the client never compares [snoozedUntil] against the clock to - * decide whether to show it; it reads it only to say when the artist comes - * back. - */ -@Serializable -data class SuggestionSnoozeWire( - val mbid: String = "", - val name: String = "", - @SerialName("snoozed_until") val snoozedUntil: String = "", - @SerialName("created_at") val createdAt: String = "", -) - -/** - * Body for `POST /api/discover/suggestions/{mbid}/snooze`. - * - * [name] is required by the server, not decorative: suggestions are - * out-of-library, so there is no artists row to resolve a display name from - * and the snooze list would have nothing to render. Omitting it is a 400. - * - * No `days` field. The duration is the server's to own (90 days); pinning it - * client-side would freeze the default at whatever this build shipped. - */ -@Serializable -data class SnoozeSuggestionBody( - val name: String, -) - -/** - * Body posted to `POST /api/requests`. Optional fields are emitted only - * when non-null server-side; matching that here keeps the wire identical. - */ -@Serializable -data class CreateRequestBody( - val kind: String, - @SerialName("artist_mbid") val artistMbid: String, - @SerialName("artist_name") val artistName: String, - @SerialName("album_mbid") val albumMbid: String? = null, - @SerialName("album_title") val albumTitle: String? = null, - @SerialName("track_mbid") val trackMbid: String? = null, - @SerialName("track_title") val trackTitle: String? = null, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt index 2ece8341..865a6f8e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt @@ -23,6 +23,16 @@ data class PlaylistWire( @SerialName("owner_username") val ownerUsername: String = "", @SerialName("created_at") val createdAt: String = "", @SerialName("updated_at") val updatedAt: String = "", + /** + * Up to six distinct albums with art, in the order they first appear in + * the playlist. Home's shelves pick each tile's picture from these. + */ + @SerialName("cover_album_ids") val coverAlbumIds: List = emptyList(), + /** + * A system mix's place on its Home shelf, 1 first: genre mixes are + * numbered by how much the listener plays each genre. 0 when unranked. + */ + @SerialName("shelf_rank") val shelfRank: Int = 0, ) /** @@ -79,5 +89,8 @@ data class PlaylistDetailWire( @SerialName("track_count") val trackCount: Int = 0, @SerialName("cover_url") val coverUrl: String = "", @SerialName("owner_username") val ownerUsername: String = "", + @SerialName("created_at") val createdAt: String = "", + @SerialName("cover_album_ids") val coverAlbumIds: List = emptyList(), + @SerialName("shelf_rank") val shelfRank: Int = 0, val tracks: List = emptyList(), ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/RequestWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/RequestWire.kt deleted file mode 100644 index d78cd555..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/RequestWire.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.fabledsword.minstrel.models.wire - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -/** - * Wire shape of `requestView` from `internal/api/requests.go` — the - * row returned by both `GET /api/requests` (caller's own requests) and - * `GET /api/admin/requests` (cross-user admin view). - * - * Status values: `pending` / `approved` / `rejected` / `completed` / - * `failed`. Kind values: `artist` / `album` / `track`. - * - * `matched_*_id` are set after a completed request ingests into the - * local library; the user-side "Listen" affordance picks the most - * specific one (track → album → artist). - */ -@Serializable -data class RequestWire( - val id: String, - @SerialName("user_id") val userId: String = "", - // The requester's username. Only `GET /api/admin/requests` sends it. - val username: String = "", - val status: String = "pending", - val kind: String = "artist", - @SerialName("artist_name") val artistName: String = "", - @SerialName("album_title") val albumTitle: String? = null, - @SerialName("track_title") val trackTitle: String? = null, - @SerialName("requested_at") val requestedAt: String = "", - @SerialName("decided_at") val decidedAt: String? = null, - val notes: String? = null, - @SerialName("imported_album_count") val importedAlbumCount: Int = 0, - @SerialName("imported_track_count") val importedTrackCount: Int = 0, - @SerialName("matched_track_id") val matchedTrackId: String? = null, - @SerialName("matched_album_id") val matchedAlbumId: String? = null, - @SerialName("matched_artist_id") val matchedArtistId: String? = null, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt b/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt index 64decef0..0a5ec914 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt @@ -15,12 +15,10 @@ import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.fabledsword.minstrel.admin.ui.AdminLandingScreen import com.fabledsword.minstrel.admin.ui.AdminQuarantineScreen -import com.fabledsword.minstrel.admin.ui.AdminRequestsScreen import com.fabledsword.minstrel.admin.ui.AdminTagSourcesScreen import com.fabledsword.minstrel.admin.ui.AdminUsersScreen import com.fabledsword.minstrel.auth.ui.LoginScreen import com.fabledsword.minstrel.auth.ui.ServerUrlScreen -import com.fabledsword.minstrel.discover.ui.DiscoverScreen import com.fabledsword.minstrel.home.ui.HomeScreen import com.fabledsword.minstrel.library.ui.AlbumDetailScreen import com.fabledsword.minstrel.library.ui.ArtistDetailScreen @@ -31,7 +29,6 @@ import com.fabledsword.minstrel.player.ui.NowPlayingScreen import com.fabledsword.minstrel.player.ui.QueueScreen import com.fabledsword.minstrel.playlists.ui.PlaylistDetailScreen import com.fabledsword.minstrel.playlists.ui.PlaylistsListScreen -import com.fabledsword.minstrel.requests.ui.RequestsScreen import com.fabledsword.minstrel.search.ui.SearchScreen import com.fabledsword.minstrel.settings.ui.SettingsScreen import com.fabledsword.minstrel.shared.widgets.ShellScaffold @@ -92,13 +89,6 @@ private fun NavGraphBuilder.inShellTopLevel( } } } - composable { - WithAnimatedScope { - ShellScaffold(onExpandPlayer = expandPlayer) { - DiscoverScreen(navController = navController) - } - } - } composable { WithAnimatedScope { ShellScaffold(onExpandPlayer = expandPlayer) { @@ -120,13 +110,6 @@ private fun NavGraphBuilder.inShellTopLevel( } } } - composable { - WithAnimatedScope { - ShellScaffold(onExpandPlayer = expandPlayer) { - RequestsScreen(navController = navController) - } - } - } } /** @@ -172,13 +155,6 @@ private fun NavGraphBuilder.inShellDetail( } } } - composable { - WithAnimatedScope { - ShellScaffold(onExpandPlayer = expandPlayer) { - AdminRequestsScreen(navController = navController) - } - } - } composable { WithAnimatedScope { ShellScaffold(onExpandPlayer = expandPlayer) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt b/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt index 830a09f3..53d87db6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt @@ -8,11 +8,9 @@ import kotlinx.serialization.Serializable @Serializable data object Home @Serializable data object Library @Serializable data object Search -@Serializable data object Discover @Serializable data object Playlists @Serializable data object Settings @Serializable data object Admin -@Serializable data object Requests @Serializable data object Notifications @Serializable data object NotificationSettings @@ -21,7 +19,6 @@ import kotlinx.serialization.Serializable @Serializable data class AlbumDetail(val id: String) @Serializable data class ArtistDetail(val id: String) @Serializable data class PlaylistDetail(val id: String) -@Serializable data object AdminRequests @Serializable data object AdminQuarantine @Serializable data object AdminUsers @Serializable data object AdminTagSources diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt index 3aa3bd3b..dfac124c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt @@ -9,8 +9,9 @@ import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEnti import com.fabledsword.minstrel.cache.mutations.MutationKind import com.fabledsword.minstrel.cache.mutations.MutationQueue import com.fabledsword.minstrel.cache.mutations.NotificationSettingPayload +import com.fabledsword.minstrel.cache.mutations.WriteOutcome import com.fabledsword.minstrel.cache.mutations.notificationSettingChange -import kotlinx.coroutines.CancellationException +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.serialization.json.Json @@ -61,16 +62,14 @@ class NotificationSettingsRepository @Inject constructor( return } val change = notificationSettingChange(payload) ?: return - try { - save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "notification settings: PUT failed; queued") - mutationQueue.enqueueNotificationSettingSet(payload) - } + sendOrQueue( + send = { save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) }, + queue = { mutationQueue.enqueueNotificationSettingSet(payload) }, + onRefused = { e -> + Timber.i(e, "notification settings: PUT refused (%d)", e.code()) + WriteOutcome.Refused + }, + ) } private suspend fun current(): NotificationSettingsWire? = dao.getSettings()?.let(::decode) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt index f6910934..f8e76e8b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt @@ -6,7 +6,8 @@ import com.fabledsword.minstrel.api.endpoints.ReadAllBody import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue -import kotlinx.coroutines.CancellationException +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.datetime.Clock @@ -52,24 +53,12 @@ class NotificationsRepository @Inject constructor( suspend fun markRead(id: String) { dao.markRead(id, Clock.System.now()) - try { - api.markRead(id) - } catch (e: CancellationException) { - throw e - } catch (e: HttpException) { - // A 4xx (404: trimmed or gone server-side) leaves nothing to mark; - // a 5xx is the server's trouble, so the read waits in the queue. - if (e.code() >= HTTP_SERVER_ERROR) { - mutationQueue.enqueueNotificationRead(id) - } else { - Timber.i(e, "notifications: mark read refused (%d)", e.code()) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "notifications: mark read failed; queued") - mutationQueue.enqueueNotificationRead(id) - } + // A refusal (404: trimmed or gone server-side) leaves nothing to mark. + sendOrQueue( + send = { api.markRead(id) }, + queue = { mutationQueue.enqueueNotificationRead(id) }, + onRefused = { e -> refused("mark read", e) }, + ) } /** @@ -80,16 +69,16 @@ class NotificationsRepository @Inject constructor( suspend fun markAllRead() { val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString() dao.markAllRead(Clock.System.now()) - try { - api.readAll(ReadAllBody(upTo = upTo)) - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "notifications: mark all read failed; queued") - mutationQueue.enqueueNotificationsReadAll(upTo) - } + sendOrQueue( + send = { api.readAll(ReadAllBody(upTo = upTo)) }, + queue = { mutationQueue.enqueueNotificationsReadAll(upTo) }, + onRefused = { e -> refused("mark all read", e) }, + ) + } + + private fun refused(what: String, e: HttpException): WriteOutcome { + Timber.i(e, "notifications: %s refused (%d)", what, e.code()) + return WriteOutcome.Refused } /** The page the device holds, newest first. */ @@ -103,8 +92,6 @@ class NotificationsRepository @Inject constructor( companion object { /** The newest page the device keeps; older notices stay on the server. */ const val PAGE_SIZE = 50 - - private const val HTTP_SERVER_ERROR = 500 } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt index 938350c9..df642dd4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt @@ -76,7 +76,7 @@ internal fun announcementFor(fresh: List): Announcemen channel = if (fresh.all { shadeChannelFor(it.kind) == ShadeChannel.LIBRARY_HEALTH }) { ShadeChannel.LIBRARY_HEALTH } else { - ShadeChannel.YOUR_REQUESTS + ShadeChannel.NEW_MUSIC }, lines = fresh.sortedByDescending { it.createdAt }.take(PILE_LINES).map { it.title }, ) @@ -94,15 +94,18 @@ internal fun phoneOnFor(settings: NotificationSettingsWire?): (String) -> Boolea * user's system-level choice for it. */ internal enum class ShadeChannel(val id: String, val title: String, val description: String) { - YOUR_REQUESTS("your_requests", "Your requests", "Approved, declined, and new music arriving"), - LIBRARY_HEALTH("library_health", "Library health", "For admins: requests to review and library problems"), + NEW_MUSIC("new_music", "New music", "Albums arriving in the library"), + LIBRARY_HEALTH("library_health", "Library health", "For admins: flagged tracks and library problems"), } -private val requesterKinds = setOf("request_approved", "request_rejected", "request_completed") +/** Channel ids the app does not post to; deleted at startup so system settings lists only live ones. */ +internal val retiredShadeChannelIds = listOf("your_requests") + +private val listenerKinds = setOf("new_music") /** Everything a listener can receive is theirs; the rest is admin work. */ internal fun shadeChannelFor(kind: String): ShadeChannel = - if (kind in requesterKinds) ShadeChannel.YOUR_REQUESTS else ShadeChannel.LIBRARY_HEALTH + if (kind in listenerKinds) ShadeChannel.NEW_MUSIC else ShadeChannel.LIBRARY_HEALTH /** The delivery service runs exactly while signed in with background delivery on. */ internal fun deliveryWanted(signedIn: Boolean, enabled: Boolean): Boolean = signedIn && enabled diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt index 983f20fa..73829ad0 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt @@ -79,6 +79,7 @@ class NotificationPoster @Inject constructor( private fun ensureChannels() { val manager = context.getSystemService(NotificationManager::class.java) ?: return + retiredShadeChannelIds.forEach { manager.deleteNotificationChannel(it) } ShadeChannel.entries.forEach { c -> manager.createNotificationChannel( NotificationChannel(c.id, c.title, NotificationManager.IMPORTANCE_DEFAULT) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt index bac2fce0..0d163cf8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt @@ -2,14 +2,14 @@ package com.fabledsword.minstrel.notifications.ui import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.AdminQuarantine -import com.fabledsword.minstrel.nav.AdminRequests import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.Requests +import com.fabledsword.minstrel.nav.Home /** * The app screen for a notice's link. The server writes web paths, the same - * for every client; this maps them onto the app's routes. The library's + * for every client; this maps them onto the app's routes. "/" is Home, + * where several new albums at once are found under Recently added. The library's * health pages sit under Collection on the web: Reports opens the * app's report screen, and the ones the app has no screen for (duplicates, * suspect sources, missing files) open the Admin landing, as do other Admin @@ -20,10 +20,10 @@ private val ADMIN_COLLECTION_PAGES = setOf("duplicates", "suspect-sources", "mis internal fun routeForLink(link: String): Any? { val parts = link.substringBefore('?').trim('/').split('/').filter { it.isNotEmpty() } return when { + link.isBlank() -> null + parts.isEmpty() -> Home parts.size == 2 && parts[0] == "albums" -> AlbumDetail(parts[1]) parts.size == 2 && parts[0] == "artists" -> ArtistDetail(parts[1]) - parts == listOf("requests") -> Requests - parts == listOf("admin", "requests") -> AdminRequests parts == listOf("collection", "reports") -> AdminQuarantine parts.firstOrNull() == "collection" && parts.getOrNull(1) in ADMIN_COLLECTION_PAGES -> Admin parts.firstOrNull() == "admin" -> Admin diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt index 70d74219..08505b9c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt @@ -9,23 +9,17 @@ import android.os.Build import android.provider.Settings import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Checkbox -import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -35,7 +29,6 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign @@ -45,8 +38,6 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController -import com.composables.icons.lucide.ChevronRight -import com.composables.icons.lucide.Lucide import com.fabledsword.minstrel.api.endpoints.NotificationKindSettingWire import com.fabledsword.minstrel.api.endpoints.NotificationSettingsWire import com.fabledsword.minstrel.nav.NotificationSettings @@ -54,13 +45,19 @@ import com.fabledsword.minstrel.notifications.data.NotificationChannel import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets +import com.fabledsword.minstrel.theme.Muted +import com.fabledsword.minstrel.theme.RowChevron +import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SectionEdge +import com.fabledsword.minstrel.theme.SectionGap +import com.fabledsword.minstrel.theme.SettingRow +import com.fabledsword.minstrel.theme.SwitchRow -private val CELL_WIDTH = 56.dp +private val CELL_WIDTH = 48.dp /** - * Per-user notification settings: a row per kind with a box for each - * channel. Rows read as a menu; anything that needs explaining - * is one short line. + * Per-user notification settings: what this device does, then a row per + * kind with a box for each channel. */ @Composable fun NotificationSettingsScreen( @@ -109,38 +106,36 @@ private fun SettingsBody( modifier = modifier .fillMaxSize() .verticalScroll(rememberScrollState()) - .padding(vertical = 8.dp), + .padding(horizontal = SectionEdge, vertical = SectionEdge), + verticalArrangement = Arrangement.spacedBy(SectionGap), ) { - deviceRows() - HeaderRow() - settings.kinds.filter { !it.adminOnly }.forEach { KindRow(it, settings.emailAvailable, onSet) } + Section("This device") { deviceRows() } + Section("New music", trailing = { ChannelHeaders() }) { + settings.kinds.filter { !it.adminOnly }.forEach { KindRow(it, settings.emailAvailable, onSet) } + if (!settings.emailAvailable) { + Muted(emailUnavailableLine(settings.emailUnavailableReason, isAdmin)) + } + } val adminKinds = settings.kinds.filter { it.adminOnly } if (adminKinds.isNotEmpty()) { - SectionLabel("Library health") - adminKinds.forEach { KindRow(it, settings.emailAvailable, onSet) } - } - if (!settings.emailAvailable) { - Muted(emailUnavailableLine(settings.emailUnavailableReason, isAdmin)) + Section("Library health", trailing = { ChannelHeaders() }) { + adminKinds.forEach { KindRow(it, settings.emailAvailable, onSet) } + } } } } +/** The channel names over the boxes, in the section's title line. */ @Composable -private fun HeaderRow() { - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Box(Modifier.weight(1f)) - NotificationChannel.entries.forEach { c -> - Text( - text = channelLabel(c), - modifier = Modifier.width(CELL_WIDTH), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } +private fun ChannelHeaders() { + NotificationChannel.entries.forEach { c -> + Text( + text = channelLabel(c), + modifier = Modifier.width(CELL_WIDTH), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) } } @@ -151,11 +146,7 @@ private fun KindRow( onSet: (String, NotificationChannel, Boolean) -> Unit, ) { val label = kindLabel(row.kind) - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(label, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) + SettingRow(title = label) { NotificationChannel.entries.forEach { c -> val enabled = channelEnabled(row, c, emailAvailable) Box(Modifier.width(CELL_WIDTH), contentAlignment = Alignment.Center) { @@ -204,60 +195,24 @@ private fun DeviceRows(backgroundDelivery: Boolean, onBackgroundDelivery: (Boole @Composable private fun BackgroundDeliveryRow(checked: Boolean, onChange: (Boolean) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .toggleable(value = checked, role = Role.Switch, onValueChange = onChange) - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Column(Modifier.weight(1f)) { - Text("Notifications when the app is closed", style = MaterialTheme.typography.bodyLarge) - // The ongoing notice is the price of not using Google's push; - // said plainly rather than left to be discovered. - Muted("Keeps a quiet notice in the shade, in place of Google's push", padded = false) - } - Switch(checked = checked, onCheckedChange = null) - } + // The ongoing notice is the price of not using Google's push; said + // plainly rather than left to be discovered. + SwitchRow( + title = "Notifications when the app is closed", + summary = "Keeps a quiet notice in the shade, in place of Google's push", + checked = checked, + onCheckedChange = onChange, + ) } @Composable private fun PhoneBlockedRow(onClick: () -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Column(Modifier.weight(1f)) { - Text("Phone alerts are off", style = MaterialTheme.typography.bodyLarge) - Muted("Allow notifications for Minstrel in system settings", padded = false) - } - Icon(Lucide.ChevronRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) - } -} - -@Composable -private fun SectionLabel(text: String) { - Text( - text = text, - modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp), - style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) -} - -@Composable -private fun Muted(text: String, padded: Boolean = true) { - Text( - text = text, - modifier = if (padded) Modifier.padding(horizontal = 16.dp, vertical = 12.dp) else Modifier, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + SettingRow( + title = "Phone alerts are off", + summary = "Allow notifications for Minstrel in system settings", + tone = MaterialTheme.colorScheme.error, + onClick = onClick, + ) { RowChevron() } } private fun openAppNotificationSettings(context: Context) { @@ -293,10 +248,7 @@ internal fun channelLabel(c: NotificationChannel): String = when (c) { /** Short row labels, the same as the web's. Unknown kinds show their key. */ internal fun kindLabel(kind: String): String = when (kind) { - "request_approved" -> "Request approved" - "request_rejected" -> "Request declined" - "request_completed" -> "New music arrived" - "request_pending" -> "Requests to review" + "new_music" -> "New music arrived" "quarantine_flagged" -> "Tracks flagged" "scan_failed" -> "Library scan failed" "tracks_missing" -> "Tracks gone missing" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt index c3add71a..82e34875 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt @@ -80,7 +80,7 @@ fun NotificationsScreen( list == null -> LoadingCentered() list.isEmpty() -> EmptyState( title = "Nothing waiting for you", - body = "Requests, new music and anything needing a look will gather here.", + body = "Library problems and anything needing a look will gather here.", icon = Lucide.Bell, ) else -> LazyColumn(modifier = Modifier.fillMaxSize()) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt index 7e6a4671..c4a8b56a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt @@ -28,7 +28,7 @@ import javax.inject.Singleton * scrobbles would not fire, and system-playlist rotation would not * advance. * - * State machine over (current track id, playing) observed against + * State machine over (current listen, playing) observed against * [PlayerController.uiState]. The client always calls `playEnded` * with the actual position played to; the server applies its * configurable skip rule (`skip_max_completion_ratio` AND @@ -81,55 +81,67 @@ class PlayEventsReporter @Inject constructor( // orphan on the next play_started instead. private var startInFlight: Boolean = false + // The listen the tracked play belongs to (PlayerUiState.listenSeq), and + // the one last seen. A repeat keeps the track id but moves the listen, + // so a song on repeat is a play per time through. + private var curListenSeq: Long = -1 private var prevTrackId: String? = null + private var prevListenSeq: Long = -1 + + // Identifies the tracked play to its own play_started call. A reply that + // lands after the play it was for has closed must neither adopt its id + // nor clear the in-flight flag the NEXT play's start has set: clearing it + // would make a quick skip of that next play record it offline as well as + // live. + private var curPlayToken: Long = 0 init { ProcessLifecycleOwner.get().lifecycle.addObserver(this) scope.launch { - playerController.uiState.collect { state -> - evaluate( - trackId = state.currentTrack?.id, - playing = state.isPlaying, - positionMs = state.positionMs, - durationMs = state.durationMs, - source = state.currentSource, - ) - } + playerController.uiState.collect { state -> evaluate(state) } } } - private fun evaluate( - trackId: String?, - playing: Boolean, - positionMs: Long, - durationMs: Long, - source: String?, - ) { - // Track-change → close the prior tracked play. - if (trackId != prevTrackId && curTrackId != null) { + private fun evaluate(state: PlayerUiState) { + val trackId = state.currentTrack?.id + val listenSeq = state.listenSeq + val playing = state.isPlaying + val durationMs = state.durationMs + val listenChanged = trackId != prevTrackId || listenSeq != prevListenSeq + // Listen change (a new track, or the same one again) → close the + // prior tracked play. + if (listenChanged && curTrackId != null) { closeCurrent() } - // Entered playing for a new track → begin tracking it. - if (trackId != null && playing && curTrackId != trackId) { - beginTrack(trackId = trackId, source = source, durationMs = durationMs) + // Entered playing for a new listen → begin tracking it. + val tracked = curTrackId == trackId && curListenSeq == listenSeq + if (trackId != null && playing && !tracked) { + beginTrack( + trackId = trackId, + listenSeq = listenSeq, + source = state.currentSource, + durationMs = durationMs, + ) } - // Advance the tracked play's progress. The gate `trackId == - // curTrackId` keeps a finishing track's last-known position - // intact across the moment the listener fires for a track - // change (where currentTrack is briefly the new one). - if (curTrackId != null && trackId == curTrackId) { - curLastPositionMs = positionMs + // Advance the tracked play's progress. The gate on the tracked + // listen keeps a finishing track's last-known position intact + // across the moment the listener fires for a track change or a + // repeat (where the position has already gone back to 0). + if (curTrackId != null && trackId == curTrackId && listenSeq == curListenSeq) { + curLastPositionMs = state.positionMs if (durationMs > 0) curDurationMs = durationMs curPlaying = playing } prevTrackId = trackId + prevListenSeq = listenSeq } - private fun beginTrack(trackId: String, source: String?, durationMs: Long) { + private fun beginTrack(trackId: String, listenSeq: Long, source: String?, durationMs: Long) { curTrackId = trackId + curListenSeq = listenSeq curStartedAt = Clock.System.now() curSource = source curLastPositionMs = 0 @@ -137,10 +149,11 @@ class PlayEventsReporter @Inject constructor( curPlaying = true openPlayEventId = null startInFlight = true - startLive(trackId = trackId, source = source) + curPlayToken++ + startLive(trackId = trackId, source = source, token = curPlayToken) } - private fun startLive(trackId: String, source: String?) { + private fun startLive(trackId: String, source: String?, token: Long) { val cid = resolveClientId() if (cid == null) { startInFlight = false @@ -156,7 +169,7 @@ class PlayEventsReporter @Inject constructor( deviceClass = DEVICE_CLASS, ), ) - if (curTrackId == trackId) { + if (curPlayToken == token) { openPlayEventId = response.playEventId } } catch ( @@ -165,7 +178,7 @@ class PlayEventsReporter @Inject constructor( // Offline / flaky — openPlayEventId stays null; close // path will enqueue the completed play for replay. } finally { - startInFlight = false + if (curPlayToken == token) startInFlight = false } } } @@ -223,6 +236,7 @@ class PlayEventsReporter @Inject constructor( private fun resetCurrent() { curTrackId = null + curListenSeq = -1 curStartedAt = null curSource = null curLastPositionMs = 0 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt index 4ceb665f..3708cbc6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt @@ -121,6 +121,14 @@ class PlayerController @Inject constructor( */ private var lastEvaluatedItemIndex: Int = -1 + /** + * Listens begun, published as [PlayerUiState.listenSeq]. Bumped on every + * onMediaItemTransition: Media3 reports a repeat of the same item as a + * transition too (MEDIA_ITEM_TRANSITION_REASON_REPEAT), though the + * current track id doesn't change. + */ + private var listenSeq: Long = 0 + /** * Self-heal budget — re-pulls of a stale refreshable queue since * the last successful play. Capped so a still-broken refresh can't loop; @@ -197,8 +205,17 @@ class PlayerController @Inject constructor( fun skipToNext() { mediaController?.let { runOnControllerThread(it) { it.seekToNextMediaItem() } } } + /** + * Previous, as the web player does it: past the first few seconds of a + * song it starts the song over, otherwise it goes back a song. Decided + * here rather than by Media3's seekToPrevious so a cast to a Sonos speaker + * behaves the same (the restart is a seek to 0 on the speaker). + */ fun skipToPrevious() { - mediaController?.let { runOnControllerThread(it) { it.seekToPreviousMediaItem() } } + val restart = uiStateInternal.value.previousRestarts + mediaController?.let { c -> + runOnControllerThread(c) { if (restart) c.seekTo(0L) else c.seekToPreviousMediaItem() } + } } /** Flip shuffle on/off. Media3 emits onEvents → uiState reflects. */ @@ -349,11 +366,13 @@ class PlayerController @Inject constructor( controller.removeMediaItem(index) } - /** Empty the queue and stop playback. */ + /** Empty the queue and stop playback. Safe to call from any thread. */ fun clearQueue() { val controller = mediaController ?: return - queueRefs = emptyList() - controller.clearMediaItems() + runOnControllerThread(controller) { + queueRefs = emptyList() + controller.clearMediaItems() + } } /** @@ -386,6 +405,22 @@ class PlayerController @Inject constructor( } } + /** + * Plays radio seeded from [trackId] now, replacing the queue: the seed + * plays first, then songs like it. Tapping a search result uses this. + * The track menu's Start radio ([startRadio]) differs on purpose: it + * keeps the current song playing and queues the radio after it. + * + * Returns false on an empty server response; throws on transport or + * non-2xx for the caller to handle. + */ + suspend fun playRadio(trackId: String): Boolean { + val tracks = radio.seed(trackId) + if (tracks.isEmpty()) return false + setQueue(tracks, initialIndex = 0, source = "radio:$trackId") + return true + } + /** * Mid-queue radio insert. The current track keeps playing; every * upcoming item is removed; the radio results are appended after. @@ -567,6 +602,8 @@ class PlayerController @Inject constructor( mediaItem: androidx.media3.common.MediaItem?, reason: Int, ) { + // A new listen begins, the same item on repeat included. + listenSeq++ // Reset the per-item evaluation guard so the new // item's STATE_READY transition gets a fresh check. lastEvaluatedItemIndex = -1 @@ -634,6 +671,9 @@ class PlayerController @Inject constructor( else -> RepeatMode.OFF }, isUpnpLoading = isUpnpLoading, + listenSeq = listenSeq, + hasPrevious = player.hasPreviousMediaItem(), + hasNext = player.hasNextMediaItem(), ) } }, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt index ae7518cb..db0fe1ed 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt @@ -29,4 +29,37 @@ data class PlayerUiState( val repeatMode: RepeatMode = RepeatMode.OFF, /** True while the UPnP initial-batch load is in progress (target set, active not yet wired). */ val isUpnpLoading: Boolean = false, -) + /** + * Counts listens begun: moves on every media-item transition, a repeat + * included. The play reporter keys a play on (track, listen), so a song + * on repeat-one, or the same song twice in a row, is a play per listen. + */ + val listenSeq: Long = 0, + /** + * Whether Previous and Next lead anywhere, as Media3 reckons it from the + * queue, shuffle and repeat. At the ends of a queue with repeat off or + * repeat one they don't, and the buttons grey out rather than do nothing. + */ + val hasPrevious: Boolean = false, + val hasNext: Boolean = false, +) { + /** Whether Previous starts this song over rather than going back one. */ + val previousRestarts: Boolean get() = previousRestarts(positionMs, hasPrevious) + + /** + * Previous always has something to do except in the opening seconds of a + * queue's first song: past [RESTART_THRESHOLD_MS] it starts the song + * over, as the web player's does. + */ + val canSkipPrevious: Boolean get() = currentTrack != null && (hasPrevious || positionMs >= RESTART_THRESHOLD_MS) +} + +/** + * How far into a song Previous starts it over instead of going back a song: + * 3 seconds, the web player's RESTART_THRESHOLD_SEC and Media3's default. + */ +const val RESTART_THRESHOLD_MS = 3_000L + +/** Previous restarts the song once it is [RESTART_THRESHOLD_MS] in, or when nothing comes before it. */ +fun previousRestarts(positionMs: Long, hasPrevious: Boolean): Boolean = + positionMs >= RESTART_THRESHOLD_MS || !hasPrevious diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt index 2ede909a..64d45fa6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt @@ -265,7 +265,7 @@ class UpnpDiscoveryController @Inject constructor( } private companion object { - // " (192.168.0.77)" trailing host suffix some generic UPnP + // " (198.51.100.77)" trailing host suffix some generic UPnP // devices append. Anchored to end-of-string so it never eats // a legitimate parenthetical inside a name. val IP_SUFFIX_REGEX = Regex("""\s*\(\d+\.\d+\.\d+\.\d+\)$""") diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt index 529efea7..8b8095cb 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt @@ -1,7 +1,6 @@ package com.fabledsword.minstrel.player.ui import androidx.compose.animation.Crossfade -import androidx.compose.animation.ExperimentalSharedTransitionApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation @@ -17,9 +16,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.material3.Surface @@ -36,14 +32,10 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Music -import com.composables.icons.lucide.Pause -import com.composables.icons.lucide.Play import com.composables.icons.lucide.SkipBack import com.composables.icons.lucide.SkipForward import com.fabledsword.minstrel.models.TrackRef -import com.fabledsword.minstrel.nav.HERO_KEY_NOW_PLAYING_COVER -import com.fabledsword.minstrel.nav.LocalAnimatedContentScope -import com.fabledsword.minstrel.nav.LocalSharedTransitionScope +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.ServerImage import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsViewModel @@ -59,25 +51,10 @@ private const val SCRUBBER_ROW_HEIGHT_DP = 4 // same across screens. private const val SWIPE_UP_VELOCITY_DP = 200 -@OptIn(ExperimentalSharedTransitionApi::class) @Composable private fun MiniCover(coverUrl: String, contentDescription: String) { - val sharedScope = LocalSharedTransitionScope.current - val animatedScope = LocalAnimatedContentScope.current - val heroModifier = if (sharedScope != null && animatedScope != null) { - with(sharedScope) { - Modifier.sharedElement( - sharedContentState = rememberSharedContentState( - key = HERO_KEY_NOW_PLAYING_COVER, - ), - animatedVisibilityScope = animatedScope, - ) - } - } else { - Modifier - } Box( - modifier = heroModifier + modifier = nowPlayingCoverHero() .size(COVER_SIZE_DP.dp) .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) .background(MaterialTheme.colorScheme.surfaceVariant), @@ -90,13 +67,7 @@ private fun MiniCover(coverUrl: String, contentDescription: String) { url = url, contentDescription = contentDescription, modifier = Modifier.size(COVER_SIZE_DP.dp), - ) { - Icon( - imageVector = Lucide.Music, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + ) { CoverFallbackIcon(Lucide.Music, size = 24.dp) } } } } @@ -176,6 +147,8 @@ fun MiniPlayer( isPlaying = state.isPlaying, isUpnpLoading = state.isUpnpLoading, isLiked = isLiked, + hasPrevious = state.canSkipPrevious, + hasNext = state.hasNext, onExpandClick = onExpandClick, onPlayPause = { if (state.isPlaying) viewModel.pause() else viewModel.play() }, onPrev = viewModel::skipToPrevious, @@ -218,6 +191,8 @@ private fun MiniRow( isPlaying: Boolean, isUpnpLoading: Boolean, isLiked: Boolean, + hasPrevious: Boolean, + hasNext: Boolean, onExpandClick: () -> Unit, onPlayPause: () -> Unit, onPrev: () -> Unit, @@ -260,51 +235,34 @@ private fun MiniRow( } } LikeButton(liked = isLiked, onToggle = onToggleLike) - TransportButton(icon = Lucide.SkipBack, description = "Previous", onClick = onPrev) - MiniPlayPauseButton( + val tint = MaterialTheme.colorScheme.onSurface + SkipButton( + icon = Lucide.SkipBack, + description = "Previous", + enabled = hasPrevious, + tint = tint, + iconSize = MINI_TRANSPORT_ICON_DP.dp, + onClick = onPrev, + ) + PlayPauseButton( isPlaying = isPlaying, isUpnpLoading = isUpnpLoading, + tint = tint, + iconSize = MINI_TRANSPORT_ICON_DP.dp, + spinnerStroke = 2.dp, onClick = onPlayPause, ) - TransportButton(icon = Lucide.SkipForward, description = "Next", onClick = onNext) - } -} - -@Composable -private fun MiniPlayPauseButton( - isPlaying: Boolean, - isUpnpLoading: Boolean, - onClick: () -> Unit, -) { - IconButton(onClick = onClick, enabled = !isUpnpLoading) { - if (isUpnpLoading) { - CircularProgressIndicator( - modifier = Modifier.size(MINI_PLAY_PAUSE_SPINNER_DP.dp), - strokeWidth = 2.dp, - ) - } else { - Icon( - imageVector = if (isPlaying) Lucide.Pause else Lucide.Play, - contentDescription = if (isPlaying) "Pause" else "Play", - tint = MaterialTheme.colorScheme.onSurface, - ) - } - } -} - -private const val MINI_PLAY_PAUSE_SPINNER_DP = 24 - -@Composable -private fun TransportButton( - icon: androidx.compose.ui.graphics.vector.ImageVector, - description: String, - onClick: () -> Unit, -) { - IconButton(onClick = onClick) { - Icon( - imageVector = icon, - contentDescription = description, - tint = MaterialTheme.colorScheme.onSurface, + SkipButton( + icon = Lucide.SkipForward, + description = "Next", + enabled = hasNext, + tint = tint, + iconSize = MINI_TRANSPORT_ICON_DP.dp, + onClick = onNext, ) } } + +/** The mini player's transport icons, at Material's standard icon size. */ +private const val MINI_TRANSPORT_ICON_DP = 24 + diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingCoverHero.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingCoverHero.kt new file mode 100644 index 00000000..80ab0723 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingCoverHero.kt @@ -0,0 +1,28 @@ +package com.fabledsword.minstrel.player.ui + +import androidx.compose.animation.ExperimentalSharedTransitionApi +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import com.fabledsword.minstrel.nav.HERO_KEY_NOW_PLAYING_COVER +import com.fabledsword.minstrel.nav.LocalAnimatedContentScope +import com.fabledsword.minstrel.nav.LocalSharedTransitionScope + +/** + * The shared-element modifier that carries the playing song's cover + * between the mini player and Now Playing, so opening Now Playing grows + * the small cover into the large one. Outside a shared transition (a + * preview, a test) it is a plain Modifier. + */ +@OptIn(ExperimentalSharedTransitionApi::class) +@Composable +internal fun nowPlayingCoverHero(): Modifier { + val sharedScope = LocalSharedTransitionScope.current + val animatedScope = LocalAnimatedContentScope.current + if (sharedScope == null || animatedScope == null) return Modifier + return with(sharedScope) { + Modifier.sharedElement( + sharedContentState = rememberSharedContentState(key = HERO_KEY_NOW_PLAYING_COVER), + animatedVisibilityScope = animatedScope, + ) + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt index e0171ee8..81ba8d1e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt @@ -6,7 +6,6 @@ import android.Manifest import android.content.pm.PackageManager import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.animation.ExperimentalSharedTransitionApi import androidx.compose.foundation.background import androidx.compose.foundation.focusable import androidx.compose.foundation.rememberScrollState @@ -26,7 +25,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -77,8 +75,6 @@ import com.composables.icons.lucide.ChevronDown import com.composables.icons.lucide.ListMusic import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Music -import com.composables.icons.lucide.Pause -import com.composables.icons.lucide.Play import com.composables.icons.lucide.Repeat import com.composables.icons.lucide.Repeat1 import com.composables.icons.lucide.Shuffle @@ -91,12 +87,10 @@ import com.fabledsword.minstrel.player.output.OutputPickerSheet import com.fabledsword.minstrel.player.output.OutputPickerViewModel import com.fabledsword.minstrel.player.output.OutputRoute import com.fabledsword.minstrel.player.output.RouteSnapshot +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import kotlinx.coroutines.launch import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.HERO_KEY_NOW_PLAYING_COVER -import com.fabledsword.minstrel.nav.LocalAnimatedContentScope -import com.fabledsword.minstrel.nav.LocalSharedTransitionScope import com.fabledsword.minstrel.nav.NowPlaying import com.fabledsword.minstrel.nav.Queue import com.fabledsword.minstrel.shared.formatDuration @@ -423,6 +417,8 @@ private fun PlaybackControlsBlock( TransportRow( isPlaying = state.isPlaying, isUpnpLoading = state.isUpnpLoading, + hasPrevious = state.canSkipPrevious, + hasNext = state.hasNext, onPrev = viewModel::skipToPrevious, onPlayPause = { if (state.isPlaying) viewModel.pause() else viewModel.play() }, onNext = viewModel::skipToNext, @@ -537,25 +533,10 @@ private fun ViewQueueButton(onClick: () -> Unit) { } } -@OptIn(ExperimentalSharedTransitionApi::class) @Composable private fun NowPlayingCover(coverUrl: String, contentDescription: String) { - val sharedScope = LocalSharedTransitionScope.current - val animatedScope = LocalAnimatedContentScope.current - val heroModifier = if (sharedScope != null && animatedScope != null) { - with(sharedScope) { - Modifier.sharedElement( - sharedContentState = rememberSharedContentState( - key = HERO_KEY_NOW_PLAYING_COVER, - ), - animatedVisibilityScope = animatedScope, - ) - } - } else { - Modifier - } Box( - modifier = heroModifier + modifier = nowPlayingCoverHero() .widthIn(max = COVER_MAX_WIDTH_DP.dp) .fillMaxWidth() .aspectRatio(1f) @@ -567,14 +548,7 @@ private fun NowPlayingCover(coverUrl: String, contentDescription: String) { url = coverUrl, contentDescription = contentDescription, modifier = Modifier.fillMaxSize(), - ) { - Icon( - imageVector = Lucide.Music, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(96.dp), - ) - } + ) { CoverFallbackIcon(Lucide.Music, size = 96.dp) } } } @@ -700,51 +674,48 @@ private fun ScrubTrack(fraction: Float, accent: Color) { } } +@Suppress("LongParameterList") // Compose row wiring — transport state + callbacks, not logic. @Composable private fun TransportRow( isPlaying: Boolean, isUpnpLoading: Boolean, + hasPrevious: Boolean, + hasNext: Boolean, onPrev: () -> Unit, onPlayPause: () -> Unit, onNext: () -> Unit, ) { val actionColors = LocalActionColors.current + val skipTint = MaterialTheme.colorScheme.onBackground Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically, ) { - IconButton(onClick = onPrev) { - Icon( - imageVector = Lucide.SkipBack, - contentDescription = "Previous", - tint = MaterialTheme.colorScheme.onBackground, - modifier = Modifier.size(TRANSPORT_ICON_DP.dp), - ) - } - IconButton(onClick = onPlayPause, enabled = !isUpnpLoading) { - if (isUpnpLoading) { - CircularProgressIndicator( - modifier = Modifier.size(PLAY_PAUSE_ICON_DP.dp), - strokeWidth = 3.dp, - ) - } else { - Icon( - imageVector = if (isPlaying) Lucide.Pause else Lucide.Play, - contentDescription = if (isPlaying) "Pause" else "Play", - tint = actionColors.primary, - modifier = Modifier.size(PLAY_PAUSE_ICON_DP.dp), - ) - } - } - IconButton(onClick = onNext) { - Icon( - imageVector = Lucide.SkipForward, - contentDescription = "Next", - tint = MaterialTheme.colorScheme.onBackground, - modifier = Modifier.size(TRANSPORT_ICON_DP.dp), - ) - } + SkipButton( + icon = Lucide.SkipBack, + description = "Previous", + enabled = hasPrevious, + tint = skipTint, + iconSize = TRANSPORT_ICON_DP.dp, + onClick = onPrev, + ) + PlayPauseButton( + isPlaying = isPlaying, + isUpnpLoading = isUpnpLoading, + tint = actionColors.primary, + iconSize = PLAY_PAUSE_ICON_DP.dp, + spinnerStroke = 3.dp, + onClick = onPlayPause, + ) + SkipButton( + icon = Lucide.SkipForward, + description = "Next", + enabled = hasNext, + tint = skipTint, + iconSize = TRANSPORT_ICON_DP.dp, + onClick = onNext, + ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt index 1f7810ce..0799b693 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt @@ -3,6 +3,7 @@ package com.fabledsword.minstrel.player.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fabledsword.minstrel.likes.data.LikesRepository +import com.fabledsword.minstrel.likes.data.toggleTrackLike import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.player.PlayerUiState import dagger.hilt.android.lifecycle.HiltViewModel @@ -61,10 +62,7 @@ class PlayerViewModel @Inject constructor( fun clearQueue() = controller.clearQueue() fun toggleLikeTrack(trackId: String) { - val desired = trackId !in likedTrackIds.value - viewModelScope.launch { - likes.toggleLike(LikesRepository.ENTITY_TRACK, trackId, desired) - } + viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt index 40cc1d52..e74be1c4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt @@ -2,58 +2,38 @@ package com.fabledsword.minstrel.player.ui import androidx.compose.foundation.background import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SwipeToDismissBox -import androidx.compose.material3.SwipeToDismissBoxValue import androidx.compose.material3.Text -import androidx.compose.material3.rememberSwipeToDismissBoxState import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.composed import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.semantics.CustomAccessibilityAction -import androidx.compose.ui.semantics.customActions -import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp -import androidx.compose.ui.zIndex import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Music -import com.composables.icons.lucide.Trash2 import com.composables.icons.lucide.Volume2 import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.widgets.LikeButton +import com.fabledsword.minstrel.shared.widgets.ReorderableRemovableRow import com.fabledsword.minstrel.shared.widgets.ServerImage -import com.fabledsword.minstrel.theme.LocalActionColors /* - * A single queue row, kept apart from QueueScreen.kt: the row carries two - * gestures, a swipe background, and its own accessibility surface, which - * is more behaviour than the screen that lists it. `internal` rather than - * `private` only because QueueList (still in QueueScreen.kt) is the caller. + * A single queue row. Its drag, swipe and screen-reader actions come from + * ReorderableRemovableRow, shared with playlist rows. `internal` rather than + * `private` only because QueueList (in QueueScreen.kt) is the caller. */ @Suppress("LongParameterList") // Compose row wiring — layout + queue callbacks, not logic. @@ -69,225 +49,55 @@ internal fun QueueRow( onRemove: () -> Unit, onMove: (Int, Int) -> Unit, ) { - var dragOffsetY by remember { mutableFloatStateOf(0f) } - var rowHeightPx by remember { mutableIntStateOf(0) } val highlight = if (isCurrent) { MaterialTheme.colorScheme.primary.copy(alpha = HIGHLIGHT_ALPHA) } else { Color.Transparent } - // Swipe left to remove. Only - // end-to-start is enabled: a right-swipe has no meaning here, and leaving it - // live would delete tracks on a mis-aimed gesture in either direction. - val dismissState = rememberSwipeToDismissBoxState( - confirmValueChange = { value -> - if (value == SwipeToDismissBoxValue.EndToStart) { - onRemove() - true - } else { - false - } - }, - ) - SwipeToDismissBox( - state = dismissState, - enableDismissFromStartToEnd = false, - backgroundContent = { RemoveSwipeBackground() }, - // The reorder lift lives out here so a row being dragged vertically - // carries its swipe container with it rather than sliding out of one. - modifier = Modifier - .onSizeChanged { rowHeightPx = it.height } - .zIndex(if (dragOffsetY != 0f) 1f else 0f) - .graphicsLayer { translationY = dragOffsetY }, - ) { - QueueRowContent( - track = track, - index = index, - queueSize = queueSize, - isCurrent = isCurrent, - liked = liked, - highlight = highlight, - rowHeightPx = rowHeightPx, - onClick = onClick, - onToggleLike = onToggleLike, - onRemove = onRemove, - onMove = onMove, - onDragOffset = { dragOffsetY = it }, - ) - } -} - -@Suppress("LongParameterList") // Compose row wiring — layout + queue callbacks, not logic. -@Composable -private fun QueueRowContent( - track: TrackRef, - index: Int, - queueSize: Int, - isCurrent: Boolean, - liked: Boolean, - highlight: Color, - rowHeightPx: Int, - onClick: () -> Unit, - onToggleLike: () -> Unit, - onRemove: () -> Unit, - onMove: (Int, Int) -> Unit, - onDragOffset: (Float) -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - // Opaque: this sits ON TOP of the red remove background, so a - // transparent row would show the fill through it at rest. - .background(MaterialTheme.colorScheme.surface) - .background(highlight) - .clickable(onClick = onClick) - .queueReorderActions( - index = index, - queueSize = queueSize, - onMove = onMove, - onRemove = onRemove, - ) - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - // The album art IS the grab surface: a separate grip icon would - // cost ~36dp of every row's width — icon plus its 12dp gap — on the - // narrowest surface in the app, competing with the title for space. - QueueRowThumbnail( - track = track, - dragModifier = Modifier.queueReorderDrag( - index = index, - queueSize = queueSize, - rowHeightPx = rowHeightPx, - onOffsetChange = onDragOffset, - onMove = onMove, - ), - ) - if (isCurrent) { - Icon( - Lucide.Volume2, - contentDescription = "Now playing", - tint = MaterialTheme.colorScheme.primary, - ) - } - QueueRowText(track = track, isCurrent = isCurrent, modifier = Modifier.weight(1f)) - if (track.durationSec > 0) { - Text( - text = formatDuration(track.durationSec), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - LikeButton(liked = liked, onToggle = onToggleLike) - } -} - -/** - * What the row slides off to reveal: the destructive colour with a trash glyph, - * pinned to the trailing edge because that is the edge the swipe uncovers. - * - * Oxblood (LocalActionColors.destructive), NOT colorScheme.error. The design - * system keeps those apart deliberately — an error is a failure that already - * happened, a destructive action is one about to happen — and using the error - * colour here would dress an intentional gesture as a fault report. - */ -@Composable -private fun RemoveSwipeBackground() { - val actions = LocalActionColors.current - Box( - modifier = Modifier - .fillMaxSize() - .background(actions.destructive) - .padding(horizontal = 24.dp), - contentAlignment = Alignment.CenterEnd, - ) { + ReorderableRemovableRow( + index = index, + count = queueSize, + removeLabel = "Remove from queue", + onRemove = onRemove, + onMove = onMove, + ) { handles -> Row( + modifier = Modifier + .fillMaxWidth() + // Opaque: this sits ON TOP of the red remove background, so a + // transparent row would show the fill through it at rest. + .background(MaterialTheme.colorScheme.surface) + .background(highlight) + .clickable(onClick = onClick) + .then(handles.actions) + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Icon(Lucide.Trash2, contentDescription = null, tint = actions.onAction) - Text( - text = "Remove", - style = MaterialTheme.typography.labelLarge, - color = actions.onAction, - ) + // The album art IS the grab surface: a separate grip icon would + // cost ~36dp of every row's width — icon plus its 12dp gap — on the + // narrowest surface in the app, competing with the title for space. + QueueRowThumbnail(track = track, dragModifier = handles.drag) + if (isCurrent) { + Icon( + Lucide.Volume2, + contentDescription = "Now playing", + tint = MaterialTheme.colorScheme.primary, + ) + } + QueueRowText(track = track, isCurrent = isCurrent, modifier = Modifier.weight(1f)) + if (track.durationSec > 0) { + Text( + text = formatDuration(track.durationSec), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + LikeButton(liked = liked, onToggle = onToggleLike) } } } -/** - * Screen-reader reordering and removal for a queue row. - * - * Both gestures this row now relies on — long-press-drag to reorder, swipe to - * remove — are touch-only and unavailable under TalkBack, and each replaced a - * control that a screen reader COULD find (the grip's "Reorder track", the X's - * "Remove from queue"). Without these actions the row would have lost both - * capabilities for anyone not using touch. They're the Android counterpart to - * the web row's ArrowUp/ArrowDown keys and its still-present X button. - */ -private fun Modifier.queueReorderActions( - index: Int, - queueSize: Int, - onMove: (Int, Int) -> Unit, - onRemove: () -> Unit, -): Modifier = semantics { - customActions = listOf( - CustomAccessibilityAction("Move up") { - if (index > 0) { onMove(index, index - 1); true } else false - }, - CustomAccessibilityAction("Move down") { - if (index < queueSize - 1) { onMove(index, index + 1); true } else false - }, - CustomAccessibilityAction("Remove from queue") { onRemove(); true }, - ) -} - -/** - * Reorder-drag behaviour for a queue row, applied to whatever element is the - * grab surface — the album art. - * - * Uses **detectDragGesturesAfterLongPress**, not detectDragGestures, and that - * is the load-bearing detail. A 48dp thumbnail is a large chunk of every row, - * and with a plain drag detector any vertical pan starting on artwork would be - * swallowed as a row-reorder instead of scrolling the queue — the list would - * feel broken precisely where it's easiest to touch. - * Long-press-then-drag separates the two: pan scrolls, long-press reorders, - * Long-press-then-drag separates the two: pan scrolls, long-press reorders, - * tap still plays (the detector doesn't consume a plain tap, so it falls - * through to the row's clickable). - */ -private fun Modifier.queueReorderDrag( - index: Int, - queueSize: Int, - rowHeightPx: Int, - onOffsetChange: (Float) -> Unit, - onMove: (Int, Int) -> Unit, -): Modifier = composed { - // Mirrors the web queue: the row follows the finger during a drag, then on - // release we translate the accumulated offset into a row delta and reorder. - var offset by remember { mutableFloatStateOf(0f) } - pointerInput(index, queueSize, rowHeightPx) { - detectDragGesturesAfterLongPress( - onDrag = { change, dragAmount -> - change.consume() - offset += dragAmount.y - onOffsetChange(offset) - }, - onDragEnd = { - val target = queueDragTarget(index, offset, rowHeightPx, queueSize) - if (target != index) onMove(index, target) - offset = 0f - onOffsetChange(0f) - }, - onDragCancel = { - offset = 0f - onOffsetChange(0f) - }, - ) - } -} - @Composable private fun QueueRowThumbnail(track: TrackRef, dragModifier: Modifier = Modifier) { Box( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt index 913d8cf0..214edb6b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt @@ -37,6 +37,7 @@ import com.composables.icons.lucide.ArrowLeft import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Trash2 import com.fabledsword.minstrel.models.TrackRef +import com.fabledsword.minstrel.shared.plural import com.fabledsword.minstrel.shared.widgets.EmptyState import kotlinx.coroutines.launch @@ -186,8 +187,7 @@ private fun queueSummary(tracks: List): String { } else { "$minutes min" } - val noun = if (tracks.size == 1) "track" else "tracks" - return "${tracks.size} $noun · $length" + return "${plural(tracks.size, "track", "tracks")} · $length" } private const val SECONDS_PER_MINUTE = 60 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/TransportControls.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/TransportControls.kt new file mode 100644 index 00000000..80ac653a --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/TransportControls.kt @@ -0,0 +1,76 @@ +package com.fabledsword.minstrel.player.ui + +import androidx.compose.foundation.layout.size +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.unit.Dp +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Pause +import com.composables.icons.lucide.Play + +/** Material's alpha for disabled content. */ +private const val DISABLED_ALPHA = 0.38f + +/** + * A Previous or Next button, shared by the mini player and Now Playing. + * It greys out when [enabled] is false: at the ends of the queue (repeat + * off or repeat one) there is nowhere to go, and a button that does + * nothing should look it. + */ +@Suppress("LongParameterList") // Compose button wiring — look + state + click, not logic. +@Composable +internal fun SkipButton( + icon: ImageVector, + description: String, + enabled: Boolean, + tint: Color, + iconSize: Dp, + onClick: () -> Unit, +) { + IconButton(onClick = onClick, enabled = enabled) { + Icon( + imageVector = icon, + contentDescription = description, + tint = if (enabled) tint else tint.copy(alpha = DISABLED_ALPHA), + modifier = Modifier.size(iconSize), + ) + } +} + +/** + * The play/pause button, shared by the mini player and Now Playing. While + * a speaker (Sonos or another UPnP renderer) is still taking the queue, a + * spinner stands in for the icon and the button is disabled, since a tap + * then would reach a player that isn't ready. + */ +@Suppress("LongParameterList") // Compose button wiring — look + state + click, not logic. +@Composable +internal fun PlayPauseButton( + isPlaying: Boolean, + isUpnpLoading: Boolean, + tint: Color, + iconSize: Dp, + spinnerStroke: Dp, + onClick: () -> Unit, +) { + IconButton(onClick = onClick, enabled = !isUpnpLoading) { + if (isUpnpLoading) { + CircularProgressIndicator( + modifier = Modifier.size(iconSize), + strokeWidth = spinnerStroke, + ) + } else { + Icon( + imageVector = if (isPlaying) Lucide.Pause else Lucide.Play, + contentDescription = if (isPlaying) "Pause" else "Play", + tint = tint, + modifier = Modifier.size(iconSize), + ) + } + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt new file mode 100644 index 00000000..4d566217 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt @@ -0,0 +1,169 @@ +package com.fabledsword.minstrel.playlists + +import com.fabledsword.minstrel.models.PlaylistRef +import com.fabledsword.minstrel.shared.plural +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit +import java.util.Locale +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToInt + +// What a Home shelf of playlist tiles shows: which album covers each tile +// gets, the one line of facts the shelf's tiles share, and the colour a +// wide card or genre band is washed in. Mirrors the web client's +// lib/playlists/shelf.ts so both Homes read the same. + +/** + * Each tile takes the first of its playlist's cover albums that no tile + * before it on the shelf already shows, so a shelf never repeats a cover + * while a tile still has an unused one. A tile whose albums are all taken + * reuses its own first albums rather than showing nothing. [perTile] is + * how many covers a tile shows (one for a card, three for a genre band). + */ +fun assignShelfCovers(playlists: List, perTile: Int): List> { + val used = mutableSetOf() + return playlists.map { p -> + val fresh = p.coverAlbumIds.filter { it !in used }.take(perTile) + val picked = fresh.ifEmpty { p.coverAlbumIds.take(perTile) } + used += picked + picked + } +} + +/** + * System playlists are rebuilt in place, so created_at is when the mix was + * last refreshed. Worded for a person ("Refreshed today"), not as "3h ago". + * Empty when [iso] does not parse. + */ +fun refreshedLabel( + iso: String, + now: Instant = Instant.now(), + zone: ZoneId = ZoneId.systemDefault(), +): String { + val t = runCatching { Instant.parse(iso) }.getOrNull() ?: return "" + val days = ChronoUnit.DAYS.between(t.atZone(zone).toLocalDate(), now.atZone(zone).toLocalDate()) + return when { + ChronoUnit.MINUTES.between(t, now) < JUST_NOW_MINUTES -> "Refreshed just now" + days <= 0 -> "Refreshed today" + days == 1L -> "Refreshed yesterday" + days < WEEK_DAYS -> "Refreshed $days days ago" + else -> "Refreshed " + t.atZone(zone).format(DateTimeFormatter.ofPattern("MMM d", Locale.getDefault())) + } +} + +/** + * The facts every system mix on a shelf has in common, said once beside the + * shelf's title instead of under each tile: their size when it is about the + * same, and when they were refreshed when that is the same. Empty when the + * mixes share nothing worth saying. User playlists are left out: their sizes + * and ages are their own. + */ +fun shelfMeta( + playlists: List, + now: Instant = Instant.now(), + zone: ZoneId = ZoneId.systemDefault(), +): String { + val mixes = playlists.filter { it.isSystem } + if (mixes.isEmpty()) return "" + val parts = mutableListOf() + + val counts = mixes.map { it.trackCount }.sorted() + val lo = counts.first() + val hi = counts.last() + if (lo == hi) { + parts += "${plural(lo, "song", "songs")} each" + } else if (hi - lo <= hi * SAME_SIZE_TOLERANCE) { + // Close enough to read as one size: round the middle to a friendly 5. + val mid = counts[counts.size / 2] + val rounded = max(ROUND_TO, (mid.toDouble() / ROUND_TO).roundToInt() * ROUND_TO) + parts += "about ${plural(rounded, "song", "songs")} each" + } + + val labels = mixes.map { refreshedLabel(it.createdAt, now, zone) }.toSet() + val label = labels.singleOrNull() + if (!label.isNullOrEmpty()) parts += label.lowercase(Locale.getDefault()) + + return parts.joinToString(" · ").replaceFirstChar { it.uppercase() } +} + +/** + * Orders a shelf by the rank the server gave each mix (1 first; genre mixes + * lead with the genres the listener plays most). Unranked playlists follow in + * name order, as do ranked ones should two share a rank. + */ +val byShelfRank: Comparator = + compareBy { if (it.shelfRank > 0) it.shelfRank else Int.MAX_VALUE } + .thenBy { it.name.lowercase(Locale.getDefault()) } + +/** + * "Songs like Low Tide Choir" → "Low Tide Choir": a Songs like tile labels + * the artist under its circle, so the prefix would only repeat the shelf. + */ +fun songsLikeArtist(p: PlaylistRef): String = p.name.replace(SONGS_LIKE_PREFIX, "") + +/** An sRGB colour as 0–255 channels; kept free of Compose so it unit-tests. */ +data class Rgb(val r: Int, val g: Int, val b: Int) + +/** + * The colour a wide card or genre band is washed in, from its lead cover's + * main colour. A light or loud cover would wash the card too light for the + * light text on it, so the tone keeps the cover's hue but caps its + * lightness and saturation. The card's gradient then darkens it further, + * and its text clears 4.5:1 on any cover (ShelfTest checks it). + */ +fun washTone(c: Rgb): Rgb { + val (h, s, l) = toHsl(c.r / CHANNEL_MAX, c.g / CHANNEL_MAX, c.b / CHANNEL_MAX) + return fromHsl(h, min(s, MAX_WASH_SATURATION), min(l, MAX_WASH_LIGHTNESS)) +} + +private fun toHsl(r: Double, g: Double, b: Double): Triple { + val mx = maxOf(r, g, b) + val mn = minOf(r, g, b) + val l = (mx + mn) / 2 + if (mx == mn) return Triple(0.0, 0.0, l) + val d = mx - mn + val s = if (l > HALF) d / (2 - mx - mn) else d / (mx + mn) + val h = when (mx) { + r -> (g - b) / d + (if (g < b) HUE_SECTORS else 0.0) + g -> (b - r) / d + 2 + else -> (r - g) / d + 4 + } + return Triple(h / HUE_SECTORS, s, l) +} + +private fun fromHsl(h: Double, s: Double, l: Double): Rgb { + val q = if (l < HALF) l * (1 + s) else l + s - l * s + val p = 2 * l - q + fun channel(t0: Double): Double { + var t = t0 + if (t < 0) t += 1 + if (t > 1) t -= 1 + return when { + t < 1.0 / HUE_SECTORS -> p + (q - p) * HUE_SECTORS * t + t < HALF -> q + t < TWO_THIRDS -> p + (q - p) * (TWO_THIRDS - t) * HUE_SECTORS + else -> p + } + } + return Rgb( + r = (channel(h + ONE_THIRD) * CHANNEL_MAX).roundToInt(), + g = (channel(h) * CHANNEL_MAX).roundToInt(), + b = (channel(h - ONE_THIRD) * CHANNEL_MAX).roundToInt(), + ) +} + +private val SONGS_LIKE_PREFIX = Regex("^Songs like\\s+", RegexOption.IGNORE_CASE) +private const val JUST_NOW_MINUTES = 5 +private const val WEEK_DAYS = 7 +private const val SAME_SIZE_TOLERANCE = 0.1 +private const val ROUND_TO = 5 +private const val CHANNEL_MAX = 255.0 +private const val HUE_SECTORS = 6.0 +private const val HALF = 0.5 +private const val ONE_THIRD = 1.0 / 3 +private const val TWO_THIRDS = 2.0 / 3 +private const val MAX_WASH_SATURATION = 0.6 +private const val MAX_WASH_LIGHTNESS = 0.3 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt new file mode 100644 index 00000000..294cfb49 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt @@ -0,0 +1,46 @@ +package com.fabledsword.minstrel.playlists.data + +/* + * How a playlist looks straight after the listener changes it, before the + * server's copy comes back. Pure, so the detail screen shows a change at + * once and the transforms are testable without a device. Positions are + * renumbered 0..n-1, as the server numbers them. + */ + +/** The playlist without its entry at [index]. */ +fun PlaylistDetailRef.withoutEntry(index: Int): PlaylistDetailRef { + if (index !in tracks.indices) return this + val kept = tracks.filterIndexed { i, _ -> i != index } + return copy( + playlist = playlist.copy(trackCount = kept.size), + tracks = kept.mapIndexed { i, row -> row.copy(position = i) }, + ) +} + +/** The playlist with its entry at [from] moved to [to]. */ +fun PlaylistDetailRef.withEntryMoved(from: Int, to: Int): PlaylistDetailRef { + if (from !in tracks.indices || to !in tracks.indices || from == to) return this + val moved = tracks.toMutableList().apply { add(to, removeAt(from)) } + return copy(tracks = moved.mapIndexed { i, row -> row.copy(position = i) }) +} + +/** + * The songs in list order, which is what a reorder sends. An entry whose + * song has left the library has no id; the server keeps it where it is. + */ +fun PlaylistDetailRef.trackOrder(): List = tracks.mapNotNull { it.trackId } + +/** + * A key per entry that stays with the entry when others move or go: the + * song's id, with a count after a song the list holds more than once. + * Keying rows by position would hand a removed row's swipe state to the + * row that slides into its place. + */ +fun PlaylistDetailRef.entryKeys(): List { + val seen = HashMap() + return tracks.map { row -> + val base = row.trackId ?: "gone" + val n = seen.merge(base, 1, Int::plus) ?: 1 + "$base#$n" + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt index bbe0371f..3c98f881 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt @@ -1,8 +1,13 @@ package com.fabledsword.minstrel.playlists.data import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest +import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest import com.fabledsword.minstrel.api.endpoints.PlaylistsApi +import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest +import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import retrofit2.HttpException import java.net.HttpURLConnection import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao @@ -11,6 +16,11 @@ import com.fabledsword.minstrel.cache.db.dao.PlaylistCachedCount import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.PlaylistAppendPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistCreatePayload +import com.fabledsword.minstrel.cache.mutations.PlaylistRemoveTrackPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistReorderPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistUpdatePayload import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.models.PlaylistTrackRef import com.fabledsword.minstrel.models.TrackRef @@ -18,12 +28,15 @@ import com.fabledsword.minstrel.models.wire.PlaylistDetailWire import com.fabledsword.minstrel.models.wire.PlaylistTrackWire import com.fabledsword.minstrel.models.wire.PlaylistWire import com.fabledsword.minstrel.shared.resolveServerUrl +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import retrofit2.Retrofit import retrofit2.create -import java.io.IOException +import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @@ -39,6 +52,7 @@ import javax.inject.Singleton * persists offline at the ID level) AND keep the freshest detail * response in memory via the returned `PlaylistDetailRef`. */ +@Suppress("TooManyFunctions") // one method per playlist read or write @Singleton class PlaylistsRepository @Inject constructor( private val playlistDao: CachedPlaylistDao, @@ -62,9 +76,19 @@ class PlaylistsRepository @Inject constructor( playlistDao.observeCachedCounts(), ) { rows, counts -> mergePlaylistsWithCache(rows, counts) } - /** User-owned playlists only (systemVariant IS NULL). */ - fun observeUserPlaylists(): Flow> = - playlistDao.observeUserPlaylists().map { rows -> rows.map { it.toDomain() } } + /** + * The signed-in listener's own playlists, not mixes and not other + * people's public lists: the ones a song can be added to. + */ + @OptIn(ExperimentalCoroutinesApi::class) + fun observeOwnPlaylists(): Flow> = + authController.currentUser.flatMapLatest { user -> + if (user == null) { + flowOf(emptyList()) + } else { + playlistDao.observeOwnedUserPlaylists(user.id).map { rows -> rows.map { it.toDomain() } } + } + } /** Server-generated system playlists (for_you / discover / etc.). */ fun observeSystemPlaylists(): Flow> = @@ -87,9 +111,10 @@ class PlaylistsRepository @Inject constructor( // UUIDs every rebuild, so upsert alone leaves stale rows // whose detail fetch 404s ("That playlist no longer // exists"). + // A list made offline isn't on the server yet; keep it. playlistDao.replaceList( userId = userId, - freshOwnedIds = wire.owned.map { it.id }, + freshOwnedIds = wire.owned.map { it.id } + mutationQueue.pendingPlaylistCreateIds(), all = all, ) } else { @@ -134,19 +159,6 @@ class PlaylistsRepository @Inject constructor( ) } - /** - * Append a single track to a user-owned playlist. Follows the - * project's offline-first write contract: optimistic Room insert - * first (so the playlist detail screen shows the new row instantly), - * then fire `POST /api/playlists/{id}/tracks`. On transport failure - * the call is enqueued via MutationQueue for the next drain pass. - * - * The optimistic row's position is best-effort — server reasserts - * canonical position on the next playlist fetch. The (playlistId, - * trackId) composite PK guarantees no duplicate rows; if the track - * is already in the playlist, the IGNORE on conflict leaves the - * existing position unchanged. - */ /** * Rebuilds the caller's system playlist of [variant]. The server * rotates the playlist's UUID on rebuild — the returned id (null @@ -174,32 +186,100 @@ class PlaylistsRepository @Inject constructor( ) } - suspend fun appendTrack(playlistId: String, trackId: String): AppendOutcome { + // ── Writes to the listener's own playlists ─────────────────────── + // + // Each follows the offline-first write contract: change Room first so + // every screen shows it at once, send it, and on a transport failure + // queue it for MutationReplayer. Membership positions in Room are + // best-effort; the next detail fetch puts the server's back. + + /** + * Append a single track to a user-owned playlist. The (playlistId, + * trackId) key means a song already in the list keeps its place in + * Room. The send and its queued replay carry one request id, so a + * replay of a send that reached the server, but whose reply didn't + * reach the phone, doesn't add the song a second time. + */ + suspend fun appendTrack(playlistId: String, trackId: String): WriteOutcome { val nextPos = (playlistTrackDao.maxPosition(playlistId) ?: -1) + 1 playlistTrackDao.insertOrIgnore( - CachedPlaylistTrackEntity( - playlistId = playlistId, - trackId = trackId, - position = nextPos, - ), + CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = nextPos), ) - return try { - api.appendTracks( - playlistId = playlistId, - body = AppendTracksRequest(trackIds = listOf(trackId)), + val append = PlaylistAppendPayload(playlistId, listOf(trackId), requestId = UUID.randomUUID().toString()) + return sendOrQueue( + send = { api.appendTracks(playlistId, AppendTracksRequest(append.trackIds, append.requestId)) }, + queue = { mutationQueue.enqueuePlaylistAppend(append) }, + ) + } + + /** + * Makes a private playlist called [name] and returns its id. The id is + * made here, so the list can be opened, filled and shown before the + * server has heard of it. + */ + suspend fun createPlaylist(name: String): Pair { + val id = UUID.randomUUID().toString() + val userId = authController.currentUser.value?.id.orEmpty() + playlistDao.upsertAll(listOf(CachedPlaylistEntity(id = id, userId = userId, name = name))) + val outcome = sendOrQueue( + send = { api.create(CreatePlaylistRequest(id = id, name = name)) }, + queue = { mutationQueue.enqueuePlaylistCreate(PlaylistCreatePayload(id = id, name = name)) }, + ) + return id to outcome + } + + /** Renames a playlist or makes it public or private; a null argument is left as it is. */ + suspend fun updatePlaylist(id: String, name: String? = null, isPublic: Boolean? = null): WriteOutcome { + playlistDao.getById(id)?.let { row -> + playlistDao.upsertAll( + listOf(row.copy(name = name ?: row.name, isPublic = isPublic ?: row.isPublic)), ) - AppendOutcome.Synced - } catch ( - @Suppress("SwallowedException") _: IOException, - ) { - mutationQueue.enqueuePlaylistAppend(playlistId, listOf(trackId)) - AppendOutcome.Queued } + return sendOrQueue( + send = { api.update(id, UpdatePlaylistRequest(name = name, isPublic = isPublic)) }, + queue = { mutationQueue.enqueuePlaylistUpdate(PlaylistUpdatePayload(id, name, isPublic)) }, + ) + } + + suspend fun deletePlaylist(id: String): WriteOutcome { + playlistTrackDao.deleteByPlaylist(id) + playlistDao.deleteByIds(listOf(id)) + return sendOrQueue( + send = { api.delete(id) }, + queue = { mutationQueue.enqueuePlaylistDelete(id) }, + ) + } + + /** + * Removes the entry at [position], which holds [trackId] (null for a + * song that has left the library). The server removes it only if that + * song is still there. + */ + suspend fun removeTrack(playlistId: String, position: Int, trackId: String?): WriteOutcome { + if (trackId != null) playlistTrackDao.deleteTracksFromPlaylist(playlistId, listOf(trackId)) + return sendOrQueue( + send = { api.removeTrack(playlistId, position, trackId) }, + queue = { + mutationQueue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload(playlistId, position, trackId)) + }, + ) + } + + /** Puts the playlist's songs in the order [trackIds] gives. */ + suspend fun reorderTracks(playlistId: String, trackIds: List): WriteOutcome { + playlistTrackDao.replacePlaylistTracks( + playlistId = playlistId, + rows = trackIds.distinct().mapIndexed { i, trackId -> + CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = i) + }, + ) + return sendOrQueue( + send = { api.reorder(playlistId, ReorderTracksRequest(trackIds = trackIds)) }, + queue = { mutationQueue.enqueuePlaylistReorder(PlaylistReorderPayload(playlistId, trackIds)) }, + ) } } -enum class AppendOutcome { Synced, Queued } - /** * Snapshot of a playlist + its per-track display fields, as returned * by `PlaylistsRepository.refreshDetail`. UI uses this directly for @@ -263,6 +343,9 @@ private fun CachedPlaylistEntity.toDomain(): PlaylistRef = isPublic = isPublic, systemVariant = systemVariant, trackCount = trackCount, + coverAlbumIds = coverAlbumIds.split(',').filter { it.isNotEmpty() }, + createdAt = createdAt, + shelfRank = shelfRank, // Server returns a relative cover path like "/api/playlists//cover"; // wrap through the placeholder host so BaseUrlInterceptor + the shared // Coil/OkHttpClient resolve it against the live server. Without this @@ -280,6 +363,9 @@ private fun PlaylistWire.toEntity(): CachedPlaylistEntity = coverPath = coverUrl.ifEmpty { null }, trackCount = trackCount, systemVariant = systemVariant, + coverAlbumIds = coverAlbumIds.joinToString(","), + createdAt = createdAt, + shelfRank = shelfRank, ) private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity = @@ -292,6 +378,9 @@ private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity = coverPath = coverUrl.ifEmpty { null }, trackCount = trackCount, systemVariant = systemVariant, + coverAlbumIds = coverAlbumIds.joinToString(","), + createdAt = createdAt, + shelfRank = shelfRank, ) private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef = @@ -308,6 +397,9 @@ private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef = // host for BaseUrlInterceptor to rewrite to the live server. coverUrl = resolveServerUrl(coverUrl) ?: "", ownerUsername = ownerUsername, + coverAlbumIds = coverAlbumIds, + createdAt = createdAt, + shelfRank = shelfRank, ) private fun PlaylistTrackWire.toDomain(): PlaylistTrackRef = diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt index 5b7b4425..ad1741b5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt @@ -5,7 +5,6 @@ package com.fabledsword.minstrel.playlists.ui import androidx.compose.animation.Crossfade import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -17,9 +16,11 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -37,10 +38,12 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel @@ -49,18 +52,21 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController import androidx.navigation.toRoute -import coil3.compose.AsyncImage import com.composables.icons.lucide.ArrowLeft +import com.composables.icons.lucide.EllipsisVertical import com.composables.icons.lucide.ListMusic import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Play import com.composables.icons.lucide.RefreshCw import com.composables.icons.lucide.Shuffle import com.fabledsword.minstrel.api.ErrorCopy +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.mutations.WriteOutcome import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.events.EventsStream import com.fabledsword.minstrel.events.LiveEvent +import com.fabledsword.minstrel.likes.data.toggleTrackLike import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.models.PlaylistTrackRef import com.fabledsword.minstrel.models.TrackRef @@ -72,8 +78,19 @@ import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.playlists.data.PlaylistDetailRef import com.fabledsword.minstrel.playlists.data.PlaylistsRepository +import com.fabledsword.minstrel.playlists.data.entryKeys import com.fabledsword.minstrel.playlists.data.toPlayableTrackRefs +import com.fabledsword.minstrel.playlists.data.trackOrder +import com.fabledsword.minstrel.playlists.data.withEntryMoved +import com.fabledsword.minstrel.playlists.data.withoutEntry import com.fabledsword.minstrel.shared.formatDuration +import com.fabledsword.minstrel.shared.plural +import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon +import com.fabledsword.minstrel.shared.widgets.CoverTile +import com.fabledsword.minstrel.shared.widgets.NameDialog +import com.fabledsword.minstrel.shared.widgets.ReorderHandles +import com.fabledsword.minstrel.shared.widgets.ReorderableRemovableRow import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.ErrorRetry @@ -82,7 +99,6 @@ import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton -import com.fabledsword.minstrel.theme.FabledSwordFlatTokens import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel @@ -92,6 +108,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -118,6 +135,7 @@ class PlaylistDetailViewModel @Inject constructor( private val player: PlayerController, private val eventsStream: EventsStream, private val seedCache: DetailSeedCache, + private val authController: AuthController, networkStatus: NetworkStatusController, savedStateHandle: SavedStateHandle, ) : ViewModel() { @@ -154,6 +172,10 @@ class PlaylistDetailViewModel @Inject constructor( private val staleInternal = MutableStateFlow(false) val stale: StateFlow = staleInternal.asStateFlow() + /** A change the server refused, for the screen's snackbar. */ + private val messagesChannel = Channel(Channel.BUFFERED) + val messages: Flow = messagesChannel.receiveAsFlow() + val likedTrackIds: StateFlow> = likes.observeLikedTrackIds() .stateIn( @@ -209,30 +231,92 @@ class PlaylistDetailViewModel @Inject constructor( } fun toggleLikeTrack(trackId: String) { - val desired = trackId !in likedTrackIds.value - viewModelScope.launch { - likes.toggleLike(LikesRepository.ENTITY_TRACK, trackId, desired) - } + viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } } + /** + * Re-fetches the playlist. A list already on screen stays there while + * it loads, and stays if the fetch fails: a refresh after every change + * (the server's event for it) must not blank the list each time, and + * offline the list the listener just edited is the best one there is. + */ fun refresh(): Job = viewModelScope.launch { + val shown = internal.value is PlaylistDetailUiState.Success try { - val carried = when (val cur = internal.value) { - is PlaylistDetailUiState.Loading -> cur.seed - is PlaylistDetailUiState.Success -> cur.detail.playlist - is PlaylistDetailUiState.Error -> null + if (!shown) { + val carried = (internal.value as? PlaylistDetailUiState.Loading)?.seed + internal.value = PlaylistDetailUiState.Loading( + carried ?: seedCache.peekPlaylist(playlistId), + ) } - internal.value = PlaylistDetailUiState.Loading( - carried ?: seedCache.peekPlaylist(playlistId), - ) val detail = repository.refreshDetail(playlistId) internal.value = PlaylistDetailUiState.Success(detail) } catch ( @Suppress("TooGenericExceptionCaught") e: Throwable, ) { - internal.value = PlaylistDetailUiState.Error( - ErrorCopy.fromThrowable(e), - ) + if (!shown) internal.value = PlaylistDetailUiState.Error(ErrorCopy.fromThrowable(e)) + } + } + + // ─── The owner's edits ────────────────────────────────────────── + // + // Each shows at once, then goes to the repository, which sends it or + // queues it for when the server is back. A change the server refuses + // says so and re-fetches, so the screen shows what is really there. + + /** Only the owner edits a playlist, and nobody edits a mix. */ + fun canEdit(playlist: PlaylistRef): Boolean = + !playlist.isSystem && playlist.userId == authController.currentUser.value?.id + + fun rename(name: String) { + val d = shownDetail() ?: return + show(d.copy(playlist = d.playlist.copy(name = name))) + save { repository.updatePlaylist(playlistId, name = name) } + } + + fun setPublic(isPublic: Boolean) { + val d = shownDetail() ?: return + show(d.copy(playlist = d.playlist.copy(isPublic = isPublic))) + save { repository.updatePlaylist(playlistId, isPublic = isPublic) } + } + + /** Deletes the playlist and leaves the screen. */ + fun delete() { + viewModelScope.launch { + runCatching { repository.deletePlaylist(playlistId) } + .onSuccess { deletedChannel.trySend(Unit) } + .onFailure { messagesChannel.trySend("Couldn't delete: ${ErrorCopy.fromThrowable(it)}") } + } + } + + fun removeAt(index: Int) { + val d = shownDetail() ?: return + val row = d.tracks.getOrNull(index) ?: return + show(d.withoutEntry(index)) + save { repository.removeTrack(playlistId, row.position, row.trackId) } + } + + fun move(from: Int, to: Int) { + val d = shownDetail() ?: return + val moved = d.withEntryMoved(from, to) + if (moved === d) return + show(moved) + save { repository.reorderTracks(playlistId, moved.trackOrder()) } + } + + private fun shownDetail(): PlaylistDetailRef? = + (internal.value as? PlaylistDetailUiState.Success)?.detail + + private fun show(detail: PlaylistDetailRef) { + internal.value = PlaylistDetailUiState.Success(detail) + } + + private fun save(write: suspend () -> WriteOutcome) { + viewModelScope.launch { + runCatching { write() }.onFailure { + messagesChannel.trySend("Couldn't save: ${ErrorCopy.fromThrowable(it)}") + refresh() + } } } @@ -310,7 +394,10 @@ fun PlaylistDetailScreen( ) { val state by viewModel.uiState.collectAsState() LaunchedEffect(Unit) { - viewModel.deleted.collect { navController.popBackStack() } + // Once: deleting here also brings the server's "deleted" event, and + // a second pop would leave the screen behind this one too. + viewModel.deleted.first() + navController.popBackStack() } LaunchedEffect(Unit) { viewModel.regenerated.collect { newId -> @@ -326,6 +413,9 @@ fun PlaylistDetailScreen( // non-intrusive "refreshed → Refresh" snackbar; Refresh re-resolves the // rotated uuid (via the regenerated navigate-replace flow). val snackbarHostState = remember { SnackbarHostState() } + LaunchedEffect(Unit) { + viewModel.messages.collect { snackbarHostState.showSnackbar(it) } + } val stale by viewModel.stale.collectAsState() LaunchedEffect(stale) { if (stale) { @@ -343,14 +433,7 @@ fun PlaylistDetailScreen( modifier = Modifier.fillMaxSize(), snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { - TopAppBar( - title = { Text(currentTitle(state)) }, - navigationIcon = { - IconButton(onClick = { navController.popBackStack() }) { - Icon(Lucide.ArrowLeft, contentDescription = "Back") - } - }, - ) + PlaylistDetailTopBar(state, viewModel, onBack = { navController.popBackStack() }) }, ) { inner -> PullToRefreshScaffold( @@ -367,6 +450,35 @@ fun PlaylistDetailScreen( } } +/** The title and back arrow, and the owner's menu when the list is theirs to change. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun PlaylistDetailTopBar( + state: PlaylistDetailUiState, + viewModel: PlaylistDetailViewModel, + onBack: () -> Unit, +) { + TopAppBar( + title = { Text(currentTitle(state)) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon(Lucide.ArrowLeft, contentDescription = "Back") + } + }, + actions = { + val playlist = (state as? PlaylistDetailUiState.Success)?.detail?.playlist + if (playlist != null && viewModel.canEdit(playlist)) { + PlaylistOwnerMenu( + playlist = playlist, + onRename = viewModel::rename, + onSetPublic = viewModel::setPublic, + onDelete = viewModel::delete, + ) + } + }, + ) +} + @Composable private fun PlaylistDetailContent( state: PlaylistDetailUiState, @@ -390,6 +502,9 @@ private fun PlaylistDetailContent( val playerState by playerViewModel.uiState.collectAsState() PlaylistDetailBody( detail = s.detail, + editable = viewModel.canEdit(s.detail.playlist), + onRemove = viewModel::removeAt, + onMove = viewModel::move, likedTrackIds = likedTrackIds, playingTrackId = playerState.currentTrack?.id, onPlayAll = { viewModel.play(s.detail.tracks, startTrackId = null) }, @@ -416,9 +531,13 @@ private fun currentTitle(state: PlaylistDetailUiState): String = when (state) { // ─── Body composables ──────────────────────────────────────────────── +@Suppress("LongParameterList") // Compose body wiring — state + callbacks, not logic. @Composable private fun PlaylistDetailBody( detail: PlaylistDetailRef, + editable: Boolean, + onRemove: (Int) -> Unit, + onMove: (Int, Int) -> Unit, likedTrackIds: Set, playingTrackId: String?, onPlayAll: () -> Unit, @@ -434,16 +553,31 @@ private fun PlaylistDetailBody( ) { item { PlaylistHeader(detail.playlist, onPlayAll, onShuffleAll, onRegenerate) } item { HorizontalDivider() } - items(items = detail.tracks, key = { it.position }) { row -> - TrackRow( - row = row, - liked = row.trackId != null && row.trackId in likedTrackIds, - nowPlaying = row.trackId != null && row.trackId == playingTrackId, - onClick = { row.trackId?.let(onTrackClick) }, - onToggleLike = { row.trackId?.let(onToggleTrackLike) }, - onNavigateToAlbum = onNavigateToAlbum, - onNavigateToArtist = onNavigateToArtist, - ) + val keys = detail.entryKeys() + itemsIndexed(items = detail.tracks, key = { i, _ -> keys[i] }) { index, row -> + val trackRow: @Composable (ReorderHandles?) -> Unit = { handles -> + TrackRow( + row = row, + handles = handles, + liked = row.trackId != null && row.trackId in likedTrackIds, + nowPlaying = row.trackId != null && row.trackId == playingTrackId, + onClick = { row.trackId?.let(onTrackClick) }, + onToggleLike = { row.trackId?.let(onToggleTrackLike) }, + onNavigateToAlbum = onNavigateToAlbum, + onNavigateToArtist = onNavigateToArtist, + ) + } + if (editable) { + ReorderableRemovableRow( + index = index, + count = detail.tracks.size, + removeLabel = "Remove from playlist", + onRemove = { onRemove(index) }, + onMove = onMove, + ) { handles -> trackRow(handles) } + } else { + trackRow(null) + } HorizontalDivider() } if (detail.tracks.isEmpty()) { @@ -496,7 +630,7 @@ private fun PlaylistHeader( } Spacer(Modifier.height(4.dp)) Text( - text = "${playlist.trackCount} tracks", + text = plural(playlist.trackCount, "track", "tracks"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -541,33 +675,20 @@ private fun PlaylistHeaderActions( @Composable private fun PlaylistCover(playlist: PlaylistRef) { - Box( - modifier = Modifier - .size(120.dp) - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) - .background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - if (playlist.coverUrl.isEmpty()) { - Icon( - imageVector = Lucide.ListMusic, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(56.dp), - ) - } else { - AsyncImage( - model = playlist.coverUrl, - contentDescription = playlist.name, - modifier = Modifier.fillMaxSize(), - ) - } - } + CoverTile( + url = playlist.coverUrl, + contentDescription = playlist.name, + size = 120.dp, + background = MaterialTheme.colorScheme.surfaceVariant, + fallback = { CoverFallbackIcon(Lucide.ListMusic) }, + ) } +@Suppress("LongParameterList") // Compose row wiring — state + callbacks, not logic. @Composable private fun TrackRow( row: PlaylistTrackRef, + handles: ReorderHandles?, liked: Boolean, nowPlaying: Boolean, onClick: () -> Unit, @@ -589,14 +710,21 @@ private fun TrackRow( artist = artistLine, trackId = row.trackId.orEmpty(), onClick = onClick, + // An editable row is opaque: it sits on the swipe's remove colour. + modifier = if (handles == null) { + Modifier + } else { + Modifier.background(MaterialTheme.colorScheme.background).then(handles.actions) + }, nowPlaying = nowPlaying, enabled = enabled, contentAlpha = rowAlpha, leading = { + // The cover is the grab surface for a drag, as in the queue. TrackCoverThumb( coverUrl = row.coverUrl, contentDescription = row.title, - modifier = Modifier.padding(end = 12.dp), + modifier = Modifier.padding(end = 12.dp).then(handles?.drag ?: Modifier), ) }, trailing = { @@ -618,6 +746,51 @@ private fun TrackRow( ) } +/** + * The owner's menu in the top bar: rename, make public or private, and + * delete, which asks first. + */ +@Composable +private fun PlaylistOwnerMenu( + playlist: PlaylistRef, + onRename: (String) -> Unit, + onSetPublic: (Boolean) -> Unit, + onDelete: () -> Unit, +) { + var open by remember { mutableStateOf(false) } + var renaming by rememberSaveable { mutableStateOf(false) } + var deleting by rememberSaveable { mutableStateOf(false) } + IconButton(onClick = { open = true }) { + Icon(Lucide.EllipsisVertical, contentDescription = "Playlist options") + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + DropdownMenuItem(text = { Text("Rename") }, onClick = { open = false; renaming = true }) + DropdownMenuItem( + text = { Text(if (playlist.isPublic) "Make private" else "Make public") }, + onClick = { open = false; onSetPublic(!playlist.isPublic) }, + ) + DropdownMenuItem(text = { Text("Delete") }, onClick = { open = false; deleting = true }) + } + if (renaming) { + NameDialog( + title = "Rename playlist", + confirmLabel = "Rename", + initial = playlist.name, + onConfirm = { name -> renaming = false; onRename(name) }, + onDismiss = { renaming = false }, + ) + } + if (deleting) { + ConfirmDestructiveDialog( + title = "Delete playlist?", + text = "Delete \"${playlist.name}\"? The songs stay in your library.", + confirmLabel = "Delete", + onConfirm = { deleting = false; onDelete() }, + onDismiss = { deleting = false }, + ) + } +} + private const val SKELETON_PLAYLIST_ROWS = 8 @Composable @@ -662,7 +835,7 @@ private fun SeededPlaylistLoading(seed: PlaylistRef) { } Spacer(Modifier.height(4.dp)) Text( - text = "${seed.trackCount} tracks", + text = plural(seed.trackCount, "track", "tracks"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt index 9b565c93..41b0bfbf 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt @@ -11,6 +11,8 @@ import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost @@ -19,7 +21,10 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel @@ -27,7 +32,10 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Plus import com.fabledsword.minstrel.api.ErrorCopy +import com.fabledsword.minstrel.cache.mutations.WriteOutcome import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.connectivity.recoveries @@ -46,6 +54,7 @@ import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar +import com.fabledsword.minstrel.shared.widgets.NameDialog import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job @@ -81,6 +90,10 @@ class PlaylistsListViewModel @Inject constructor( /** Transient snackbar messages from playlist tile play taps. */ val transientMessages: Flow = poolMessages.receiveAsFlow() + /** The id of a playlist just made here, for the screen to open. */ + private val createdChannel = Channel(Channel.BUFFERED) + val created: Flow = createdChannel.receiveAsFlow() + /** Cache-only: no link OR server unreachable (Unstable stays calm). Greys tiles. */ val offline: StateFlow = networkStatus.state .map { it == ServerHealth.Offline || it == ServerHealth.ServerDown } @@ -116,6 +129,19 @@ class PlaylistsListViewModel @Inject constructor( .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } } + /** + * Makes an empty playlist called [name] and opens it. Made offline, it + * waits in the list instead: its page can't load until the server has + * it. + */ + fun createPlaylist(name: String) { + viewModelScope.launch { + runCatching { repository.createPlaylist(name) } + .onSuccess { (id, outcome) -> if (outcome == WriteOutcome.Synced) createdChannel.trySend(id) } + .onFailure { poolMessages.trySend("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") } + } + } + /** Tile play button: shuffle the playlist's tracks and start at index 0. */ suspend fun playPlaylist(playlist: PlaylistRef) { viewModelScope.launch { @@ -149,6 +175,18 @@ fun PlaylistsListScreen( LaunchedEffect(Unit) { viewModel.transientMessages.collect { snackbar.showSnackbar(it) } } + LaunchedEffect(Unit) { + viewModel.created.collect { id -> navController.navigate(PlaylistDetail(id)) } + } + var naming by rememberSaveable { mutableStateOf(false) } + if (naming) { + NameDialog( + title = "New playlist", + confirmLabel = "Create", + onConfirm = { name -> naming = false; viewModel.createPlaylist(name) }, + onDismiss = { naming = false }, + ) + } Scaffold( contentWindowInsets = ShellContentWindowInsets, modifier = Modifier.fillMaxSize(), @@ -157,40 +195,51 @@ fun PlaylistsListScreen( title = "Playlists", navController = navController, currentRouteName = Playlists::class.qualifiedName, + actions = { + IconButton(onClick = { naming = true }) { + Icon(Lucide.Plus, contentDescription = "New playlist") + } + }, ) }, snackbarHost = { SnackbarHost(snackbar) }, ) { inner -> - val state by viewModel.uiState.collectAsStateWithLifecycle() - val offline by viewModel.offline.collectAsStateWithLifecycle() PullToRefreshScaffold( onRefresh = { viewModel.refresh().join() }, modifier = Modifier.fillMaxSize().padding(inner), ) { - when (val s = state) { - UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "No playlists yet", - body = "System playlists (For You / Discover / Songs like…) " + - "appear once your library has enough plays. Create your " + - "own playlist from any album or track in the meantime.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load playlists", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> PlaylistsGrid( - playlists = s.data, - offline = offline, - onPlaylistClick = { id -> navController.navigate(PlaylistDetail(id)) }, - onPlay = viewModel::playPlaylist, - ) - } + PlaylistsListBody(viewModel, onOpen = { id -> navController.navigate(PlaylistDetail(id)) }) } } } +/** Loading, empty, error, or the grid of playlists. */ +@Composable +private fun PlaylistsListBody(viewModel: PlaylistsListViewModel, onOpen: (String) -> Unit) { + val state by viewModel.uiState.collectAsStateWithLifecycle() + val offline by viewModel.offline.collectAsStateWithLifecycle() + when (val s = state) { + UiState.Loading -> LoadingCentered() + UiState.Empty -> EmptyState( + title = "No playlists yet", + body = "System playlists (For You / Discover / Songs like…) " + + "appear once your library has enough plays. Make your own " + + "with + above, or from any track's Add to playlist.", + ) + is UiState.Error -> ErrorRetry( + title = "Couldn't load playlists", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> PlaylistsGrid( + playlists = s.data, + offline = offline, + onPlaylistClick = onOpen, + onPlay = viewModel::playPlaylist, + ) + } +} + @Composable private fun PlaylistsGrid( playlists: List, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaceholderShape.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaceholderShape.kt new file mode 100644 index 00000000..a878c4c8 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaceholderShape.kt @@ -0,0 +1,7 @@ +package com.fabledsword.minstrel.playlists.widgets + +/** + * Which shelf a placeholder stands in for; it takes that shelf's tile shape. + * TALL fills the width its caller gives it, like [TallPlaylistCard]. + */ +enum class PlaceholderShape { SQUARE, WIDE, TALL, ROUND } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt index afaeca0f..951cf2ba 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt @@ -8,7 +8,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text @@ -23,6 +22,8 @@ import com.composables.icons.lucide.ListMusic import com.composables.icons.lucide.Lucide import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.nav.LocalDetailSeedCache +import com.fabledsword.minstrel.shared.plural +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.PlayCircleButton import com.fabledsword.minstrel.theme.FabledSwordFlatTokens @@ -105,14 +106,7 @@ private fun PlaylistCardCover( url = playlist.coverUrl, contentDescription = playlist.name, size = 144.dp, - fallback = { - Icon( - imageVector = Lucide.ListMusic, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(56.dp), - ) - }, + fallback = { CoverFallbackIcon(Lucide.ListMusic) }, overlay = { if (playlist.isSystem) { VariantPill( @@ -154,10 +148,9 @@ private fun VariantPill(label: String, modifier: Modifier = Modifier) { } private const val PILL_BG_ALPHA = 0.85f -private const val GREYED_ALPHA = 0.45f private fun subtitleFor(playlist: PlaylistRef): String = when { - playlist.trackCount > 0 -> "${playlist.trackCount} tracks" + playlist.trackCount > 0 -> plural(playlist.trackCount, "track", "tracks") playlist.isSystem -> systemLabelFor(playlist.systemVariant) else -> " " } @@ -171,6 +164,7 @@ private fun systemLabelFor(variant: String?): String = when (variant) { "new_for_you" -> "New for you" "on_this_day" -> "On this day" "first_listens" -> "First listens" + "genre_mix" -> "Genre mix" null -> "" else -> variant.replace('_', ' ').replaceFirstChar { it.uppercase() } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt index 86377ce4..65c37d0c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt @@ -3,12 +3,15 @@ package com.fabledsword.minstrel.playlists.widgets import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme @@ -18,6 +21,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.composables.icons.lucide.ListMusic @@ -43,12 +47,32 @@ fun PlaylistPlaceholderCard( label: String, variant: String, modifier: Modifier = Modifier, + shape: PlaceholderShape = PlaceholderShape.SQUARE, ) { - Column(modifier = modifier.width(176.dp).padding(horizontal = 8.dp)) { + if (shape == PlaceholderShape.WIDE) { + WidePlaceholder(label = label, variant = variant, modifier = modifier) + return + } + val round = shape == PlaceholderShape.ROUND + val tall = shape == PlaceholderShape.TALL + Column( + modifier = if (tall) { + modifier + } else { + modifier.width(if (round) 136.dp else 176.dp).padding(horizontal = 8.dp) + }, + horizontalAlignment = if (round) Alignment.CenterHorizontally else Alignment.Start, + ) { Box( modifier = Modifier - .size(144.dp) - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) + .then( + if (tall) { + Modifier.fillMaxWidth().aspectRatio(1f) + } else { + Modifier.size(if (round) 120.dp else 144.dp) + }, + ) + .clip(if (round) CircleShape else RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { @@ -58,39 +82,80 @@ fun PlaylistPlaceholderCard( tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(40.dp), ) - Surface( + StatusPill( + variant = variant, modifier = Modifier - .align(Alignment.BottomStart) + .align(if (round) Alignment.BottomCenter else Alignment.BottomStart) .padding(6.dp), - shape = RoundedCornerShape(FabledSwordFlatTokens.radiusSm), - color = MaterialTheme.colorScheme.surface.copy(alpha = STATUS_BG_ALPHA), - ) { - Text( - text = statusLabelFor(variant), - modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurface, - ) - } + ) } Spacer(Modifier.height(8.dp)) + PlaceholderText(label = label, variant = variant, centered = round) + } +} + +/** The wide placeholder, the same size as Home's wide playlist card. */ +@Composable +private fun WidePlaceholder(label: String, variant: String, modifier: Modifier) { + Row( + modifier = modifier + .width(296.dp) + .height(125.dp) + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant), + ) { + Box(modifier = Modifier.size(125.dp), contentAlignment = Alignment.Center) { + Icon( + imageVector = iconFor(variant), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(40.dp), + ) + StatusPill(variant = variant, modifier = Modifier.align(Alignment.BottomStart).padding(6.dp)) + } + Column(modifier = Modifier.padding(12.dp)) { + PlaceholderText(label = label, variant = variant, centered = false) + } + } +} + +@Composable +private fun StatusPill(variant: String, modifier: Modifier) { + Surface( + modifier = modifier, + shape = RoundedCornerShape(FabledSwordFlatTokens.radiusSm), + color = MaterialTheme.colorScheme.surface.copy(alpha = STATUS_BG_ALPHA), + ) { Text( - text = label, - style = MaterialTheme.typography.titleSmall, + text = statusLabelFor(variant), + modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), + style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - text = subtitleFor(variant), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, ) } } +@Composable +private fun PlaceholderText(label: String, variant: String, centered: Boolean) { + val align = if (centered) TextAlign.Center else TextAlign.Start + Text( + text = label, + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = align, + ) + Text( + text = subtitleFor(variant), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = align, + ) +} + private const val STATUS_BG_ALPHA = 0.85f private fun iconFor(variant: String) = when (variant) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/ShelfPlaylistCards.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/ShelfPlaylistCards.kt new file mode 100644 index 00000000..40238001 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/ShelfPlaylistCards.kt @@ -0,0 +1,360 @@ +package com.fabledsword.minstrel.playlists.widgets + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shadow +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.zIndex +import com.composables.icons.lucide.ListMusic +import com.composables.icons.lucide.Lucide +import com.fabledsword.minstrel.models.PlaylistRef +import com.fabledsword.minstrel.models.albumCoverPath +import com.fabledsword.minstrel.nav.LocalDetailSeedCache +import com.fabledsword.minstrel.player.ui.rememberDominantColor +import com.fabledsword.minstrel.playlists.Rgb +import com.fabledsword.minstrel.playlists.songsLikeArtist +import com.fabledsword.minstrel.playlists.washTone +import com.fabledsword.minstrel.shared.plural +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon +import com.fabledsword.minstrel.shared.widgets.CoverTile +import com.fabledsword.minstrel.shared.widgets.PlayCircleButton +import com.fabledsword.minstrel.shared.widgets.ServerImage +import com.fabledsword.minstrel.theme.FabledSwordDarkTokens +import kotlin.math.roundToInt + +// Home's three playlist tile shapes, one per kind of shelf, so the shelves +// can be told apart at a glance (the web Home's PlaylistCard has the same +// three): +// - WidePlaylistCard: a main mix or playlist. Its lead cover on the left, +// the name and what it is built from on a wash of the cover's colour. +// - SongsLikeCard: a circle, the shape artists have everywhere else. +// - GenreBandCard: a colour field with a fan of three covers. +// `covers` are the album ids the shelf assigned this tile +// (assignShelfCovers), so neighbouring tiles show different pictures. The +// size and refresh time the tiles share are said once in the shelf heading +// (shelfMeta), so no tile repeats them. + +/** + * A main mix or user playlist on Home. [greyed] dims it (not playable + * offline) while keeping it tappable, as [PlaylistCard] does. + */ +@Composable +fun WidePlaylistCard( + playlist: PlaylistRef, + covers: List, + onClick: () -> Unit, + onPlay: suspend () -> Unit, + playEnabled: Boolean, + greyed: Boolean, +) { + val lead = leadCoverUrl(playlist, covers) + Box( + modifier = Modifier + .width(WIDE_WIDTH) + .height(WIDE_HEIGHT) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .clip(RoundedCornerShape(CARD_RADIUS)) + .background(washBrush(rememberWash(lead))) + .stashingClick(playlist, onClick), + ) { + Row(modifier = Modifier.fillMaxSize()) { + LeadArt(url = lead, modifier = Modifier.size(WIDE_HEIGHT)) + Column( + modifier = Modifier + .weight(1f) + .padding(start = 12.dp, top = 12.dp, end = 52.dp, bottom = 12.dp), + ) { + Text( + text = playlist.name, + style = MaterialTheme.typography.headlineSmall, + color = OnWash, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = sublineFor(playlist), + style = MaterialTheme.typography.bodySmall, + color = OnWash.copy(alpha = ON_WASH_2), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + PlayCircleButton( + onPlay = onPlay, + enabled = playEnabled && !greyed, + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(8.dp), + ) + } +} + +/** A "Songs like {artist}" mix: a circle labelled with the seed artist. */ +@Composable +fun SongsLikeCard( + playlist: PlaylistRef, + covers: List, + onClick: () -> Unit, + onPlay: suspend () -> Unit, + playEnabled: Boolean, + greyed: Boolean, +) { + Column( + modifier = Modifier + .width(ROUND_WIDTH) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .stashingClick(playlist, onClick) + .padding(horizontal = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + CoverTile( + url = leadCoverUrl(playlist, covers), + contentDescription = playlist.name, + size = ROUND_SIZE, + shape = CircleShape, + background = MaterialTheme.colorScheme.surfaceVariant, + fallback = { CoverFallbackIcon(Lucide.ListMusic, size = NO_ART_ICON_SIZE) }, + overlay = { + PlayCircleButton( + onPlay = onPlay, + enabled = playEnabled && !greyed, + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(4.dp), + ) + }, + ) + Spacer(Modifier.height(8.dp)) + Text( + text = "SONGS LIKE", + style = MaterialTheme.typography.labelSmall.copy(letterSpacing = MICRO_LABEL_TRACKING), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = songsLikeArtist(playlist), + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + ) + } +} + +/** + * A genre mix: a field of its lead cover's colour, the genre in large type, + * and a fan of up to three covers across most of its width. The leftmost + * cover sits on top and each one to its right tucks under it. + */ +@Composable +fun GenreBandCard( + playlist: PlaylistRef, + covers: List, + onClick: () -> Unit, + onPlay: suspend () -> Unit, + playEnabled: Boolean, + greyed: Boolean, +) { + val fan = covers.map(::albumCoverPath).ifEmpty { listOfNotNull(playlist.coverUrl.ifEmpty { null }) } + Box( + modifier = Modifier + .width(BAND_WIDTH) + .height(BAND_HEIGHT) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .clip(RoundedCornerShape(CARD_RADIUS)) + .background(washBrush(rememberWash(fan.firstOrNull()))) + .stashingClick(playlist, onClick), + ) { + CoverFan(urls = fan, modifier = Modifier.align(Alignment.CenterEnd).padding(end = 12.dp)) + Text( + text = playlist.name.replace(MIX_SUFFIX, ""), + style = MaterialTheme.typography.headlineSmall.copy( + shadow = Shadow(color = Color.Black.copy(alpha = NAME_SHADOW_ALPHA), blurRadius = 4f), + ), + color = OnWash, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier + .align(Alignment.BottomStart) + .padding(start = 8.dp, bottom = 10.dp) + .widthIn(max = BAND_WIDTH * NAME_MAX_FRACTION) + .zIndex(FAN_LAYERS) + .clip(RoundedCornerShape(6.dp)) + .background(NameBacking) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) + PlayCircleButton( + onPlay = onPlay, + enabled = playEnabled && !greyed, + modifier = Modifier + .align(Alignment.BottomEnd) + .zIndex(FAN_LAYERS + 1) + .padding(8.dp), + ) + } +} + +/** + * Up to three covers spanning [FAN_SPAN] of the band's width, as tall as the + * band allows and overlapping to fit, tilted -8° / 0° / +8°. + */ +@Composable +private fun CoverFan(urls: List, modifier: Modifier = Modifier) { + val n = urls.size.coerceAtMost(FAN_MAX) + if (n == 0) return + val span = BAND_WIDTH * FAN_SPAN + val step: Dp = if (n > 1) (span - FAN_COVER) / (n - 1) else 0.dp + Box(modifier = modifier.width(if (n > 1) span else FAN_COVER).height(BAND_HEIGHT)) { + urls.take(n).forEachIndexed { i, url -> + val tilt = if (n > 1) FAN_TILT_DEG * (2f * i / (n - 1) - 1f) else 0f + ServerImage( + url = url, + contentDescription = null, + modifier = Modifier + .align(Alignment.CenterStart) + .offset(x = step * i, y = if (tilt == 0f) (-4).dp else 4.dp) + .zIndex((n - i).toFloat()) + .rotate(tilt) + .shadow(elevation = 6.dp, shape = RoundedCornerShape(6.dp)) + .size(FAN_COVER) + .clip(RoundedCornerShape(6.dp)), + ) + } + } +} + +@Composable +internal fun LeadArt(url: String?, modifier: Modifier) { + Box( + modifier = modifier + .fillMaxHeight() + .background(MaterialTheme.colorScheme.surfaceVariant), + contentAlignment = Alignment.Center, + ) { + ServerImage( + url = url, + contentDescription = null, + modifier = Modifier.fillMaxSize(), + fallback = { CoverFallbackIcon(Lucide.ListMusic, size = NO_ART_ICON_SIZE) }, + ) + } +} + +@Composable +internal fun Modifier.stashingClick(playlist: PlaylistRef, onClick: () -> Unit): Modifier { + val seedCache = LocalDetailSeedCache.current + return clickable { + seedCache.stashPlaylist(playlist) + onClick() + } +} + +/** + * The wash colour for a tile whose lead cover is [url]: the cover's main + * colour, toned by [washTone] so light text reads on it. A neutral slate + * until the colour is known, or when there is no cover. + */ +@Composable +internal fun rememberWash(url: String?): Color { + val dominant = rememberDominantColor(url) + if (dominant == Color.Transparent) return NeutralWash + val toned = washTone( + Rgb( + r = (dominant.red * CHANNEL_MAX).roundToInt(), + g = (dominant.green * CHANNEL_MAX).roundToInt(), + b = (dominant.blue * CHANNEL_MAX).roundToInt(), + ), + ) + return Color(red = toned.r, green = toned.g, blue = toned.b) +} + +/** + * The tile background: the wash darkened toward near-black, 62% wash at the + * art end fading to 30% (left to right, or top to bottom when [vertical]). + * With [washTone]'s caps this keeps [OnWash] text at 4.5:1 or better on any + * cover (ShelfTest checks the numbers). + */ +internal fun washBrush(wash: Color, vertical: Boolean = false): Brush { + val stops = listOf(lerp(WashBase, wash, WASH_NEAR), lerp(WashBase, wash, WASH_FAR)) + return if (vertical) Brush.verticalGradient(stops) else Brush.horizontalGradient(stops) +} + +internal fun leadCoverUrl(playlist: PlaylistRef, covers: List): String? = + covers.firstOrNull()?.let(::albumCoverPath) ?: playlist.coverUrl.ifEmpty { null } + +/** A system mix says what it is built from; anything else says its size and owner. */ +internal fun sublineFor(p: PlaylistRef): String = + if (p.isSystem && p.description.isNotEmpty()) { + p.description + } else { + plural(p.trackCount, "track", "tracks") + + if (p.ownerUsername.isNotEmpty()) " · by ${p.ownerUsername}" else "" + } + +// The wash is dark in both themes, so its text is the dark theme's light +// parchment in both themes too; the theme-switching tokens would turn it +// dark in light mode and lose the contrast. +internal val OnWash = FabledSwordDarkTokens.parchment +private val WashBase = Color(red = 14, green = 16, blue = 19) +private val NeutralWash = Color(red = 44, green = 49, blue = 58) + +// 70% near-black behind a genre name keeps it above 4.5:1 even where the +// fan's covers run under it and one of them is white. +private val NameBacking = Color(red = 14, green = 16, blue = 19, alpha = 179) +private val MIX_SUFFIX = Regex("\\s+mix$", RegexOption.IGNORE_CASE) + +// Wide card 64:27 and band 16:7, the web Home's proportions. +private val WIDE_WIDTH = 296.dp +private val WIDE_HEIGHT = 125.dp +private val BAND_WIDTH = 280.dp +private val BAND_HEIGHT = 122.dp +private val ROUND_WIDTH = 136.dp +private val ROUND_SIZE = 120.dp +internal val CARD_RADIUS = 12.dp +private val FAN_COVER = 95.dp +private val NO_ART_ICON_SIZE = 40.dp +private val MICRO_LABEL_TRACKING = 0.9.sp + +private const val FAN_SPAN = 0.8f +private const val FAN_MAX = 3 +private const val FAN_LAYERS = 4f +private const val FAN_TILT_DEG = 8f +private const val NAME_MAX_FRACTION = 0.85f +private const val NAME_SHADOW_ALPHA = 0.6f +private const val WASH_NEAR = 0.62f +private const val WASH_FAR = 0.30f +internal const val ON_WASH_2 = 0.9f +internal const val GREYED_ALPHA = 0.45f +private const val CHANNEL_MAX = 255f diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/TallPlaylistCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/TallPlaylistCard.kt new file mode 100644 index 00000000..f8484000 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/TallPlaylistCard.kt @@ -0,0 +1,86 @@ +package com.fabledsword.minstrel.playlists.widgets + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.fabledsword.minstrel.models.PlaylistRef +import com.fabledsword.minstrel.shared.widgets.PlayCircleButton + +/** + * The phone-portrait form of [WidePlaylistCard], for screens where a wide + * card would leave only one playlist in view: the lead cover on top, and + * under it a panel washed in the cover's colour holding the name, what the + * mix is built from, and the play button, which sits on the panel and never + * over the art. [width] is chosen by the shelf so two cards show whole. + */ +@Composable +fun TallPlaylistCard( + playlist: PlaylistRef, + covers: List, + width: Dp, + onClick: () -> Unit, + onPlay: suspend () -> Unit, + playEnabled: Boolean, + greyed: Boolean, +) { + val lead = leadCoverUrl(playlist, covers) + Column( + modifier = Modifier + .width(width) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .clip(RoundedCornerShape(CARD_RADIUS)) + .background(washBrush(rememberWash(lead), vertical = true)) + .stashingClick(playlist, onClick), + ) { + LeadArt(url = lead, modifier = Modifier.fillMaxWidth().aspectRatio(1f)) + Box(modifier = Modifier.fillMaxWidth().height(TALL_PANEL_HEIGHT)) { + Column(modifier = Modifier.padding(start = 10.dp, top = 8.dp, end = 10.dp, bottom = 8.dp)) { + Text( + text = playlist.name, + style = MaterialTheme.typography.headlineSmall, + color = OnWash, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = sublineFor(playlist), + style = MaterialTheme.typography.bodySmall, + color = OnWash.copy(alpha = ON_WASH_2), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + // Leaves the play button's corner clear. + modifier = Modifier.padding(end = 40.dp), + ) + } + PlayCircleButton( + onPlay = onPlay, + enabled = playEnabled && !greyed, + size = 36.dp, + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(8.dp), + ) + } + } +} + +// Name, two lines of description, and room for the play button under them. +private val TALL_PANEL_HEIGHT = 96.dp diff --git a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt index 23f16631..2a9a706e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt @@ -5,17 +5,22 @@ import com.fabledsword.minstrel.api.endpoints.QuarantineApi import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import com.fabledsword.minstrel.models.QuarantineRef import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.models.wire.QuarantineMineWire import com.fabledsword.minstrel.shared.secondsToMillis import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.datetime.Clock +import retrofit2.HttpException import retrofit2.Retrofit import retrofit2.create import javax.inject.Inject import javax.inject.Singleton +import timber.log.Timber /** * Outcome of an `unflag` call — mirrors LikesRepository.toggleLike's @@ -59,7 +64,19 @@ class QuarantineRepository @Inject constructor( /** Pull the server snapshot and atomically replace the cached table. */ suspend fun refresh() { val fresh = api.listMine().map { it.toEntity() } - dao.replaceAll(fresh) + // A flag or unflag still queued wins over the server's list, which + // hasn't seen it yet; a queued flag keeps the row made when it was + // flagged here. + val pending = mutationQueue.pendingQuarantineStates() + if (pending.isEmpty()) { + dao.replaceAll(fresh) + return + } + val kept = fresh.filter { pending[it.trackId] != false } + val listed = kept.mapTo(HashSet()) { it.trackId } + val flaggedHere = dao.observeAll().first() + .filter { pending[it.trackId] == true && it.trackId !in listed } + dao.replaceAll(kept + flaggedHere) } /** Server snapshot without touching the cache — used by the TrackActions hidden check. */ @@ -75,28 +92,41 @@ class QuarantineRepository @Inject constructor( */ suspend fun flag(track: TrackRef, reason: String, notes: String): FlagOutcome { dao.upsert(track.toQuarantineEntity(reason, notes)) - return try { - api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes)) - FlagOutcome.ACCEPTED - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { + // An unflag for this track still queued would replay after a live + // flag and undo it: queue behind it instead. + if (mutationQueue.pendingQuarantineStates().containsKey(track.id)) { mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) - FlagOutcome.QUEUED + return FlagOutcome.QUEUED } + val outcome = sendOrQueue( + send = { api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes)) }, + queue = { mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) }, + onRefused = { e -> refused("flag", track.id, e) }, + ) + return if (outcome == WriteOutcome.Queued) FlagOutcome.QUEUED else FlagOutcome.ACCEPTED } suspend fun unflag(trackId: String): UnflagOutcome { dao.deleteByTrackId(trackId) - return try { - api.unflag(trackId) - UnflagOutcome.ACCEPTED - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { + if (mutationQueue.pendingQuarantineStates().containsKey(trackId)) { mutationQueue.enqueueQuarantineUnflag(trackId) - UnflagOutcome.QUEUED + return UnflagOutcome.QUEUED } + val outcome = sendOrQueue( + send = { api.unflag(trackId) }, + queue = { mutationQueue.enqueueQuarantineUnflag(trackId) }, + onRefused = { e -> refused("unflag", trackId, e) }, + ) + return if (outcome == WriteOutcome.Queued) UnflagOutcome.QUEUED else UnflagOutcome.ACCEPTED + } + + /** + * The server said no (say, the track is gone). Nothing is queued, since a + * replay would be refused too; the next refresh shows the server's list. + */ + private fun refused(what: String, trackId: String, e: HttpException): WriteOutcome { + Timber.i(e, "quarantine: %s %s refused (%d)", what, trackId, e.code()) + return WriteOutcome.Refused } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/requests/data/RequestsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/requests/data/RequestsRepository.kt deleted file mode 100644 index 4814e651..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/requests/data/RequestsRepository.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.fabledsword.minstrel.requests.data - -import com.fabledsword.minstrel.api.endpoints.RequestsApi -import com.fabledsword.minstrel.cache.mutations.MutationQueue -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.Retrofit -import retrofit2.create -import java.io.IOException -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Outcome of a [RequestsRepository.cancel] call. Mirrors the - * [com.fabledsword.minstrel.likes.data.UnflagOutcome] / etc. shape. - */ -enum class CancelOutcome { Synced, Queued } - -/** - * Read-through accessor for the caller's own requests + - * cancel-while-pending write. No Room caching. Cancel is offline-first: - * direct REST on the happy - * path, MutationQueue fallback on transport failure so the user's - * intent persists across connectivity loss. - */ -@Singleton -class RequestsRepository @Inject constructor( - private val mutationQueue: MutationQueue, - retrofit: Retrofit, -) { - private val api: RequestsApi = retrofit.create() - - suspend fun listMine(): List = - api.listMine().map { it.toDomain() } - - /** - * Cancels a pending request. On 2xx, returns the canonical - * cancelled row from the server (status=rejected). On transport - * failure, enqueues a REQUEST_CANCEL mutation for later replay - * and returns null — the caller's optimistic UI removal already - * reflects the user's intent, and the next listMine() refetch - * (post-replay) will surface the canonical row. - */ - suspend fun cancel(id: String): Pair = try { - CancelOutcome.Synced to api.cancel(id).toDomain() - } catch ( - @Suppress("SwallowedException") _: IOException, - ) { - mutationQueue.enqueueRequestCancel(id) - CancelOutcome.Queued to null - } -} - -// ── Mappers (internal — wire stays out of UI) ── - -private fun RequestWire.toDomain(): RequestRef = RequestRef( - id = id, - userId = userId, - status = RequestStatus.fromWire(status), - kind = kind, - artistName = artistName, - albumTitle = albumTitle, - trackTitle = trackTitle, - requestedAt = requestedAt, - decidedAt = decidedAt, - notes = notes, - importedAlbumCount = importedAlbumCount, - importedTrackCount = importedTrackCount, - matchedTrackId = matchedTrackId, - matchedAlbumId = matchedAlbumId, - matchedArtistId = matchedArtistId, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsScreen.kt deleted file mode 100644 index 03d13202..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsScreen.kt +++ /dev/null @@ -1,313 +0,0 @@ -@file:Suppress("TooManyFunctions") // Compose screen + private helper composables - -package com.fabledsword.minstrel.requests.ui - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.layout.size -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.AssistChip -import androidx.compose.material3.Button -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.hilt.navigation.compose.hiltViewModel -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.navigation.NavHostController -import com.composables.icons.lucide.Disc3 -import com.composables.icons.lucide.LibraryBig -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.Music -import com.composables.icons.lucide.Play -import com.composables.icons.lucide.X -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.nav.AlbumDetail -import com.fabledsword.minstrel.shared.UiState -import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.Requests -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets -import com.fabledsword.minstrel.shared.widgets.EmptyState -import com.fabledsword.minstrel.shared.widgets.ErrorRetry -import com.fabledsword.minstrel.shared.widgets.LoadingCentered -import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar -import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold - -@Composable -fun RequestsScreen( - navController: NavHostController, - viewModel: RequestsViewModel = hiltViewModel(), -) { - val state by viewModel.uiState.collectAsStateWithLifecycle() - Scaffold( - contentWindowInsets = ShellContentWindowInsets, - modifier = Modifier.fillMaxSize(), - topBar = { - MinstrelTopAppBar( - title = "Your requests", - navController = navController, - currentRouteName = Requests::class.qualifiedName, - onBack = { navController.popBackStack() }, - ) - }, - ) { inner -> - PullToRefreshScaffold( - onRefresh = { viewModel.refresh().join() }, - modifier = Modifier.fillMaxSize().padding(inner), - ) { - when (val s = state) { - UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "Nothing requested yet", - body = "Use Discover to ask for new music; your " + - "requests show up here.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load requests", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> RequestList( - rows = s.data, - onCancel = viewModel::cancel, - onListen = { id -> navController.navigate(id) }, - ) - } - } - } -} - -@Composable -private fun RequestList( - rows: List, - onCancel: (String) -> Unit, - onListen: (Any) -> Unit, -) { - LazyColumn(modifier = Modifier.fillMaxSize()) { - items(items = rows, key = { it.id }) { req -> - RequestRow( - req = req, - onCancel = { onCancel(req.id) }, - onListen = req.listenRoute()?.let { route -> { onListen(route) } }, - ) - HorizontalDivider() - } - } -} - -@Composable -private fun RequestRow( - req: RequestRef, - onCancel: () -> Unit, - onListen: (() -> Unit)?, -) { - var showCancelConfirm by remember { mutableStateOf(false) } - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - KindAvatar(kind = req.kind) - RequestRowBody(req = req, modifier = Modifier.weight(1f)) - RequestRowAction( - req = req, - onListen = onListen, - onAskCancel = { showCancelConfirm = true }, - ) - } - if (showCancelConfirm) { - CancelConfirmDialog( - displayName = req.displayName, - onConfirm = { - showCancelConfirm = false - onCancel() - }, - onDismiss = { showCancelConfirm = false }, - ) - } -} - -@Composable -private fun RequestRowBody(req: RequestRef, modifier: Modifier = Modifier) { - Column(modifier = modifier) { - Text( - text = req.displayName, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Row( - modifier = Modifier.padding(top = 4.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - StatusPill(status = req.status) - KindPill(label = req.kind) - } - val progress = req.ingestProgressText() - if (progress != null) { - Text( - text = progress, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 4.dp), - ) - } - if (req.status == RequestStatus.REJECTED && !req.notes.isNullOrEmpty()) { - Text( - text = req.notes, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 4.dp), - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - } -} - -@Composable -private fun RequestRowAction( - req: RequestRef, - onListen: (() -> Unit)?, - onAskCancel: () -> Unit, -) { - when { - onListen != null -> OutlinedButton(onClick = onListen) { - Icon( - Lucide.Play, - contentDescription = null, - modifier = Modifier.size(16.dp).padding(end = 4.dp), - ) - Text("Listen") - } - req.status == RequestStatus.PENDING -> TextButton(onClick = onAskCancel) { - Icon(Lucide.X, contentDescription = null, modifier = Modifier.padding(end = 4.dp)) - Text("Cancel") - } - } -} - -@Composable -private fun CancelConfirmDialog( - displayName: String, - onConfirm: () -> Unit, - onDismiss: () -> Unit, -) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Cancel request?") }, - text = { Text("Cancel “$displayName”? Your request is withdrawn.") }, - confirmButton = { - Button(onClick = onConfirm) { Text("Cancel request") } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text("Keep") } - }, - ) -} - -@Composable -private fun KindAvatar(kind: String) { - // Icons: disc-3 for artist, library-big for album, music for track. - val icon = when (kind) { - "artist" -> Lucide.Disc3 - "album" -> Lucide.LibraryBig - "track" -> Lucide.Music - else -> Lucide.Music - } - Icon( - imageVector = icon, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(28.dp), - ) -} - -/** - * Most-specific listenable detail-screen route for a completed - * request, or null when nothing's been matched / the status isn't - * completed. Track-level matches resolve to AlbumDetail since the - * client has no TrackDetail screen. - */ -private fun RequestRef.listenRoute(): Any? = when { - status != RequestStatus.COMPLETED -> null - !matchedAlbumId.isNullOrEmpty() -> AlbumDetail(matchedAlbumId) - !matchedArtistId.isNullOrEmpty() -> ArtistDetail(matchedArtistId) - else -> null -} - -/** - * "2 albums · 14 tracks ingested" — null when both counts are zero. - * Singular when the count is 1 ("1 album · 1 track ingested"). - */ -private fun RequestRef.ingestProgressText(): String? { - if (importedAlbumCount == 0 && importedTrackCount == 0) return null - val parts = buildList { - if (importedAlbumCount > 0) { - add( - "$importedAlbumCount ${if (importedAlbumCount == 1) "album" else "albums"}", - ) - } - if (importedTrackCount > 0) { - add( - "$importedTrackCount ${if (importedTrackCount == 1) "track" else "tracks"}", - ) - } - } - return "${parts.joinToString(" · ")} ingested" -} - -@Composable -private fun StatusPill(status: RequestStatus) { - val (label, isError) = when (status) { - RequestStatus.PENDING -> "pending" to false - RequestStatus.APPROVED -> "approved" to false - RequestStatus.COMPLETED -> "completed" to false - RequestStatus.REJECTED -> "rejected" to true - RequestStatus.FAILED -> "failed" to true - RequestStatus.UNKNOWN -> "unknown" to false - } - val color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary - AssistChip( - onClick = {}, - enabled = false, - label = { Text(label, color = color) }, - ) -} - -@Composable -private fun KindPill(label: String) { - AssistChip( - onClick = {}, - enabled = false, - label = { - Text( - label, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - ) -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsViewModel.kt deleted file mode 100644 index d1c3a82d..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsViewModel.kt +++ /dev/null @@ -1,177 +0,0 @@ -package com.fabledsword.minstrel.requests.ui - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.fabledsword.minstrel.api.ErrorCopy -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.recoveries -import com.fabledsword.minstrel.events.EventsStream -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.requests.data.CancelOutcome -import com.fabledsword.minstrel.requests.data.RequestsRepository -import com.fabledsword.minstrel.shared.UiState -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import javax.inject.Inject - -private val RELEVANT_EVENT_KINDS = setOf("request.status_changed") - -// Cadence for in-flight request polling — matches the web client: -// fast enough to feel live, slow enough not to hammer the server. -private const val POLL_INTERVAL_MS = 12_000L - -@HiltViewModel -class RequestsViewModel @Inject constructor( - private val repository: RequestsRepository, - private val eventsStream: EventsStream, - networkStatus: NetworkStatusController, -) : ViewModel() { - - private val internal = MutableStateFlow>>(UiState.Loading) - val uiState: StateFlow>> = internal.asStateFlow() - - init { - refresh() - // SSE push: reconciler completions arrive here; reload silently so the - // row updates in place rather than flashing the loading spinner. - viewModelScope.launch { - eventsStream.events - .filter { it.kind in RELEVANT_EVENT_KINDS } - .collect { silentReload() } - } - viewModelScope.launch { pollWhileInFlight() } - // Screen-level auto-recovery: a load that failed while - // the server was unreachable heals the moment health returns, without - // waiting for the next poll tick. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is UiState.Error) silentReload() - } - } - } - - fun refresh(): Job = viewModelScope.launch { - internal.value = UiState.Loading - try { - val rows = repository.listMine() - internal.value = if (rows.isEmpty()) { - UiState.Empty - } else { - UiState.Success(rows) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = UiState.Error(ErrorCopy.fromThrowable(e)) - } - } - - /** - * Auto-poll while any request is mid-ingest (status APPROVED), matching the - * web client. Reloads silently every [POLL_INTERVAL_MS] and pauses - * when nothing is in-flight — complements the SSE push so progress stays - * live even if the event stream drops. - */ - private suspend fun pollWhileInFlight() { - while (true) { - // Also retry from a failed load: from UiState.Error - // the in-flight predicate can never become true, so without this - // the poll never self-heals the screen — e.g. after a transient - // 500 that health monitoring (transport-level) never saw. - if (hasInFlightRequest() || internal.value is UiState.Error) { - silentReload() - } - delay(POLL_INTERVAL_MS) - } - } - - private fun hasInFlightRequest(): Boolean { - val state = internal.value - return state is UiState.Success && - state.data.any { it.status == RequestStatus.APPROVED } - } - - /** - * Reload the list in place without flipping to Loading — used by the poll - * loop and the SSE collector so visible rows update without a spinner - * flash. A transient failure keeps the current view; the next reload wins. - */ - private suspend fun silentReload() { - try { - val rows = repository.listMine() - internal.value = if (rows.isEmpty()) UiState.Empty else UiState.Success(rows) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Keep the current view; the next poll / SSE / pull reconciles. - } - } - - /** - * Optimistically removes [id] from the success list so the row - * disappears immediately; on server-side success the row is - * replaced by the canonical cancelled state from the return value. - * On error rolls back by refetching the list. - */ - fun cancel(id: String) { - val before = internal.value - if (before is UiState.Success) { - val filtered = before.data.filterNot { it.id == id } - internal.value = if (filtered.isEmpty()) { - UiState.Empty - } else { - UiState.Success(filtered) - } - } - viewModelScope.launch { - try { - val (outcome, updated) = repository.cancel(id) - if (updated != null) { - internal.update { state -> - if (state !is UiState.Success) { - // Mid-refresh — let the refresh result win, but - // splice the cancelled row in so it shows the new - // status if the user re-pulls. - UiState.Success(listOf(updated)) - } else { - // Re-insert the cancelled row in its old position - // would require remembering the prior ordering; - // simpler to refetch in the background. - state - } - } - } - // Only refetch on the Synced outcome. The - // Queued path is offline by definition — the optimistic - // removal at the top of cancel() is correct, and a - // refresh() call here would either (a) get the - // not-yet-delivered cancelled row back from the server - // and snap it into the list (confusing), or (b) fail - // with a transport error and flip the whole screen to - // UiState.Error, making the user think the cancel - // failed. The mutation queue will replay the cancel - // when connectivity returns; the next on-screen refresh - // (pull-to-refresh, navigation back) reconciles. - if (outcome == CancelOutcome.Synced) { - refresh() - } - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Roll back by re-fetching; the failed cancel might - // already be visible to the server (eventual consistency) - // or not at all (transport drop). The refetch makes - // local state match either outcome. - refresh() - } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt index 24a08477..fc090c84 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt @@ -10,6 +10,7 @@ import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.search.data.SearchRepository import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -20,6 +21,7 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import timber.log.Timber import javax.inject.Inject private const val DEBOUNCE_MS = 250L @@ -104,21 +106,29 @@ class SearchViewModel @Inject constructor( } /** - * Tapping a search result builds a queue from the full visible - * track-results list starting at the tapped entry. - * Falls back to single-track playback when the loaded state isn't - * a Success (shouldn't happen in normal flow but keeps the call - * safe). + * Tapping a search result starts radio seeded from it: the tapped song + * plays first, then songs like it. The list of matches for a few typed + * words is rarely what someone wants to hear next. The web's search does + * the same (radioFromRow). + * + * When radio can't be had (offline, or the server returns nothing), the + * tapped song plays on its own, so a tap always plays what was tapped. */ fun playTrack(track: TrackRef) { if (track.streamUrl.isEmpty()) return - val loaded = internal.value.results as? SearchResultsState.Loaded - val playable = loaded?.response?.tracks - ?.filter { it.streamUrl.isNotEmpty() } - ?.takeIf { it.isNotEmpty() } - ?: listOf(track) - val startIndex = playable.indexOfFirst { it.id == track.id }.coerceAtLeast(0) - player.setQueue(playable, initialIndex = startIndex, source = "search") + viewModelScope.launch { + val started = try { + player.playRadio(track.id) + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + Timber.i(e, "search: radio for %s failed; playing the track alone", track.id) + false + } + if (!started) player.setQueue(listOf(track), initialIndex = 0, source = "search") + } } private suspend fun runSearch(q: String) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt index 634f8483..77b70534 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt @@ -30,9 +30,13 @@ class MeRepository @Inject constructor(retrofit: Retrofit) { UpdateProfileRequest(displayName = displayName, email = email), ).toDomain() - suspend fun changePassword(current: String, next: String) { + suspend fun changePassword(current: String, next: String, signOutSubsonic: Boolean = false) { api.changePassword( - ChangePasswordRequest(currentPassword = current, newPassword = next), + ChangePasswordRequest( + currentPassword = current, + newPassword = next, + signOutSubsonic = signOutSubsonic, + ), ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt index 52d2a57f..34a99fbb 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt @@ -5,7 +5,8 @@ import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.mutations.MutationKind import com.fabledsword.minstrel.cache.mutations.MutationQueue -import kotlinx.coroutines.CancellationException +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import kotlinx.coroutines.flow.StateFlow import retrofit2.Retrofit import retrofit2.create @@ -53,15 +54,13 @@ class NormalizationRepository @Inject constructor( mutationQueue.enqueueNormalizationSet(next) return } - try { - api.putNormalization(next) - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "normalization: PUT failed; queued for replay") - mutationQueue.enqueueNormalizationSet(next) - } + sendOrQueue( + send = { api.putNormalization(next) }, + queue = { mutationQueue.enqueueNormalizationSet(next) }, + onRefused = { e -> + Timber.i(e, "normalization: PUT refused (%d)", e.code()) + WriteOutcome.Refused + }, + ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt index 89718579..3cce4374 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt @@ -1,68 +1,44 @@ package com.fabledsword.minstrel.settings.ui -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ElevatedCard import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.fabledsword.minstrel.models.ListenBrainzStatus +import com.fabledsword.minstrel.theme.Muted +import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SwitchRow @Composable fun ListenBrainzCard(viewModel: ListenBrainzViewModel = hiltViewModel()) { val state by viewModel.state.collectAsStateWithLifecycle() - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), + Section("ListenBrainz") { + SettingsLoad( + isLoading = state.isLoading, + loadError = state.loadError, + what = "ListenBrainz", + onRetry = viewModel::refresh, ) { - Text( - text = "ListenBrainz", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, + ListenBrainzForm( + status = state.status, + tokenInput = state.tokenInput, + isSaving = state.isSaving, + message = state.message, + onTokenChange = viewModel::setTokenInput, + onSaveToken = viewModel::saveToken, + onSetEnabled = viewModel::setEnabled, ) - Text( - text = "Send your plays to ListenBrainz so you can keep your " + - "scrobble history portable. Get a token at " + - "listenbrainz.org/profile — it's stored encrypted on " + - "the server and never read back.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (state.isLoading) { - Box( - modifier = Modifier.fillMaxWidth().padding(16.dp), - contentAlignment = Alignment.Center, - ) { CircularProgressIndicator() } - } else { - ListenBrainzForm( - status = state.status, - tokenInput = state.tokenInput, - isSaving = state.isSaving, - message = state.message, - onTokenChange = viewModel::setTokenInput, - onSaveToken = viewModel::saveToken, - onSetEnabled = viewModel::setEnabled, - ) - } } } } @@ -77,25 +53,25 @@ private fun ListenBrainzForm( onSaveToken: () -> Unit, onSetEnabled: (Boolean) -> Unit, ) { - TokenField( - tokenInput = tokenInput, - tokenSet = status?.tokenSet == true, - onChange = onTokenChange, + val tokenSet = status?.tokenSet == true + SwitchRow( + title = "Send my plays to ListenBrainz", + summary = when { + !tokenSet -> "Save a token first" + status?.lastScrobbledAt != null -> "Last scrobble: ${status.lastScrobbledAt}" + else -> null + }, + checked = status?.enabled == true, + onCheckedChange = onSetEnabled, + enabled = !isSaving && tokenSet, ) - Spacer(Modifier.height(4.dp)) + TokenField(tokenInput = tokenInput, tokenSet = tokenSet, onChange = onTokenChange) SaveTokenButton( isSaving = isSaving, enabled = !isSaving && tokenInput.isNotBlank(), onClick = onSaveToken, ) - EnabledRow(status = status, isSaving = isSaving, onSetEnabled = onSetEnabled) - if (message != null) { - Text( - text = message, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + if (message != null) Muted(message) } @Composable @@ -105,6 +81,7 @@ private fun TokenField(tokenInput: String, tokenSet: Boolean, onChange: (String) onValueChange = onChange, label = { Text(if (tokenSet) "Replace token" else "Token") }, placeholder = { Text(if (tokenSet) "Token saved" else "") }, + supportingText = { Text("From listenbrainz.org/profile; never shown again") }, modifier = Modifier.fillMaxWidth(), singleLine = true, visualTransformation = PasswordVisualTransformation(), @@ -129,36 +106,3 @@ private fun SaveTokenButton(isSaving: Boolean, enabled: Boolean, onClick: () -> Text(if (isSaving) "Saving…" else "Save token") } } - -@Composable -private fun EnabledRow( - status: ListenBrainzStatus?, - isSaving: Boolean, - onSetEnabled: (Boolean) -> Unit, -) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Column(modifier = Modifier.padding(end = 12.dp)) { - Text( - text = "Send my plays to ListenBrainz", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - if (status?.lastScrobbledAt != null) { - Text( - text = "Last scrobble: ${status.lastScrobbledAt}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - Switch( - checked = status?.enabled == true, - onCheckedChange = onSetEnabled, - enabled = !isSaving && status?.tokenSet == true, - ) - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt index 6e7bcb41..551378cd 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt @@ -19,6 +19,8 @@ data class ListenBrainzUiState( val status: ListenBrainzStatus? = null, val tokenInput: String = "", val message: String? = null, + /** Why the last load failed; the card then offers Try again instead of the form. */ + val loadError: String? = null, ) /** @@ -47,7 +49,7 @@ class ListenBrainzViewModel @Inject constructor( fun refresh() { viewModelScope.launch { - internal.update { it.copy(isLoading = true, message = null) } + internal.update { it.copy(isLoading = true, message = null, loadError = null) } try { val s = repository.getListenBrainz() internal.update { it.copy(isLoading = false, status = s) } @@ -57,7 +59,7 @@ class ListenBrainzViewModel @Inject constructor( internal.update { it.copy( isLoading = false, - message = ErrorCopy.fromThrowable(e), + loadError = ErrorCopy.fromThrowable(e), ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt index 0e9076ee..eae7bab6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt @@ -1,30 +1,15 @@ package com.fabledsword.minstrel.settings.ui -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.material3.ElevatedCard -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SegmentedButton -import androidx.compose.material3.SegmentedButtonDefaults -import androidx.compose.material3.SingleChoiceSegmentedButtonRow -import androidx.compose.material3.Switch -import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.fabledsword.minstrel.settings.data.NormalizationBoost import com.fabledsword.minstrel.settings.data.NormalizationMode import com.fabledsword.minstrel.settings.data.NormalizationPrefs +import com.fabledsword.minstrel.theme.ChoiceRow +import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SwitchRow /** * Volume leveling. The choice is stored on the server, so the @@ -36,98 +21,39 @@ fun NormalizationCard(viewModel: NormalizationViewModel = hiltViewModel()) { NormalizationCardContent(prefs = prefs, onChange = viewModel::update) } -@OptIn(ExperimentalMaterial3Api::class) @Composable internal fun NormalizationCardContent( prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -> Unit, ) { - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = "Volume leveling", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Hint(modeHint(prefs.mode)) - val modes = NormalizationMode.entries - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - modes.forEachIndexed { index, mode -> - SegmentedButton( - selected = mode == prefs.mode, - onClick = { onChange(prefs.copy(mode = mode)) }, - shape = SegmentedButtonDefaults.itemShape( - index = index, - count = modes.size, - ), - ) { Text(modeLabel(mode)) } - } - } - if (prefs.mode != NormalizationMode.OFF) { - TargetRow(prefs = prefs, onChange = onChange) - BoostRow(prefs = prefs, onChange = onChange) - } - } - } -} - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun TargetRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -> Unit) { - Text( - text = "Target loudness", - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - ) - val targets = NormalizationPrefs.TARGETS - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - targets.forEachIndexed { index, lufs -> - SegmentedButton( - selected = lufs == prefs.targetLufs, - onClick = { onChange(prefs.copy(targetLufs = lufs)) }, - shape = SegmentedButtonDefaults.itemShape( - index = index, - count = targets.size, - ), - ) { Text("$lufs LUFS") } - } - } -} - -@Composable -private fun BoostRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -> Unit) { - Row(verticalAlignment = Alignment.CenterVertically) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = "Boost quiet tracks fully", - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - ) - Hint("A limiter catches the peaks.") - } - Spacer(Modifier.size(12.dp)) - Switch( - checked = prefs.boost == NormalizationBoost.LIMITER, - onCheckedChange = { on -> - val boost = if (on) NormalizationBoost.LIMITER else NormalizationBoost.HEADROOM - onChange(prefs.copy(boost = boost)) - }, + Section("Volume leveling") { + ChoiceRow( + title = "Leveling", + summary = modeHint(prefs.mode), + options = NormalizationMode.entries.map { it to modeLabel(it) }, + selected = prefs.mode, + onSelect = { onChange(prefs.copy(mode = it)) }, ) + if (prefs.mode != NormalizationMode.OFF) { + ChoiceRow( + title = "Target loudness", + options = NormalizationPrefs.TARGETS.map { it to "$it LUFS" }, + selected = prefs.targetLufs, + onSelect = { onChange(prefs.copy(targetLufs = it)) }, + ) + SwitchRow( + title = "Boost quiet tracks fully", + summary = "A limiter catches the peaks", + checked = prefs.boost == NormalizationBoost.LIMITER, + onCheckedChange = { on -> + val boost = if (on) NormalizationBoost.LIMITER else NormalizationBoost.HEADROOM + onChange(prefs.copy(boost = boost)) + }, + ) + } } } -@Composable -private fun Hint(text: String) { - Text( - text = text, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) -} - private fun modeLabel(mode: NormalizationMode): String = when (mode) { NormalizationMode.OFF -> "Off" NormalizationMode.AUTO -> "Auto" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt index f54e2b02..03cd431a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt @@ -1,7 +1,5 @@ package com.fabledsword.minstrel.settings.ui -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -10,7 +8,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ElevatedCard import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text @@ -22,59 +19,54 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.fabledsword.minstrel.auth.PasswordRules +import com.fabledsword.minstrel.theme.Muted +import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SwitchRow @Composable fun PasswordCard(viewModel: PasswordViewModel = hiltViewModel()) { val state by viewModel.state.collectAsStateWithLifecycle() - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), + Section("Password") { + PasswordField( + value = state.current, + label = "Current password", + onChange = viewModel::setCurrent, + ) + PasswordField( + value = state.next, + label = "New password", + onChange = viewModel::setNext, + hint = PasswordRules.HINT, + ) + PasswordField( + value = state.confirm, + label = "Confirm new password", + onChange = viewModel::setConfirm, + ) + SwitchRow( + title = "Sign out Subsonic apps too", + summary = "Your API token and Subsonic password stop working.", + checked = state.signOutSubsonic, + onCheckedChange = viewModel::setSignOutSubsonic, + ) + Spacer(Modifier.height(4.dp)) + Button( + onClick = viewModel::change, + enabled = !state.isChanging, + modifier = Modifier.fillMaxWidth(), ) { - Text( - text = "Password", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - PasswordField( - value = state.current, - label = "Current password", - onChange = viewModel::setCurrent, - ) - PasswordField( - value = state.next, - label = "New password", - onChange = viewModel::setNext, - ) - PasswordField( - value = state.confirm, - label = "Confirm new password", - onChange = viewModel::setConfirm, - ) - Spacer(Modifier.height(4.dp)) - Button( - onClick = viewModel::change, - enabled = !state.isChanging, - modifier = Modifier.fillMaxWidth(), - ) { - if (state.isChanging) { - CircularProgressIndicator( - modifier = Modifier.size(16.dp), - strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.onPrimary, - ) - Spacer(Modifier.size(8.dp)) - } - Text(if (state.isChanging) "Changing…" else "Change password") - } - if (state.message != null) { - Text( - text = state.message!!, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + if (state.isChanging) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.onPrimary, ) + Spacer(Modifier.size(8.dp)) } + Text(if (state.isChanging) "Changing…" else "Change password") } + state.message?.let { Muted(it) } } } @@ -83,11 +75,13 @@ private fun PasswordField( value: String, label: String, onChange: (String) -> Unit, + hint: String? = null, ) { OutlinedTextField( value = value, onValueChange = onChange, label = { Text(label) }, + supportingText = hint?.let { { Text(it) } }, modifier = Modifier.fillMaxWidth(), singleLine = true, visualTransformation = PasswordVisualTransformation(), diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt index ea50c42d..ee9bf071 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt @@ -3,6 +3,7 @@ package com.fabledsword.minstrel.settings.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fabledsword.minstrel.api.ErrorCopy +import com.fabledsword.minstrel.auth.PasswordRules import com.fabledsword.minstrel.settings.data.MeRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow @@ -16,6 +17,7 @@ data class PasswordUiState( val current: String = "", val next: String = "", val confirm: String = "", + val signOutSubsonic: Boolean = false, val isChanging: Boolean = false, val message: String? = null, ) @@ -37,13 +39,16 @@ class PasswordViewModel @Inject constructor( fun setCurrent(value: String) = internal.update { it.copy(current = value, message = null) } fun setNext(value: String) = internal.update { it.copy(next = value, message = null) } fun setConfirm(value: String) = internal.update { it.copy(confirm = value, message = null) } + fun setSignOutSubsonic(value: Boolean) = + internal.update { it.copy(signOutSubsonic = value, message = null) } fun change() { val s = internal.value val validationError: String? = when { s.isChanging -> "" // sentinel: silent no-op s.current.isEmpty() || s.next.isEmpty() -> "All fields required." - s.next != s.confirm -> "New passwords do not match." + !PasswordRules.isLongEnough(s.next) -> PasswordRules.TOO_SHORT + s.next != s.confirm -> PasswordRules.DIFFER else -> null } if (validationError != null) { @@ -55,9 +60,15 @@ class PasswordViewModel @Inject constructor( viewModelScope.launch { internal.update { it.copy(isChanging = true, message = null) } try { - repository.changePassword(current = s.current, next = s.next) + repository.changePassword( + current = s.current, + next = s.next, + signOutSubsonic = s.signOutSubsonic, + ) + val signedOut = + if (s.signOutSubsonic) "Your other devices and Subsonic apps" else "Your other devices" internal.update { - PasswordUiState(message = "Password changed. Your other devices have been signed out.") + PasswordUiState(message = "Password changed. $signedOut have been signed out.") } } catch ( @Suppress("TooGenericExceptionCaught") e: Throwable, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileCard.kt index f76661fd..db426559 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileCard.kt @@ -1,56 +1,42 @@ package com.fabledsword.minstrel.settings.ui -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ElevatedCard import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.fabledsword.minstrel.theme.Muted +import com.fabledsword.minstrel.theme.Section @Composable fun ProfileCard(viewModel: ProfileViewModel = hiltViewModel()) { val state by viewModel.state.collectAsStateWithLifecycle() - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), + Section("Profile") { + SettingsLoad( + isLoading = state.isLoading, + loadError = state.loadError, + what = "your profile", + onRetry = viewModel::refresh, ) { - Text( - text = "Profile", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, + ProfileForm( + displayName = state.displayName, + email = state.email, + isSaving = state.isSaving, + message = state.message, + onDisplayNameChange = viewModel::setDisplayName, + onEmailChange = viewModel::setEmail, + onSave = viewModel::save, ) - if (state.isLoading) { - Box( - modifier = Modifier.fillMaxWidth().padding(16.dp), - contentAlignment = Alignment.Center, - ) { CircularProgressIndicator() } - } else { - ProfileForm( - displayName = state.displayName, - email = state.email, - isSaving = state.isSaving, - message = state.message, - onDisplayNameChange = viewModel::setDisplayName, - onEmailChange = viewModel::setEmail, - onSave = viewModel::save, - ) - } } } } @@ -95,11 +81,5 @@ private fun ProfileForm( } Text(if (isSaving) "Saving…" else "Save profile") } - if (message != null) { - Text( - text = message, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + if (message != null) Muted(message) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt index d375a7f1..052968f1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt @@ -20,6 +20,8 @@ data class ProfileUiState( val email: String = "", val loadedProfile: MyProfile? = null, val message: String? = null, + /** Why the last load failed; the card then offers Try again instead of the form. */ + val loadError: String? = null, ) /** @@ -55,7 +57,7 @@ class ProfileViewModel @Inject constructor( fun refresh() { viewModelScope.launch { - internal.update { it.copy(isLoading = true, message = null) } + internal.update { it.copy(isLoading = true, message = null, loadError = null) } try { val profile = repository.getProfile() internal.update { @@ -72,7 +74,7 @@ class ProfileViewModel @Inject constructor( internal.update { it.copy( isLoading = false, - message = ErrorCopy.fromThrowable(e), + loadError = ErrorCopy.fromThrowable(e), ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsLoad.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsLoad.kt new file mode 100644 index 00000000..3854d46d --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsLoad.kt @@ -0,0 +1,51 @@ +package com.fabledsword.minstrel.settings.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.TriangleAlert +import com.fabledsword.minstrel.theme.SettingRow + +/** + * A settings card's load state, shared by the cards that fetch what they + * show (Profile, ListenBrainz). While loading it shows a spinner; when the + * load failed it shows one row saying so, with Try again; only once the + * data is in does it show [content]. + * + * The form is held back on a failed load on purpose: its fields would be + * empty rather than the saved values, and saving them would overwrite the + * real settings with blanks. The web's settings cards do the same + * (SettingsLoadStatus). + */ +@Composable +fun SettingsLoad( + isLoading: Boolean, + loadError: String?, + what: String, + onRetry: () -> Unit, + content: @Composable () -> Unit, +) { + when { + isLoading -> Box( + modifier = Modifier.fillMaxWidth().padding(16.dp), + contentAlignment = Alignment.Center, + ) { CircularProgressIndicator() } + loadError != null -> SettingRow( + title = "Couldn't load $what", + summary = loadError, + icon = Lucide.TriangleAlert, + tone = MaterialTheme.colorScheme.error, + trailing = { TextButton(onClick = onRetry) { Text("Try again") } }, + ) + else -> content() + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt index 349f9b6c..368dd5d3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt @@ -1,63 +1,45 @@ -@file:Suppress("TooManyFunctions") // Settings screen + per-card helper composables +@file:Suppress("TooManyFunctions") // Settings screen + per-section composables package com.fabledsword.minstrel.settings.ui -import androidx.compose.foundation.clickable -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ElevatedCard -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold -import androidx.compose.material3.SegmentedButton -import androidx.compose.material3.SegmentedButtonDefaults -import androidx.compose.material3.SingleChoiceSegmentedButtonRow -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.composables.icons.lucide.Bell -import com.composables.icons.lucide.ChevronRight -import com.composables.icons.lucide.ListMusic import com.composables.icons.lucide.LogOut import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Shield import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.NotificationSettings -import com.fabledsword.minstrel.nav.Requests -import com.fabledsword.minstrel.nav.Settings as SettingsRoute import com.fabledsword.minstrel.nav.ServerUrl -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets +import com.fabledsword.minstrel.nav.Settings as SettingsRoute +import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets +import com.fabledsword.minstrel.theme.ChoiceRow +import com.fabledsword.minstrel.theme.RowChevron +import com.fabledsword.minstrel.theme.RowSpinner +import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SectionEdge +import com.fabledsword.minstrel.theme.SectionGap +import com.fabledsword.minstrel.theme.SettingRow +import com.fabledsword.minstrel.theme.SwitchRow import com.fabledsword.minstrel.theme.ThemeMode import com.fabledsword.minstrel.theme.ThemePreferenceViewModel import com.fabledsword.minstrel.update.ui.AppVersionCard @@ -99,7 +81,6 @@ fun SettingsScreen( state = state, themeMode = themeMode, onPickTheme = themeVm::setThemeMode, - onNavToRequests = { navController.navigate(Requests) }, onNavToNotifications = { navController.navigate(NotificationSettings) }, onNavToAdmin = { navController.navigate(Admin) }, onToggleDiagnostics = viewModel::setDiagnosticsOptOut, @@ -119,11 +100,10 @@ fun SettingsScreen( @Composable private fun SettingsList( - inner: androidx.compose.foundation.layout.PaddingValues, + inner: PaddingValues, state: SettingsState, themeMode: ThemeMode, onPickTheme: (ThemeMode) -> Unit, - onNavToRequests: () -> Unit, onNavToNotifications: () -> Unit, onNavToAdmin: () -> Unit, onToggleDiagnostics: (Boolean) -> Unit, @@ -134,155 +114,75 @@ private fun SettingsList( .fillMaxSize() .padding(inner) .verticalScroll(rememberScrollState()) - .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(16.dp), + .padding(horizontal = SectionEdge, vertical = SectionEdge), + verticalArrangement = Arrangement.spacedBy(SectionGap), ) { - AccountCard( - username = state.username, - isAdmin = state.isAdmin, - serverUrl = state.serverUrl, + AccountSection( + state = state, + onNavToNotifications = onNavToNotifications, + onNavToAdmin = onNavToAdmin, + onSignOutClick = onSignOutClick, ) - NavTile( - icon = Lucide.ListMusic, - title = "My requests", - subtitle = "Track what you've asked Minstrel to add", - onClick = onNavToRequests, - ) - NavTile( - icon = Lucide.Bell, - title = "Notifications", - subtitle = "What reaches you, and where", - onClick = onNavToNotifications, - ) - if (state.isAdmin) { - NavTile( - icon = Lucide.Shield, - title = "Admin", - subtitle = "Manage requests, quarantine, and users", - onClick = onNavToAdmin, - ) - } ProfileCard() PasswordCard() ListenBrainzCard() if (state.diagnosticsEnabledByAdmin) { - DiagnosticsCard( - optOut = state.diagnosticsOptOut, - onToggle = onToggleDiagnostics, - ) + DiagnosticsSection(optOut = state.diagnosticsOptOut, onToggle = onToggleDiagnostics) } NormalizationCard() - AppearanceCard(themeMode = themeMode, onPick = onPickTheme) + AppearanceSection(themeMode = themeMode, onPick = onPickTheme) StorageCard() AboutCard() - SignOutButton(isSigningOut = state.isSigningOut, onSignOut = onSignOutClick) } } @Composable private fun SignOutConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Sign out?") }, - text = { - Text( - "Sign out of this server? Your downloaded music and " + - "settings on this device will be removed.", - ) - }, - confirmButton = { - Button( - onClick = onConfirm, - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.errorContainer, - contentColor = MaterialTheme.colorScheme.onErrorContainer, - ), - ) { Text("Sign out") } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text("Cancel") } - }, + ConfirmDestructiveDialog( + title = "Sign out?", + text = "Sign out of this server? Your downloaded music and " + + "settings on this device will be removed.", + confirmLabel = "Sign out", + onConfirm = onConfirm, + onDismiss = onDismiss, ) } +/** Who is signed in, where, the screens that belong to the account, and signing out. */ @Composable -private fun NavTile( - icon: ImageVector, - title: String, - subtitle: String, - onClick: () -> Unit, +private fun AccountSection( + state: SettingsState, + onNavToNotifications: () -> Unit, + onNavToAdmin: () -> Unit, + onSignOutClick: () -> Unit, ) { - ElevatedCard( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick), - ) { - Row( - modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = icon, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - ) - Spacer(Modifier.size(16.dp)) - Column(modifier = Modifier.weight(1f)) { - Text( - text = title, - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - text = subtitle, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Icon( - imageVector = Lucide.ChevronRight, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -@Composable -private fun AccountCard(username: String, isAdmin: Boolean, serverUrl: String) { - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text( - text = "Account", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - val adminTag = if (isAdmin) " · admin" else "" - Text( - text = when { - username.isEmpty() -> "Signed in" - else -> "Signed in as $username$adminTag" - }, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(8.dp)) - Text( - text = "Server", - style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - text = serverUrl, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) + Section("Account") { + SettingRow( + title = state.username.ifEmpty { "Signed in" }, + summary = if (state.isAdmin) "Signed in · admin" else "Signed in", + ) + SettingRow(title = "Server", summary = state.serverUrl) + SettingRow( + title = "Notifications", + summary = "What reaches you, and where", + icon = Lucide.Bell, + onClick = onNavToNotifications, + ) { RowChevron() } + if (state.isAdmin) { + SettingRow( + title = "Admin", + summary = "Library health, users and metadata", + icon = Lucide.Shield, + onClick = onNavToAdmin, + ) { RowChevron() } } + SettingRow( + title = if (state.isSigningOut) "Signing out…" else "Sign out", + icon = Lucide.LogOut, + tone = MaterialTheme.colorScheme.error, + enabled = !state.isSigningOut, + onClick = onSignOutClick, + ) { if (state.isSigningOut) RowSpinner() } } } @@ -290,74 +190,27 @@ private fun AccountCard(username: String, isAdmin: Boolean, serverUrl: String) { // the user turn reporting OFF on this device (battery/privacy) without // touching the account flag. Checked = reporting on = NOT opted out. @Composable -private fun DiagnosticsCard(optOut: Boolean, onToggle: (Boolean) -> Unit) { - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = "Diagnostics", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Row(verticalAlignment = Alignment.CenterVertically) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = "Send diagnostic reports", - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - text = "Your admin enabled debug mode to investigate an " + - "issue. This device streams connectivity and playback " + - "diagnostics. Turn off any time.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Spacer(Modifier.size(12.dp)) - Switch( - checked = !optOut, - onCheckedChange = { checked -> onToggle(!checked) }, - ) - } - } +private fun DiagnosticsSection(optOut: Boolean, onToggle: (Boolean) -> Unit) { + Section("Diagnostics") { + SwitchRow( + title = "Send diagnostic reports", + summary = "Your admin turned on debug mode", + checked = !optOut, + onCheckedChange = { checked -> onToggle(!checked) }, + ) } } -@OptIn(ExperimentalMaterial3Api::class) @Composable -private fun AppearanceCard(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) { - val options = ThemeMode.entries - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = "Appearance", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - text = "System follows your device setting.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - options.forEachIndexed { index, mode -> - SegmentedButton( - selected = mode == themeMode, - onClick = { onPick(mode) }, - shape = SegmentedButtonDefaults.itemShape( - index = index, - count = options.size, - ), - ) { Text(displayName(mode)) } - } - } - } +private fun AppearanceSection(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) { + Section("Appearance") { + ChoiceRow( + title = "Theme", + summary = if (themeMode == ThemeMode.SYSTEM) "Follows your device" else null, + options = ThemeMode.entries.map { it to displayName(it) }, + selected = themeMode, + onSelect = onPick, + ) } } @@ -376,29 +229,3 @@ private fun AboutCard(model: UpdateViewModel = hiltViewModel()) { CheckWhileShown(model) AppVersionCard(model) } - -@Composable -private fun SignOutButton(isSigningOut: Boolean, onSignOut: () -> Unit) { - Button( - onClick = onSignOut, - enabled = !isSigningOut, - modifier = Modifier.fillMaxWidth(), - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.errorContainer, - contentColor = MaterialTheme.colorScheme.onErrorContainer, - ), - ) { - if (isSigningOut) { - CircularProgressIndicator( - modifier = Modifier.size(20.dp), - color = MaterialTheme.colorScheme.onErrorContainer, - strokeWidth = 2.dp, - ) - } else { - Box(modifier = Modifier.padding(end = 4.dp)) { - Icon(Lucide.LogOut, contentDescription = null) - } - Text("Sign out") - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt index 4de63638..41f104c9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt @@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.cache.mutations.MutationReplayer import com.fabledsword.minstrel.notifications.data.NotificationsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow @@ -12,6 +13,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject data class SettingsState( @@ -30,6 +32,7 @@ class SettingsViewModel @Inject constructor( private val authController: AuthController, private val authStore: AuthStore, private val notifications: NotificationsRepository, + private val replayer: MutationReplayer, ) : ViewModel() { private val transient = MutableStateFlow(TransientState()) @@ -71,6 +74,10 @@ class SettingsViewModel @Inject constructor( if (transient.value.isSigningOut) return viewModelScope.launch { transient.update { it.copy(isSigningOut = true) } + // Send what is still queued while this session can: once another + // account signs in on this device, the rest is cleared unsent. + // Bounded, so signing out offline doesn't hang on the network. + withTimeoutOrNull(SIGN_OUT_DRAIN_MS) { runCatching { replayer.drainSafe() } } authController.signOut() // The inbox is this account's; the next one on the device must not see it. runCatching { notifications.clearLocal() } @@ -87,4 +94,11 @@ class SettingsViewModel @Inject constructor( val isSigningOut: Boolean = false, val signedOut: Boolean = false, ) + + private companion object { + // Long enough for a handful of queued writes on a working + // connection; short enough that a sign-out offline still feels + // immediate. + const val SIGN_OUT_DRAIN_MS = 5_000L + } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt index 3cc572a7..1c74f378 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt @@ -1,36 +1,19 @@ package com.fabledsword.minstrel.settings.ui -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.selection.toggleable -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ElevatedCard import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog +import com.fabledsword.minstrel.theme.ChoiceRow +import com.fabledsword.minstrel.theme.RowSpinner +import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SettingRow +import com.fabledsword.minstrel.theme.SwitchRow private const val GIB: Long = 1024L * 1024 * 1024 private const val MIB: Long = 1024L * 1024 @@ -48,44 +31,39 @@ private val CAP_OPTIONS: List> = listOf( fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) { val state by viewModel.state.collectAsStateWithLifecycle() var showClearConfirm by remember { mutableStateOf(false) } - ElevatedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = "Storage", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - // Two budgets: a liked track that is also recently played counts - // against Liked songs only. The prefetch window has no control; - // AudioPrefetcher uses the stored value (default 5). - CapDropdown( - label = "Liked songs", - hint = "${formatBytes(state.likedBytes)} used", - value = state.settings.likedCapBytes, - onSet = viewModel::setLikedCapBytes, - ) - CapDropdown( - label = "Recently played", - hint = "${formatBytes(state.recentBytes)} used", - value = state.settings.rollingCapBytes, - onSet = viewModel::setRollingCapBytes, - ) - SwitchRow( - label = "Keep liked songs offline", - hint = "Downloads on Wi-Fi", - checked = state.settings.cacheLikedTracks, - onCheckedChange = viewModel::setCacheLikedTracks, - ) - StorageActions( - isSyncing = state.isSyncing, - isClearing = state.isClearing, - onSync = viewModel::syncNow, - onClear = { showClearConfirm = true }, - ) - } + Section("Storage") { + // Two budgets: a liked track that is also recently played counts + // against Liked songs only. The prefetch window has no control; + // AudioPrefetcher uses the stored value (default 5). + CapRow( + title = "Liked songs", + used = state.likedBytes, + value = state.settings.likedCapBytes, + onSet = viewModel::setLikedCapBytes, + ) + CapRow( + title = "Recently played", + used = state.recentBytes, + value = state.settings.rollingCapBytes, + onSet = viewModel::setRollingCapBytes, + ) + SwitchRow( + title = "Keep liked songs offline", + summary = "Downloads on Wi-Fi", + checked = state.settings.cacheLikedTracks, + onCheckedChange = viewModel::setCacheLikedTracks, + ) + SettingRow( + title = if (state.isSyncing) "Syncing…" else "Sync library now", + enabled = !state.isSyncing, + onClick = viewModel::syncNow, + ) { if (state.isSyncing) RowSpinner() } + SettingRow( + title = if (state.isClearing) "Clearing…" else "Clear cached audio", + tone = MaterialTheme.colorScheme.error, + enabled = !state.isClearing, + onClick = { showClearConfirm = true }, + ) { if (state.isClearing) RowSpinner() } } if (showClearConfirm) { ClearCacheConfirmDialog( @@ -98,151 +76,28 @@ fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) { } } +/** A storage budget: how much it holds now, and the cap it may grow to. */ @Composable -private fun CapDropdown(label: String, hint: String, value: Long, onSet: (Long) -> Unit) { - val selectedLabel = CAP_OPTIONS.firstOrNull { it.first == value }?.second - ?: formatBytes(value) - LabeledDropdown( - label = label, - hint = hint, - selectedLabel = selectedLabel, +private fun CapRow(title: String, used: Long, value: Long, onSet: (Long) -> Unit) { + ChoiceRow( + title = title, + summary = "${formatBytes(used)} used", options = CAP_OPTIONS, + selected = value, onSelect = onSet, + selectedLabel = CAP_OPTIONS.firstOrNull { it.first == value }?.second ?: formatBytes(value), ) } -/** A setting's name, with one short line under it. */ -@Composable -private fun RowLabel(label: String, hint: String, modifier: Modifier = Modifier) { - Column(modifier = modifier) { - Text( - text = label, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - text = hint, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -@Composable -private fun SwitchRow(label: String, hint: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .toggleable(value = checked, role = Role.Switch, onValueChange = onCheckedChange), - verticalAlignment = Alignment.CenterVertically, - ) { - RowLabel(label = label, hint = hint, modifier = Modifier.weight(1f)) - Spacer(Modifier.size(12.dp)) - Switch(checked = checked, onCheckedChange = null) - } -} - -/** - * Label and hint on the left, button-with-current-value on the right that - * opens a DropdownMenu of [options]. Used by the cap selectors. - */ -@Composable -private fun LabeledDropdown( - label: String, - hint: String, - selectedLabel: String, - options: List>, - onSelect: (T) -> Unit, -) { - var expanded by remember { mutableStateOf(false) } - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - RowLabel(label = label, hint = hint, modifier = Modifier.weight(1f)) - OutlinedButton(onClick = { expanded = true }) { - Text(selectedLabel) - DropdownMenu( - expanded = expanded, - onDismissRequest = { expanded = false }, - ) { - options.forEach { (value, name) -> - DropdownMenuItem( - text = { Text(name) }, - onClick = { - expanded = false - onSelect(value) - }, - ) - } - } - } - } -} - -@Composable -private fun StorageActions( - isSyncing: Boolean, - isClearing: Boolean, - onSync: () -> Unit, - onClear: () -> Unit, -) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedButton( - onClick = onClear, - enabled = !isClearing, - ) { - if (isClearing) { - CircularProgressIndicator( - modifier = Modifier.size(16.dp), - strokeWidth = 2.dp, - ) - Spacer(Modifier.size(8.dp)) - } - Text(if (isClearing) "Clearing…" else "Clear cache") - } - OutlinedButton( - onClick = onSync, - enabled = !isSyncing, - ) { - if (isSyncing) { - CircularProgressIndicator( - modifier = Modifier.size(16.dp), - strokeWidth = 2.dp, - ) - Spacer(Modifier.size(8.dp)) - } - Text(if (isSyncing) "Syncing…" else "Sync now") - } - } -} - @Composable private fun ClearCacheConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Clear cache?") }, - text = { - Text( - "This deletes all cached audio. The next play of any track " + - "re-downloads from the server.", - ) - }, - confirmButton = { - Button( - onClick = onConfirm, - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.error, - contentColor = MaterialTheme.colorScheme.onError, - ), - ) { Text("Clear") } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text("Cancel") } - }, + ConfirmDestructiveDialog( + title = "Clear cache?", + text = "This deletes all cached audio. The next play of any track " + + "re-downloads from the server.", + confirmLabel = "Clear", + onConfirm = onConfirm, + onDismiss = onDismiss, ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/Plural.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/Plural.kt new file mode 100644 index 00000000..d762ceef --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/Plural.kt @@ -0,0 +1,11 @@ +package com.fabledsword.minstrel.shared + +import java.text.NumberFormat + +/** + * A count with its noun: "1 track", "12,345 tracks". The number is formatted + * for the listener's locale, as the web app's counts are. The app's one way to + * say a count; PluralTest names any hand-written copy. + */ +fun plural(n: Int, one: String, many: String): String = + "${NumberFormat.getIntegerInstance().format(n)} ${if (n == 1) one else many}" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt index 43ee2c44..b3fdce82 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt @@ -1,5 +1,8 @@ package com.fabledsword.minstrel.shared +import com.fabledsword.minstrel.api.ErrorCopy +import kotlinx.coroutines.CancellationException + /** * Shared cache-first UI state for a screen / tab that resolves to a * single payload. Mirrors the shape every screen had reinvented: @@ -20,3 +23,22 @@ sealed interface UiState { data class Success(val data: T) : UiState data class Error(val message: String) : UiState } + +/** This list as a state: [UiState.Empty] when it has nothing in it, else [UiState.Success]. */ +fun List.toListState(): UiState> = if (isEmpty()) UiState.Empty else UiState.Success(this) + +/** + * Runs [load] and gives its answer as a state, for a screen that loads + * straight from the server (the admin screens). A failure becomes + * [UiState.Error] in ErrorCopy's words; cancellation passes through. + */ +suspend fun loadUiState(load: suspend () -> UiState): UiState = + try { + load() + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + UiState.Error(ErrorCopy.fromThrowable(e)) + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt index 1e16bdf4..a3e71e0c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt @@ -6,13 +6,17 @@ import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp import com.fabledsword.minstrel.theme.FabledSwordFlatTokens /** @@ -63,3 +67,19 @@ fun CoverTile( overlay() } } + +/** + * What a cover shows when it has no artwork, or its artwork fails to load: + * the kind of thing it is (an album's disc, an artist's figure, a + * playlist's list) drawn in the muted on-surface colour. 56dp suits the + * library's cards; smaller and larger covers pass their own [size]. + */ +@Composable +fun CoverFallbackIcon(icon: ImageVector, size: Dp = 56.dp) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(size), + ) +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt new file mode 100644 index 00000000..5427c37a --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt @@ -0,0 +1,116 @@ +package com.fabledsword.minstrel.shared.widgets + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.unit.dp +import com.fabledsword.minstrel.theme.LocalActionColors + +/** + * Asks for a name: a playlist's when it is made or renamed. The confirm + * button stays off while the name is blank, and the keyboard's Done key + * confirms too. [onConfirm] gets the name trimmed. + */ +@Composable +fun NameDialog( + title: String, + confirmLabel: String, + onConfirm: (String) -> Unit, + onDismiss: () -> Unit, + initial: String = "", +) { + var name by rememberSaveable { mutableStateOf(initial) } + val trimmed = name.trim() + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + label = { Text("Name") }, + singleLine = true, + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Done, + ), + keyboardActions = KeyboardActions(onDone = { if (trimmed.isNotEmpty()) onConfirm(trimmed) }), + modifier = Modifier.fillMaxWidth(), + ) + }, + confirmButton = { + TextButton(onClick = { onConfirm(trimmed) }, enabled = trimmed.isNotEmpty()) { + Text(confirmLabel) + } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +/** + * Asks before an action that can't be undone. The confirm button is the + * destructive action colour (oxblood), not the error colour: an error is a + * failure that already happened, and this is a choice about to be made. + * + * With [confirmWord], the confirm button stays off until that word is typed + * (case aside), for the few actions that take a lot with them, such as + * deleting an account. + */ +@Composable +fun ConfirmDestructiveDialog( + title: String, + text: String, + confirmLabel: String, + onConfirm: () -> Unit, + onDismiss: () -> Unit, + confirmWord: String? = null, +) { + val actions = LocalActionColors.current + var typed by rememberSaveable { mutableStateOf("") } + val armed = confirmWord == null || typed.trim().equals(confirmWord, ignoreCase = true) + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(text) + if (confirmWord != null) { + OutlinedTextField( + value = typed, + onValueChange = { typed = it }, + label = { Text("Type $confirmWord") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + } + } + }, + confirmButton = { + Button( + onClick = onConfirm, + enabled = armed, + colors = ButtonDefaults.buttonColors( + containerColor = actions.destructive, + contentColor = actions.onAction, + ), + ) { Text(confirmLabel) } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/HorizontalScrollRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/HorizontalScrollRow.kt index b544f5c1..64ffb557 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/HorizontalScrollRow.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/HorizontalScrollRow.kt @@ -3,6 +3,7 @@ package com.fabledsword.minstrel.shared.widgets import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyListScope @@ -11,6 +12,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp /** @@ -22,21 +24,41 @@ import androidx.compose.ui.unit.dp * * The `content` lambda receives a `LazyListScope` so callers use * `items(list, key = ...) { ... }` — preserves lazy item rendering. + * + * [meta] is a short line beside the title for facts every tile in the row + * shares ("25 songs each · refreshed today"), said once instead of under + * each tile. Empty shows nothing. */ @Composable fun HorizontalScrollRow( title: String, modifier: Modifier = Modifier, + meta: String = "", content: LazyListScope.() -> Unit, ) { Column(modifier = modifier.fillMaxWidth()) { if (title.isNotEmpty()) { - Text( - text = title, - style = MaterialTheme.typography.titleLarge, - color = MaterialTheme.colorScheme.onBackground, + Row( modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), - ) + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = title, + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onBackground, + modifier = Modifier.alignByBaseline(), + ) + if (meta.isNotEmpty()) { + Text( + text = meta, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.alignByBaseline(), + ) + } + } } LazyRow( contentPadding = PaddingValues(horizontal = 16.dp), diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt index 634400b4..4c0f62ad 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt @@ -24,7 +24,6 @@ import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.EllipsisVertical import com.composables.icons.lucide.Search as SearchIcon import com.fabledsword.minstrel.nav.Admin -import com.fabledsword.minstrel.nav.Discover import com.fabledsword.minstrel.nav.Home import com.fabledsword.minstrel.nav.Library import com.fabledsword.minstrel.nav.Notifications @@ -37,7 +36,7 @@ import com.fabledsword.minstrel.nav.Settings as SettingsRoute * bottom nav, drawer, or rail; every * top-level AppBar carries this row, and the kebab covers the rest. * - * [Home] [Library] [Search] [ ⋮ Playlists / Discover / Settings / Admin ] + * [Home] [Library] [Search] [ ⋮ Playlists / Settings / Admin ] * * The icon for the screen the user is currently on is suppressed so * the action set looks contextual. The "Admin" overflow item is @@ -124,10 +123,6 @@ private fun OverflowMenu(navController: NavHostController, isAdmin: Boolean) { text = { Text("Playlists") }, onClick = { expanded = false; navController.navigate(Playlists) }, ) - DropdownMenuItem( - text = { Text("Discover") }, - onClick = { expanded = false; navController.navigate(Discover) }, - ) DropdownMenuItem( text = { Text("Settings") }, onClick = { expanded = false; navController.navigate(SettingsRoute) }, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueDragMath.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt similarity index 51% rename from android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueDragMath.kt rename to android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt index 0c1e5c4f..556a6cd9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueDragMath.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt @@ -1,32 +1,33 @@ -package com.fabledsword.minstrel.player.ui +package com.fabledsword.minstrel.shared.widgets import kotlin.math.roundToInt /** * Drag offset to row delta, rounded to the nearest row boundary. The Android * half of web's `offsetToDelta` (web/src/lib/components/queue-row-math.ts): - * the two clients are meant to agree, and QueueDragMathTest mirrors web's + * the two clients are meant to agree, and ReorderDragMathTest mirrors web's * cases so both are held to it. * * Ties round toward positive infinity, as JS `Math.round` does: half a row * down moves one row, half a row up stays put. A row not yet measured * (height 0) moves nothing. */ -internal fun queueDragDelta(offsetPx: Float, rowHeightPx: Int): Int = +internal fun reorderDragDelta(offsetPx: Float, rowHeightPx: Int): Int = if (rowHeightPx > 0) (offsetPx / rowHeightPx).roundToInt() else 0 /** - * The queue index a row dragged from [index] lands on, clamped to the queue. - * A drag past either end stops at the first or last row. + * The index a row dragged from [index] lands on, in a list of [count] rows + * (the queue, or a playlist). A drag past either end stops at the first or + * last row. */ -internal fun queueDragTarget( +internal fun reorderDragTarget( index: Int, offsetPx: Float, rowHeightPx: Int, - queueSize: Int, + count: Int, ): Int { // coerceIn throws on an empty range; a row can't be dragged in an empty - // queue, but the composable's keys can briefly outlive the list. - if (queueSize <= 0) return index - return (index + queueDragDelta(offsetPx, rowHeightPx)).coerceIn(0, queueSize - 1) + // list, but the composable's keys can briefly outlive the list. + if (count <= 0) return index + return (index + reorderDragDelta(offsetPx, rowHeightPx)).coerceIn(0, count - 1) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt new file mode 100644 index 00000000..cb254268 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt @@ -0,0 +1,193 @@ +@file:Suppress("MatchingDeclarationName") // The file is named for its row; ReorderHandles is the row's parameter type. + +package com.fabledsword.minstrel.shared.widgets + +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SwipeToDismissBox +import androidx.compose.material3.SwipeToDismissBoxValue +import androidx.compose.material3.Text +import androidx.compose.material3.rememberSwipeToDismissBoxState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import androidx.compose.ui.zIndex +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Trash2 +import com.fabledsword.minstrel.theme.LocalActionColors + +/** + * What a reorderable row's content applies: [drag] goes on the grab surface + * (the album art), [actions] on the row's clickable container, where a + * screen reader finds it. + */ +class ReorderHandles(val drag: Modifier, val actions: Modifier) + +/** + * A list row that can be dragged to a new place and swiped away: the queue's + * rows and the rows of a listener's own playlist. + * + * - **Long-press the grab surface, then drag** to move the row. On release + * the offset becomes a row delta ([reorderDragTarget]) and [onMove] gets + * (from, to). A long press, not a plain drag, so a pan that starts on the + * artwork still scrolls the list, and a tap still falls through to the + * row's click. + * - **Swipe left** to remove. Only end-to-start is live, so a mis-aimed swipe + * the other way removes nothing. + * - **Under TalkBack**, where both gestures are unavailable, the row offers + * "Move up", "Move down" and [removeLabel] as custom actions. + * + * The caller must key its list items by the entry, not by position: the + * swipe state is remembered per key, and a removed row's key taken by its + * neighbour would show the neighbour as swiped away. + */ +@Suppress("LongParameterList") // Compose row wiring — position, labels and callbacks, not logic. +@Composable +fun ReorderableRemovableRow( + index: Int, + count: Int, + removeLabel: String, + onRemove: () -> Unit, + onMove: (Int, Int) -> Unit, + content: @Composable (ReorderHandles) -> Unit, +) { + var dragOffsetY by remember { mutableFloatStateOf(0f) } + var rowHeightPx by remember { mutableIntStateOf(0) } + val dismissState = rememberSwipeToDismissBoxState( + confirmValueChange = { value -> + if (value == SwipeToDismissBoxValue.EndToStart) { + onRemove() + true + } else { + false + } + }, + ) + SwipeToDismissBox( + state = dismissState, + enableDismissFromStartToEnd = false, + backgroundContent = { RemoveSwipeBackground() }, + // The lift lives out here so a row being dragged vertically carries + // its swipe container with it rather than sliding out of one. + modifier = Modifier + .onSizeChanged { rowHeightPx = it.height } + .zIndex(if (dragOffsetY != 0f) 1f else 0f) + .graphicsLayer { translationY = dragOffsetY }, + ) { + content( + ReorderHandles( + drag = Modifier.reorderDrag(index, count, rowHeightPx, { dragOffsetY = it }, onMove), + actions = Modifier.reorderActions(index, count, removeLabel, onMove, onRemove), + ), + ) + } +} + +/** + * What the row slides off to reveal: the destructive colour with a trash glyph, + * pinned to the trailing edge because that is the edge the swipe uncovers. + * + * Oxblood (LocalActionColors.destructive), NOT colorScheme.error. The design + * system keeps those apart deliberately — an error is a failure that already + * happened, a destructive action is one about to happen — and using the error + * colour here would dress an intentional gesture as a fault report. + */ +@Composable +private fun RemoveSwipeBackground() { + val actions = LocalActionColors.current + Box( + modifier = Modifier + .fillMaxSize() + .background(actions.destructive) + .padding(horizontal = 24.dp), + contentAlignment = Alignment.CenterEnd, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(Lucide.Trash2, contentDescription = null, tint = actions.onAction) + Text( + text = "Remove", + style = MaterialTheme.typography.labelLarge, + color = actions.onAction, + ) + } + } +} + +/** + * Screen-reader moving and removal. Both gestures are touch-only, so without + * these a TalkBack user could neither reorder nor remove. They are the + * Android counterpart to the web row's ArrowUp/ArrowDown keys and X button. + */ +private fun Modifier.reorderActions( + index: Int, + count: Int, + removeLabel: String, + onMove: (Int, Int) -> Unit, + onRemove: () -> Unit, +): Modifier = semantics { + customActions = listOf( + CustomAccessibilityAction("Move up") { + if (index > 0) { onMove(index, index - 1); true } else false + }, + CustomAccessibilityAction("Move down") { + if (index < count - 1) { onMove(index, index + 1); true } else false + }, + CustomAccessibilityAction(removeLabel) { onRemove(); true }, + ) +} + +/** + * The long-press drag. The row follows the finger during the drag, as on + * the web, and on release the accumulated offset becomes the move. + */ +private fun Modifier.reorderDrag( + index: Int, + count: Int, + rowHeightPx: Int, + onOffsetChange: (Float) -> Unit, + onMove: (Int, Int) -> Unit, +): Modifier = composed { + var offset by remember { mutableFloatStateOf(0f) } + pointerInput(index, count, rowHeightPx) { + detectDragGesturesAfterLongPress( + onDrag = { change, dragAmount -> + change.consume() + offset += dragAmount.y + onOffsetChange(offset) + }, + onDragEnd = { + val target = reorderDragTarget(index, offset, rowHeightPx, count) + if (target != index) onMove(index, target) + offset = 0f + onOffsetChange(0f) + }, + onDragCancel = { + offset = 0f + onOffsetChange(0f) + }, + ) + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt index 93a72f5e..722b4dda 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt @@ -26,6 +26,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.fabledsword.minstrel.theme.FabledSwordFlatTokens @@ -67,17 +68,17 @@ fun SkeletonBox( } /** - * Stand-in for AlbumCard / PlaylistCard (same 176dp×144dp cover + - * 2 caption lines geometry). + * Stand-in for AlbumCard / PlaylistCard (same geometry: an [artSize] + * cover in a tile 32dp wider, and 2 caption lines). */ @Composable -fun SkeletonAlbumTile(modifier: Modifier = Modifier) { +fun SkeletonAlbumTile(modifier: Modifier = Modifier, artSize: Dp = 144.dp) { Column( modifier = modifier - .width(176.dp) + .width(artSize + 32.dp) .padding(horizontal = 8.dp), ) { - SkeletonBox(modifier = Modifier.size(144.dp)) + SkeletonBox(modifier = Modifier.size(artSize)) Spacer(Modifier.height(8.dp)) SkeletonBox(modifier = Modifier.fillMaxWidth().height(14.dp)) Spacer(Modifier.height(4.dp)) @@ -86,18 +87,19 @@ fun SkeletonAlbumTile(modifier: Modifier = Modifier) { } /** - * Stand-in for ArtistCard (128dp circular cover + 1 name line). + * Stand-in for ArtistCard (an [artSize] circular cover in a tile 16dp + * wider, and 1 name line). */ @Composable -fun SkeletonArtistTile(modifier: Modifier = Modifier) { +fun SkeletonArtistTile(modifier: Modifier = Modifier, artSize: Dp = 128.dp) { Column( modifier = modifier - .width(144.dp) + .width(artSize + 16.dp) .padding(horizontal = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { SkeletonBox( - modifier = Modifier.size(128.dp), + modifier = Modifier.size(artSize), shape = CircleShape, ) Spacer(Modifier.height(8.dp)) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt index 14fbfb67..2486ab85 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt @@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment @@ -47,14 +46,7 @@ fun TrackCoverThumb( url = coverUrl, contentDescription = contentDescription, modifier = Modifier.fillMaxSize(), - ) { - Icon( - imageVector = Lucide.Music, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(size / 2), - ) - } + ) { CoverFallbackIcon(Lucide.Music, size = size / 2) } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt index df907560..25f72b53 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt @@ -18,6 +18,9 @@ import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow @@ -26,24 +29,39 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.composables.icons.lucide.ListMusic import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Plus import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.plural +import com.fabledsword.minstrel.shared.widgets.NameDialog /** - * ModalBottomSheet that lists the caller's user-owned playlists and - * pops back with the picked id via [onPick]. System playlists are - * filtered out — they're - * not appendable. + * ModalBottomSheet that lists the listener's own playlists and pops back + * with the picked id via [onPick]. Its first row makes a new playlist: + * [onCreate] gets the name typed for it. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddToPlaylistSheet( onPick: (playlistId: String) -> Unit, + onCreate: (name: String) -> Unit, onDismiss: () -> Unit, viewModel: AddToPlaylistViewModel = hiltViewModel(), ) { val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val state by viewModel.uiState.collectAsStateWithLifecycle() + var naming by rememberSaveable { mutableStateOf(false) } + if (naming) { + NameDialog( + title = "New playlist", + confirmLabel = "Create", + onConfirm = { name -> + naming = false + onCreate(name) + }, + onDismiss = { naming = false }, + ) + } ModalBottomSheet( onDismissRequest = onDismiss, sheetState = sheetState, @@ -55,16 +73,14 @@ fun AddToPlaylistSheet( color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp), ) + NewPlaylistRow(onClick = { naming = true }) when (val s = state) { UiState.Loading -> Box( modifier = Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center, ) { CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) } - UiState.Empty -> Text( - text = "You haven't created any playlists yet.", - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp), - ) + // The New playlist row above is the way forward. + UiState.Empty -> Unit is UiState.Error -> Text( text = s.message, color = MaterialTheme.colorScheme.error, @@ -80,6 +96,25 @@ fun AddToPlaylistSheet( } } +@Composable +private fun NewPlaylistRow(onClick: () -> Unit) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + Icon(Lucide.Plus, contentDescription = null, tint = MaterialTheme.colorScheme.primary) + Text( + text = "New playlist", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.primary, + ) + } +} + @Composable private fun PlaylistPickRow(playlist: PlaylistRef, onClick: () -> Unit) { Row( @@ -104,7 +139,7 @@ private fun PlaylistPickRow(playlist: PlaylistRef, onClick: () -> Unit) { overflow = TextOverflow.Ellipsis, ) Text( - text = "${playlist.trackCount} ${if (playlist.trackCount == 1) "track" else "tracks"}", + text = plural(playlist.trackCount, "track", "tracks"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt index 3175daed..c0f5f2b2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt @@ -14,9 +14,8 @@ import kotlinx.coroutines.launch import javax.inject.Inject /** - * Backs [AddToPlaylistSheet] with the caller's user-owned playlists. - * System playlists (For You / Discover / etc.) are filtered out at - * the repository layer — they're not appendable. + * Backs [AddToPlaylistSheet] with the listener's own playlists. Mixes and + * other people's public lists are left out: neither can take a song. */ @HiltViewModel class AddToPlaylistViewModel @Inject constructor( @@ -24,7 +23,7 @@ class AddToPlaylistViewModel @Inject constructor( ) : ViewModel() { val uiState: StateFlow>> = repository - .observeUserPlaylists() + .observeOwnPlaylists() .map { list -> if (list.isEmpty()) UiState.Empty else UiState.Success(list) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt index 7609d195..3b81af88 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt @@ -164,6 +164,11 @@ private fun TrackActionSubSheets( onCloseAddToPlaylist() onDismissParent() }, + onCreate = { name -> + viewModel.addToNewPlaylist(name, track.id) + onCloseAddToPlaylist() + onDismissParent() + }, onDismiss = onCloseAddToPlaylist, ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt index feabb80e..cb5eda3e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt @@ -110,6 +110,20 @@ class TrackActionsViewModel @Inject constructor( } } + /** Makes a playlist called [name] holding just this song. */ + fun addToNewPlaylist(name: String, trackId: String) { + viewModelScope.launch { + runCatching { + val (playlistId, _) = playlists.createPlaylist(name) + playlists.appendTrack(playlistId, trackId) + } + .onSuccess { messages.tryEmit("Added to $name") } + .onFailure { + messages.tryEmit("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") + } + } + } + fun flag(track: TrackRef, reason: String, notes: String) { viewModelScope.launch { runCatching { quarantine.flag(track, reason, notes) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/Section.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/Section.kt new file mode 100644 index 00000000..d1245e21 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/Section.kt @@ -0,0 +1,262 @@ +@file:Suppress("TooManyFunctions") // the settings vocabulary: a plate and its row kinds + +package com.fabledsword.minstrel.theme + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import com.composables.icons.lucide.ChevronRight +import com.composables.icons.lucide.ChevronDown +import com.composables.icons.lucide.Lucide + +/** + * The plate every group of settings sits on. Every section gets the same + * plate, so the screen reads as one thing; a section that matters earns its + * weight with what is inside it, never with a louder box. + * + * The rhythm between lines lives here, not at the call sites. + */ +@Composable +fun Section( + title: String, + modifier: Modifier = Modifier, + trailing: @Composable (RowScope.() -> Unit)? = null, + content: @Composable ColumnScope.() -> Unit, +) { + Surface( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(FabledSwordFlatTokens.radiusLg), + // `iron`, the raised surface, on the `obsidian` ground. + color = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface, + ) { + Column( + modifier = Modifier.padding(SectionInset), + verticalArrangement = Arrangement.spacedBy(SectionRow), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text(title, style = MaterialTheme.typography.titleMedium) + if (trailing != null) { + Row(verticalAlignment = Alignment.CenterVertically, content = trailing) + } + } + Spacer(Modifier.height(TITLE_GAP - SectionRow)) + content() + } + } +} + +/** The quiet line: a caption, a count, a consequence. */ +@Composable +fun Muted(said: String, modifier: Modifier = Modifier, tone: Color = Color.Unspecified) { + Text( + said, + style = MaterialTheme.typography.bodySmall, + color = if (tone == Color.Unspecified) MaterialTheme.colorScheme.onSurfaceVariant else tone, + modifier = modifier, + ) +} + +/** + * One line of a settings section: what it is, one short line about it, and + * its control at the end. A settings screen is a menu, so the summary is one + * short line, never an explanation. + * + * With [onClick] the whole row is the tap target. [tone] colours the title of + * a row reporting something wrong, so the control beside it still reads as a + * control. + */ +@Composable +fun SettingRow( + title: String, + modifier: Modifier = Modifier, + summary: String? = null, + icon: ImageVector? = null, + tone: Color = Color.Unspecified, + enabled: Boolean = true, + onClick: (() -> Unit)? = null, + trailing: @Composable (RowScope.() -> Unit)? = null, +) { + val tappable = if (onClick != null) { + Modifier + .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd)) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick) + } else { + Modifier + } + Row( + modifier = modifier + .fillMaxWidth() + .heightIn(min = ROW_HEIGHT) + .then(tappable) + .alpha(if (enabled) 1f else DISABLED_ALPHA), + verticalAlignment = Alignment.CenterVertically, + ) { + if (icon != null) { + Icon( + icon, + contentDescription = null, + tint = if (tone == Color.Unspecified) MaterialTheme.colorScheme.onSurfaceVariant else tone, + modifier = Modifier.padding(end = ICON_GAP).size(ICON), + ) + } + Column(Modifier.weight(1f).padding(vertical = ROW_PAD)) { + Text( + title, + style = MaterialTheme.typography.bodyLarge, + color = if (tone == Color.Unspecified) MaterialTheme.colorScheme.onSurface else tone, + ) + if (summary != null) Muted(summary) + } + if (trailing != null) { + Row( + modifier = Modifier.padding(start = ICON_GAP), + verticalAlignment = Alignment.CenterVertically, + content = trailing, + ) + } + } +} + +/** A row whose control is a switch; the whole row toggles it. */ +@Composable +fun SwitchRow( + title: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + modifier: Modifier = Modifier, + summary: String? = null, + enabled: Boolean = true, +) { + SettingRow( + title = title, + summary = summary, + enabled = enabled, + modifier = modifier + .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd)) + .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onCheckedChange), + ) { + Switch(checked = checked, onCheckedChange = null, enabled = enabled) + } +} + +/** + * A one-of-N setting: the row shows the current choice, and a tap opens the + * choices under it. + */ +@Composable +fun ChoiceRow( + title: String, + options: List>, + selected: T, + onSelect: (T) -> Unit, + modifier: Modifier = Modifier, + summary: String? = null, + selectedLabel: String = options.firstOrNull { it.first == selected }?.second.orEmpty(), +) { + var open by remember { mutableStateOf(false) } + Box(modifier) { + SettingRow(title = title, summary = summary, onClick = { open = true }) { + RowValue(selectedLabel) + Icon( + Lucide.ChevronDown, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 4.dp).size(SMALL_ICON), + ) + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + options.forEach { (value, name) -> + DropdownMenuItem( + text = { Text(name) }, + onClick = { + open = false + onSelect(value) + }, + ) + } + } + } +} + +/** A row's value, set to the right: a count, a version, a size. */ +@Composable +fun RowValue(said: String) { + Text( + said, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** Work in progress, at the size a row's trailing slot expects. */ +@Composable +fun RowSpinner() { + CircularProgressIndicator(modifier = Modifier.size(SPINNER), strokeWidth = 2.dp) +} + +/** "This opens something", for a row whose tap leads somewhere. */ +@Composable +fun RowChevron() { + Icon(Lucide.ChevronRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) +} + +/** The screen margin either side of a plate. */ +val SectionEdge = 16.dp + +/** Between one plate and the next. */ +val SectionGap = 14.dp + +/** Inside a plate. */ +val SectionInset = 18.dp + +/** Between one line of a plate and the next. */ +val SectionRow = 6.dp + +private val TITLE_GAP = 12.dp + +/** Material's one-line list item height: the smallest a thumb reliably hits. */ +private val ROW_HEIGHT = 48.dp +private val ROW_PAD = 6.dp +private val ICON = 22.dp +private val SMALL_ICON = 16.dp +private val ICON_GAP = 14.dp +private const val DISABLED_ALPHA = 0.5f +private val SPINNER = 16.dp diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt index 40d79c4a..1e09ab00 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt @@ -146,7 +146,17 @@ class AppUpdates @Inject constructor( if (mutable.value.stage != InstallStage.IDLE) return mutable.update { it.copy(stage = InstallStage.DOWNLOADING, progress = 0f, problem = null) } scope.launch { - val download = updates.download(offer) { done -> mutable.update { it.copy(progress = done) } } + // Follows whichever download is running, not only one this call + // starts: when the Wi-Fi fetch is already bringing the build + // down, this waits behind it and its bar should move with it. + val following = launch { + updates.downloadProgress.collect { done -> mutable.update { it.copy(progress = done) } } + } + val download = try { + updates.download(offer) {} + } finally { + following.cancel() + } when (download) { is Download.Problem -> mutable.update { it.copy(stage = InstallStage.IDLE, problem = download.message) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt index 5b1e96a9..175e5fba 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt @@ -5,6 +5,9 @@ import com.fabledsword.minstrel.models.UpdateInfo import com.fabledsword.minstrel.models.wire.UpdateInfoWire import com.fabledsword.minstrel.update.api.ClientVersionApi import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext @@ -66,6 +69,16 @@ class UpdateRepository( private val legacyApk: File? = null, ) { private val turns = Mutex() + private val fetched = MutableStateFlow(0f) + + /** + * How far the download under way has got, 0 to 1, whichever caller + * started it. An Update tap that arrives while the Wi-Fi fetch is + * already bringing the build down waits its turn behind it, and follows + * this to show that download moving rather than a bar stuck at zero. + * Back to 0 once no download is running. + */ + val downloadProgress: StateFlow = fetched.asStateFlow() suspend fun check(): Offer { if (!offers) return Offer.Current @@ -118,9 +131,13 @@ class UpdateRepository( private suspend fun fetch(info: UpdateInfo, progress: (Float) -> Unit): Download { val target = waiting(info) val part = File(dir, target.name + PART) + fetched.value = 0f return try { val digest = withContext(Dispatchers.IO) { - save(apk.open(info.apkUrl), part, info.sizeBytes, progress) + save(apk.open(info.apkUrl), part, info.sizeBytes) { done -> + fetched.value = done + progress(done) + } } withContext(Dispatchers.IO) { settle(info, part, target, digest) } } catch (e: CancellationException) { @@ -129,6 +146,8 @@ class UpdateRepository( } catch (e: IOException) { part.delete() Download.Problem("Couldn't download the update: ${ErrorCopy.fromThrowable(e)}") + } finally { + fetched.value = 0f } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt index 1dee8f39..5f1e28b6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt @@ -1,24 +1,23 @@ package com.fabledsword.minstrel.update.ui -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button -import androidx.compose.material3.ElevatedCard import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.fabledsword.minstrel.BuildConfig import com.fabledsword.minstrel.models.UpdateInfo import com.fabledsword.minstrel.settings.ui.formatBytes +import com.fabledsword.minstrel.theme.Muted +import com.fabledsword.minstrel.theme.RowSpinner +import com.fabledsword.minstrel.theme.RowValue +import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SettingRow import com.fabledsword.minstrel.update.data.InstallStage import com.fabledsword.minstrel.update.data.UpdateUiState @@ -36,53 +35,41 @@ fun AppVersionCard(model: UpdateViewModel, modifier: Modifier = Modifier) { onPauseOrDispose {} } val state by model.state.collectAsStateWithLifecycle() - ElevatedCard(modifier = modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = "About", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - text = "Installed: Minstrel ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - val offer = state.offer - if (offer != null) { - Offered(offer, state, model::update) - } else { - Text( - text = versionWords(state, selfUpdates = !BuildConfig.DEBUG), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - state.problem?.let { - Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) - } - TextButton( - onClick = model::check, - enabled = !BuildConfig.DEBUG && !state.checking && state.stage == InstallStage.IDLE, - ) { Text(if (state.checking) "Checking…" else "Check for updates") } + Section("About", modifier) { + SettingRow(title = "Version") { + RowValue("${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})") } + val offer = state.offer + if (offer != null) { + Offered(offer, state, model::update) + } else { + val canCheck = !BuildConfig.DEBUG && !state.checking && state.stage == InstallStage.IDLE + SettingRow( + title = "Check for updates", + summary = versionWords(state, selfUpdates = !BuildConfig.DEBUG), + enabled = canCheck || state.checking, + onClick = if (canCheck) model::check else null, + ) { if (state.checking) RowSpinner() } + } + state.problem?.let { Muted(it, tone = MaterialTheme.colorScheme.error) } } } /** The newer build, and the one button that fetches and installs it. */ @Composable private fun Offered(offer: UpdateInfo, state: UpdateUiState, update: () -> Unit) { - Text(offeredWords(offer, state.ready), style = MaterialTheme.typography.bodyMedium) - when (state.stage) { - InstallStage.IDLE -> Button(onClick = update, modifier = Modifier.fillMaxWidth()) { - Text(if (state.ready) "Install" else "Update") + SettingRow( + title = if (state.ready) "Ready to install" else "New version on your server", + summary = describe(offer), + ) { + when (state.stage) { + InstallStage.IDLE -> Button(onClick = update) { Text(if (state.ready) "Install" else "Update") } + InstallStage.DOWNLOADING -> RowSpinner() + InstallStage.INSTALLING -> RowValue("Installing…") } - InstallStage.DOWNLOADING -> - LinearProgressIndicator(progress = { state.progress }, modifier = Modifier.fillMaxWidth()) - InstallStage.INSTALLING -> Text("Installing…", style = MaterialTheme.typography.bodyMedium) + } + if (state.stage == InstallStage.DOWNLOADING) { + LinearProgressIndicator(progress = { state.progress }, modifier = Modifier.fillMaxWidth()) } } @@ -95,14 +82,6 @@ internal fun versionWords(state: UpdateUiState, selfUpdates: Boolean = true): St else -> "This is the newest version." } -/** The newer build, and whether it is already downloaded. */ -internal fun offeredWords(offer: UpdateInfo, ready: Boolean): String = - if (ready) { - "A new version of the app is downloaded and ready: ${describe(offer)}" - } else { - "A new version of the app is on your server: ${describe(offer)}" - } - /** The name, the channel when it is the test line, and the size. */ internal fun describe(offer: UpdateInfo): String { val channel = if (offer.channel == "dev") " (test build)" else "" diff --git a/android/app/src/test/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepositoryTest.kt deleted file mode 100644 index 9aae6bb9..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepositoryTest.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.fabledsword.minstrel.admin.data - -import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi -import com.fabledsword.minstrel.models.wire.RequestWire -import io.mockk.coEvery -import io.mockk.every -import io.mockk.mockk -import kotlinx.coroutines.test.runTest -import org.junit.jupiter.api.Test -import retrofit2.Retrofit -import kotlin.test.assertEquals - -/** - * The admin queue names who asked from the row itself: the server - * sends the requester's username, so the screen needs no users-list fetch. - */ -class AdminRequestsRepositoryTest { - private val api: AdminRequestsApi = mockk(relaxed = true) - private val retrofit: Retrofit = mockk { - every { create(AdminRequestsApi::class.java) } returns api - } - private val repo = AdminRequestsRepository(retrofit) - - @Test - fun `a request carries the requester's username`() = runTest { - coEvery { api.list() } returns listOf( - RequestWire(id = "r1", userId = "f7e1ec86-0e76-4cad-8191-b0cc78492851", username = "alice"), - ) - - assertEquals("alice", repo.list().single().username) - } - - @Test - fun `a request without a username keeps it empty`() = runTest { - coEvery { api.list() } returns listOf(RequestWire(id = "r1", userId = "u1")) - - assertEquals("", repo.list().single().username) - } -} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModelTest.kt new file mode 100644 index 00000000..ee9da1f0 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModelTest.kt @@ -0,0 +1,62 @@ +package com.fabledsword.minstrel.admin.ui + +import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository +import com.fabledsword.minstrel.connectivity.NetworkStatusController +import com.fabledsword.minstrel.connectivity.ServerHealth +import com.fabledsword.minstrel.events.EventsStream +import com.fabledsword.minstrel.events.LiveEvent +import com.fabledsword.minstrel.models.AdminQuarantineItemRef +import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.testutil.MainDispatcherExtension +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import kotlin.test.assertEquals + +/** Reports' two removals each reach their own endpoint, and either takes the row off the queue. */ +@ExtendWith(MainDispatcherExtension::class) +class AdminQuarantineViewModelTest { + private val row = AdminQuarantineItemRef( + trackId = "t1", + trackTitle = "Prismatic", + artistName = "Fields of Ontario", + albumTitle = "Geomantic", + albumId = "al1", + reportCount = 1, + ) + private val repository: AdminQuarantineRepository = mockk(relaxed = true) { + coEvery { list() } returns listOf(row) + } + private val eventsStream: EventsStream = mockk { + every { events } returns MutableSharedFlow() + } + private val network: NetworkStatusController = mockk { + every { state } returns MutableStateFlow(ServerHealth.Healthy) + } + + // Lazy: built inside each test, after the extension has swapped in the test Main dispatcher. + private val viewModel by lazy { AdminQuarantineViewModel(repository, eventsStream, network) } + + @Test + fun `remove the file keeps the track and clears the row`() { + viewModel.removeFile("t1") + + coVerify(exactly = 1) { repository.removeFile("t1") } + coVerify(exactly = 0) { repository.deleteFile(any()) } + assertEquals(UiState.Empty, viewModel.uiState.value) + } + + @Test + fun `remove from library is the separate full removal`() { + viewModel.deleteFile("t1") + + coVerify(exactly = 1) { repository.deleteFile("t1") } + coVerify(exactly = 0) { repository.removeFile(any()) } + assertEquals(UiState.Empty, viewModel.uiState.value) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt index fb685099..7f1455e8 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt @@ -2,23 +2,32 @@ package com.fabledsword.minstrel.api import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.auth.FakeSessionVault +import com.fabledsword.minstrel.auth.SessionVault import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao +import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity import io.mockk.coEvery import io.mockk.every import io.mockk.mockk +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import okhttp3.OkHttpClient import okhttp3.Request +import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) class AuthCookieInterceptorTest { @@ -92,6 +101,87 @@ class AuthCookieInterceptorTest { assertNull(authStore.sessionCookie.value) } + @Test + fun `a refused session asks the UI to open sign-in`() { + authStore.setSessionCookie("session=expired") + server.enqueue(MockResponse().setResponseCode(401)) + + client.newCall(Request.Builder().url(placeholderUrl("/api/test")).build()).execute() + + assertTrue(authStore.sessionRejected.value) + } + + // A refusal of a request that carried no cookie says nothing about the + // stored login, and must not raise the sign-in screen either. + @Test + fun `a 401 to a request sent without a cookie signs nobody out`() { + server.enqueue(MockResponse().setResponseCode(401)) + + client.newCall(Request.Builder().url(placeholderUrl("/api/test")).build()).execute() + + assertFalse(authStore.sessionRejected.value) + } + + // The interceptor reads the cookie when the request starts. A sign-in + // that lands while an old request is in flight must survive that old + // request's 401. + @Test + fun `a 401 for an older cookie keeps the one stored since`() { + authStore.setSessionCookie("session=old") + server.dispatcher = + object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + authStore.setSessionCookie("session=new") + return MockResponse().setResponseCode(401) + } + } + + client.newCall(Request.Builder().url(placeholderUrl("/api/test")).build()).execute() + + assertEquals("session=new", authStore.sessionCookie.value) + assertFalse(authStore.sessionRejected.value) + } + + // At launch the stored cookie loads from the Keystore off the main + // thread. A request made before that finishes waits for it rather than + // going out without the login. + @Test + fun `a request made while the stored cookie is still loading carries it`() { + val slowVault = + object : SessionVault { + override fun read(): String? { + Thread.sleep(SLOW_VAULT_MS) + return "session=stored" + } + + override fun write(value: String?): Boolean = true + } + // The store runs on a real background dispatcher here, so its row + // collector lands after construction; the row itself carries the + // server URL so that collector cannot reset it to the default. + val row = AuthSessionEntity(baseUrl = server.url("/").toString()) + val dao = + mockk { + every { observe() } returns flowOf(row) + coEvery { get() } returns row + coEvery { upsert(any()) } returns Unit + coEvery { setSessionCookie(any()) } returns Unit + coEvery { setBaseUrl(any()) } returns Unit + } + val loading = AuthStore(dao, slowVault, CoroutineScope(SupervisorJob() + Dispatchers.Default)) + val launchClient = + OkHttpClient.Builder() + .addInterceptor(AuthCookieInterceptor(loading)) + .addInterceptor(BaseUrlInterceptor(loading)) + .build() + server.enqueue(MockResponse().setResponseCode(200)) + + launchClient.newCall(Request.Builder().url(placeholderUrl("/api/library/sync")).build()).execute() + + assertEquals("session=stored", server.takeRequest().getHeader("Cookie")) + assertEquals("session=stored", loading.sessionCookie.value) + } + @Test fun `captures Set-Cookie on successful response`() { server.enqueue( @@ -145,4 +235,8 @@ class AuthCookieInterceptorTest { assertEquals("session=keep", authStore.sessionCookie.value) } + + private companion object { + const val SLOW_VAULT_MS = 300L + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt index 0fc5e568..c341da5b 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt @@ -70,8 +70,7 @@ class BaseUrlInterceptorTest { // External artwork hosts (artwork.musicbrainz.org, // coverartarchive.org) are absolute external URLs. The // interceptor must NOT rewrite them to the Minstrel base — - // doing so produces 404s the user saw as missing Discover - // suggestion covers. + // doing so produces 404s, and the art never shows. authStore.setBaseUrl(server.url("/").toString()) var seen: HttpUrl? = null val client = diff --git a/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt index c7b7d67a..6c47e211 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt @@ -57,4 +57,23 @@ class ErrorCopyTest { ErrorCopy.fromThrowable(IOException("refused")), ) } + + // The copy is the web app's error-copy.json, so codes only the web had + // before (a server shutting down, a bad setting) now read the same here, + // and an unknown code still falls back rather than showing nothing. + @Test + fun theCopyIsTheWebAppsWording() { + assertEquals("The server is shutting down. Try again in a moment.", ErrorCopy.messageFor("shutting_down")) + assertEquals("Password must be at least 8 characters.", ErrorCopy.messageFor("password_too_short")) + assertEquals("Something went wrong.", ErrorCopy.messageFor("no_such_code")) + } + + // The detail codes are the web's list too: invalid_setting names the + // field and its range, which the fixed copy can't. + @Test + fun theWebsDetailCodesAppendTheServerMessage() { + val e = httpError(400, """{"error":{"code":"invalid_setting","message":"volume must be 0-100"}}""") + + assertEquals("${ErrorCopy.messageFor("invalid_setting")} volume must be 0-100", ErrorCopy.fromThrowable(e)) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthControllerTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthControllerTest.kt new file mode 100644 index 00000000..9ce9015d --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthControllerTest.kt @@ -0,0 +1,140 @@ +package com.fabledsword.minstrel.auth + +import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao +import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory +import io.mockk.coEvery +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import retrofit2.Retrofit +import java.util.concurrent.TimeUnit +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +class AuthControllerTest { + private lateinit var server: MockWebServer + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val json = Json { ignoreUnknownKeys = true } + + @BeforeEach + fun setup() { + server = MockWebServer().apply { start() } + } + + @AfterEach + fun teardown() { + scope.cancel() + server.shutdown() + } + + // At launch the controller refreshes the profile (it carries account + // flags such as debug mode). The stored login loads from the Keystore + // off the main thread, so the refresh has to wait for it rather than + // read the user as signed out and skip. + @Test + fun `the launch profile refresh waits for the stored login`() { + val slowVault = + object : SessionVault { + override fun read(): String? { + Thread.sleep(SLOW_VAULT_MS) + return "session=stored" + } + + override fun write(value: String?): Boolean = true + } + val row = AuthSessionEntity(baseUrl = server.url("/").toString()) + val dao = + mockk { + every { observe() } returns flowOf(row) + coEvery { get() } returns row + coEvery { upsert(any()) } returns Unit + coEvery { setSessionCookie(any()) } returns Unit + coEvery { setBaseUrl(any()) } returns Unit + } + val store = AuthStore(dao, slowVault, scope) + val retrofit = + Retrofit.Builder() + .baseUrl(server.url("/")) + .client(OkHttpClient.Builder().build()) + .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) + .build() + server.enqueue(MockResponse().setResponseCode(200).setBody("""{"id":"u1","username":"listener"}""")) + + AuthController(store, json, scope, retrofit) + + val request = server.takeRequest(REQUEST_WAIT_SECONDS, TimeUnit.SECONDS) + assertNotNull(request, "the profile refresh never reached the server") + assertEquals("/api/me", request.path) + } + + // Signing out ends the session on the server: the logout call goes out + // while the cookie is still set, since the cookie is what names the + // session to drop, and the cookie is cleared once it has. + @Test + fun `sign out sends the logout with the session cookie, then clears it`() { + val vault = FakeSessionVault(stored = "session=stored") + val row = AuthSessionEntity(baseUrl = server.url("/").toString()) + val dao = + mockk { + every { observe() } returns flowOf(row) + coEvery { get() } returns row + coEvery { upsert(any()) } returns Unit + coEvery { setSessionCookie(any()) } returns Unit + coEvery { setUserJson(any()) } returns Unit + coEvery { setBaseUrl(any()) } returns Unit + } + val store = AuthStore(dao, vault, scope) + val retrofit = + Retrofit.Builder() + .baseUrl(server.url("/")) + .client( + OkHttpClient.Builder() + // Attaches the stored cookie, as AuthCookieInterceptor does. + .addInterceptor { chain -> + val cookie = store.sessionCookieForRequest() + chain.proceed( + chain.request().newBuilder().apply { + if (!cookie.isNullOrEmpty()) header("Cookie", cookie) + }.build(), + ) + } + .build(), + ) + .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) + .build() + server.enqueue(MockResponse().setResponseCode(200).setBody("""{"id":"u1","username":"listener"}""")) + server.enqueue(MockResponse().setResponseCode(204)) + + val controller = AuthController(store, json, scope, retrofit) + val launch = server.takeRequest(REQUEST_WAIT_SECONDS, TimeUnit.SECONDS) + assertEquals("/api/me", launch?.path) + + runBlocking { controller.signOut() } + + val logout = server.takeRequest(REQUEST_WAIT_SECONDS, TimeUnit.SECONDS) + assertNotNull(logout, "the logout never reached the server") + assertEquals("/api/auth/logout", logout.path) + assertEquals("session=stored", logout.getHeader("Cookie")) + assertNull(store.sessionCookie.value, "the cookie outlived the sign-out") + } + + private companion object { + const val SLOW_VAULT_MS = 300L + const val REQUEST_WAIT_SECONDS = 5L + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt new file mode 100644 index 00000000..5911cc2e --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt @@ -0,0 +1,133 @@ +package com.fabledsword.minstrel.auth + +import com.fabledsword.minstrel.api.CleartextGuardInterceptor +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import okhttp3.tls.HandshakeCertificates +import okhttp3.tls.HeldCertificate +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * The sign-in screen's address probe: https first, http only when https could + * not connect, and never past a certificate that fails to verify. + */ +class ServerProbeTest { + private val servers = mutableListOf() + + /** The scheme of every request the probe made, in order. */ + private val schemes = mutableListOf() + + private val ca = HeldCertificate.Builder().certificateAuthority(0).build() + private val strangerCa = HeldCertificate.Builder().certificateAuthority(0).build() + private val serverCertificate = HeldCertificate.Builder() + .signedBy(ca) + .addSubjectAlternativeName("localhost") + .build() + + @AfterEach + fun teardown() { + servers.forEach { it.shutdown() } + } + + private fun server(tls: Boolean, body: String = SETUP_STATUS): String { + val server = MockWebServer() + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest) = MockResponse().setBody(body) + } + if (tls) { + val certificates = HandshakeCertificates.Builder().heldCertificate(serverCertificate).build() + server.useHttps(certificates.sslSocketFactory(), false) + } + server.start() + servers += server + return "localhost:${server.port}" + } + + private fun probe(trusts: HeldCertificate = ca, cleartextAllowed: Boolean = true): ServerProbe { + val certificates = HandshakeCertificates.Builder() + .addTrustedCertificate(trusts.certificate) + .build() + val client = OkHttpClient.Builder() + .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager) + .addInterceptor { chain -> + schemes += chain.request().url.scheme + chain.proceed(chain.request()) + } + .addNetworkInterceptor(CleartextGuardInterceptor { cleartextAllowed }) + .build() + // https aimed at a plain-http port can stall until the call times + // out; a short timeout keeps those cases quick. + return ServerProbe(client, callTimeoutMillis = 2_000) + } + + private fun failure(result: ServerProbe.Result): String = + assertIs(result).message + + @Test + fun `an address without a scheme is saved as https when Minstrel answers there`() { + val address = server(tls = true) + val result = runBlocking { probe().find(address) } + assertEquals(ServerProbe.Result.Found("https://$address"), result) + assertEquals(listOf("https"), schemes) + } + + @Test + fun `when https cannot connect, http is tried and saved`() { + val address = server(tls = false) + val result = runBlocking { probe().find("$address/") } + assertEquals(ServerProbe.Result.Found("http://$address"), result) + assertEquals(listOf("https", "http"), schemes) + } + + @Test + fun `a certificate that fails to verify stops the probe before http is tried`() { + val address = server(tls = true) + val message = failure(runBlocking { probe(trusts = strangerCa).find(address) }) + assertTrue("certificate" in message, message) + assertEquals(listOf("https"), schemes, "fell back to http past a bad certificate") + } + + @Test + fun `plain http typed for a public address is refused by the cleartext guard`() { + val address = server(tls = false) + val message = failure(runBlocking { probe(cleartextAllowed = false).find("http://$address") }) + assertTrue("home network" in message, message) + } + + @Test + fun `a public address with no https says https failed and never suggests http`() { + val address = server(tls = false) + val message = failure(runBlocking { probe(cleartextAllowed = false).find(address) }) + assertEquals("Couldn't reach https://$address.", message) + assertFalse("http://" in message, message) + } + + @Test + fun `a server that answers but is not Minstrel is an error, not a fallback`() { + val address = server(tls = true, body = "It works!") + val message = failure(runBlocking { probe().find(address) }) + assertTrue("isn't Minstrel" in message, message) + assertEquals(listOf("https"), schemes) + } + + @Test + fun `a typed scheme is used as typed`() { + val address = server(tls = false) + val result = runBlocking { probe().find("http://$address") } + assertEquals(ServerProbe.Result.Found("http://$address"), result) + assertEquals(listOf("http"), schemes) + } + + private companion object { + const val SETUP_STATUS = """{"setup_required":false}""" + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt new file mode 100644 index 00000000..aef748af --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt @@ -0,0 +1,113 @@ +package com.fabledsword.minstrel.cache.account + +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.models.UserRef +import com.fabledsword.minstrel.player.PlayerController +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class OwnerStepTest { + @Test + fun `waits until the owner has loaded and someone is signed in`() { + assertEquals(OwnerStep.WAIT, ownerStep(loaded = false, signedInUserId = "a", ownerUserId = "a")) + assertEquals(OwnerStep.WAIT, ownerStep(loaded = true, signedInUserId = null, ownerUserId = "a")) + } + + @Test + fun `adopts the account when the cache has no owner, and clears another account's cache`() { + assertEquals(OwnerStep.ADOPT, ownerStep(loaded = true, signedInUserId = "a", ownerUserId = null)) + assertEquals(OwnerStep.SWITCH, ownerStep(loaded = true, signedInUserId = "b", ownerUserId = "a")) + assertEquals(OwnerStep.OWNED, ownerStep(loaded = true, signedInUserId = "a", ownerUserId = "a")) + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class AccountCacheTest { + private val loaded = MutableStateFlow(true) + private val user = MutableStateFlow(null) + private val owner = MutableStateFlow(null) + + private val authStore = mockk { + every { settingsLoaded } returns loaded + every { cacheOwnerUserId } returns owner + coEvery { setCacheOwnerUserId(any()) } coAnswers { owner.value = firstArg() } + coEvery { clearNotifiedUpTo() } returns Unit + } + private val authController = mockk { every { currentUser } returns user } + private val tables = mockk(relaxed = true) + private val player = mockk(relaxed = true) + + private fun TestScope.accountCache() = AccountCache( + authStore, authController, tables, { player }, TestScope(UnconfinedTestDispatcher(testScheduler)), + ) + + private fun signIn(id: String) { + user.value = UserRef(id = id, username = id, isAdmin = false) + } + + @Test + fun `another account signing in clears the last one's data before it owns the cache`() = runTest { + owner.value = "anna" + val cache = accountCache() + signIn("ben") + + coVerify(exactly = 1) { tables.clear() } + coVerify(exactly = 1) { authStore.clearNotifiedUpTo() } + verify(exactly = 1) { player.clearQueue() } + assertEquals("ben", owner.value) + assertTrue(cache.ownedBySignedInUser.value, "ben owns the cache once it is cleared") + } + + @Test + fun `the same account signing back in keeps everything, queued writes included`() = runTest { + owner.value = "anna" + val cache = accountCache() + signIn("anna") + user.value = null + assertFalse(cache.ownedBySignedInUser.value, "nobody owns it while signed out") + signIn("anna") + + coVerify(exactly = 0) { tables.clear() } + verify(exactly = 0) { player.clearQueue() } + assertTrue(cache.ownedBySignedInUser.value) + } + + @Test + fun `an install from before owners adopts the signed-in account without clearing`() = runTest { + val cache = accountCache() + signIn("anna") + + coVerify(exactly = 0) { tables.clear() } + assertEquals("anna", owner.value) + assertTrue(cache.ownedBySignedInUser.value) + } + + @Test + fun `nothing is owned until the stored owner has loaded`() = runTest { + loaded.value = false + owner.value = null + val cache = accountCache() + signIn("ben") + assertFalse(cache.ownedBySignedInUser.value) + coVerify(exactly = 0) { authStore.setCacheOwnerUserId(any()) } + + // The stored row arrives naming another account: that one's data goes. + owner.value = "anna" + loaded.value = true + coVerify(exactly = 1) { tables.clear() } + assertEquals("ben", owner.value) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt new file mode 100644 index 00000000..301d0692 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt @@ -0,0 +1,55 @@ +package com.fabledsword.minstrel.cache.mutations + +import kotlinx.coroutines.test.runTest +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.jupiter.api.Test +import retrofit2.HttpException +import retrofit2.Response +import java.io.IOException +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +/** + * The one rule for an offline-first write: queue what a later replay could + * get through (no answer, 5xx, 408, 429), and never queue what the server + * refused, since the replayer would only drop it. + */ +class SendOrQueueTest { + private var queued = 0 + + private fun httpError(status: Int) = HttpException(Response.error(status, "".toResponseBody())) + + private suspend fun attempt(failure: Throwable?, onRefused: ((HttpException) -> WriteOutcome)? = null) = + if (onRefused == null) { + sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }) + } else { + sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }, onRefused = onRefused) + } + + @Test + fun `a write the server takes is synced and not queued`() = runTest { + assertEquals(WriteOutcome.Synced, attempt(null)) + assertEquals(0, queued) + } + + @Test + fun `no answer, a server error, a timeout and too-many-requests are queued`() = runTest { + for (failure in listOf(IOException("offline"), httpError(503), httpError(408), httpError(429))) { + assertEquals(WriteOutcome.Queued, attempt(failure), "for $failure") + } + assertEquals(4, queued) + } + + @Test + fun `a refusal is not queued, and is thrown by default so the caller can say why`() = runTest { + assertFailsWith { attempt(httpError(403)) } + assertEquals(WriteOutcome.Refused, attempt(httpError(404)) { WriteOutcome.Refused }) + assertEquals(0, queued) + } + + @Test + fun `the replayer and the live write agree on what is worth retrying`() { + val statuses = listOf(400, 403, 404, 408, 409, 429, 500, 503) + assertEquals(listOf(408, 429, 500, 503), statuses.filter(::isRetryableStatus)) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt index c055e4fb..2480cf56 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt @@ -13,22 +13,13 @@ import kotlin.test.assertTrue * Collapse rules for desired-state toggles in the offline queue. * * The hazard this guards against is real and silent: without collapsing, a - * queued snooze that replays AFTER the user's undo re-hides an artist they - * asked to see again, and nothing surfaces the contradiction. + * queued like that replays AFTER the user's unlike likes the artist again, + * and nothing surfaces the contradiction. */ class SupersededToggleIdsTest { private val json = Json { ignoreUnknownKeys = true } - private fun snoozeRow(id: Long, mbid: String, desiredSnoozed: Boolean) = CachedMutationEntity( - id = id, - kind = MutationKind.SUGGESTION_SNOOZE_TOGGLE, - payload = json.encodeToString( - SuggestionSnoozeTogglePayload.serializer(), - SuggestionSnoozeTogglePayload(mbid, "Name", desiredSnoozed), - ), - ) - private fun likeRow(id: Long, entityId: String, desired: Boolean) = CachedMutationEntity( id = id, kind = MutationKind.LIKE_TOGGLE, @@ -39,54 +30,46 @@ class SupersededToggleIdsTest { ) @Test - fun `a snooze followed by its undo drops the snooze`() { + fun `a like followed by its undo drops the like`() { val rows = listOf( - snoozeRow(1, "mb-a", desiredSnoozed = true), - snoozeRow(2, "mb-a", desiredSnoozed = false), + likeRow(1, "artist-1", desired = true), + likeRow(2, "artist-1", desired = false), ) // Only the later intent (the undo) survives to be replayed. assertEquals(setOf(1L), supersededToggleIds(rows, json)) } @Test - fun `toggles for different candidates never collapse into each other`() { + fun `toggles for different entities never collapse into each other`() { val rows = listOf( - snoozeRow(1, "mb-a", desiredSnoozed = true), - snoozeRow(2, "mb-b", desiredSnoozed = true), + likeRow(1, "artist-1", desired = true), + likeRow(2, "artist-2", desired = true), ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } @Test - fun `only the newest of several toggles for one candidate survives`() { + fun `only the newest of several toggles for one entity survives`() { val rows = listOf( - snoozeRow(1, "mb-a", desiredSnoozed = true), - snoozeRow(2, "mb-a", desiredSnoozed = false), - snoozeRow(3, "mb-a", desiredSnoozed = true), + likeRow(1, "artist-1", desired = true), + likeRow(2, "artist-1", desired = false), + likeRow(3, "artist-1", desired = true), ) assertEquals(setOf(1L, 2L), supersededToggleIds(rows, json)) } - // The kind is part of the collapse key, so a snooze and a like that happen - // to share an id string must not shadow one another. + // The kind is part of the collapse key, so a like and a notification + // setting whose fields happen to spell the same strings must not shadow + // one another. @Test - fun `a like and a snooze on the same id string do not collide`() { + fun `a like and a setting with the same strings do not collide`() { val rows = listOf( likeRow(1, "same-id", desired = true), - snoozeRow(2, "same-id", desiredSnoozed = true), + settingRow(2, "artist", "same-id", value = true), ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } - @Test - fun `like toggles still collapse — the pre-existing behaviour is intact`() { - val rows = listOf( - likeRow(1, "artist-1", desired = true), - likeRow(2, "artist-1", desired = false), - ) - assertEquals(setOf(1L), supersededToggleIds(rows, json)) - } - @Test fun `non-toggle kinds are never collapsed, even repeated for one entity`() { // Two appends to the same playlist are two real actions, not one @@ -120,10 +103,10 @@ class SupersededToggleIdsTest { val rows = listOf( CachedMutationEntity( id = 1, - kind = MutationKind.SUGGESTION_SNOOZE_TOGGLE, + kind = MutationKind.LIKE_TOGGLE, payload = "{ not json", ), - snoozeRow(2, "mb-a", desiredSnoozed = true), + likeRow(2, "artist-1", desired = true), ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } @@ -148,7 +131,7 @@ class SupersededToggleIdsTest { fun `only the newest queued normalization change survives`() { val rows = listOf( normalizationRow(1, NormalizationMode.TRACK), - snoozeRow(2, "mb-a", desiredSnoozed = true), + likeRow(2, "artist-1", desired = true), normalizationRow(3, NormalizationMode.OFF), normalizationRow(4, NormalizationMode.ALBUM), ) @@ -167,12 +150,12 @@ class SupersededToggleIdsTest { @Test fun `notification settings collapse per kind and channel, never across them`() { val rows = listOf( - settingRow(1, "request_completed", "email", false), - settingRow(2, "request_completed", "phone", false), - settingRow(3, "request_completed", "email", true), - settingRow(4, "request_approved", "email", false), + settingRow(1, "tracks_missing", "email", false), + settingRow(2, "tracks_missing", "phone", false), + settingRow(3, "tracks_missing", "email", true), + settingRow(4, "quarantine_flagged", "email", false), ) - // Only the older email toggle for request_completed is superseded. + // Only the older email toggle for tracks_missing is superseded. assertEquals(setOf(1L), supersededToggleIds(rows, json)) } @@ -184,4 +167,45 @@ class SupersededToggleIdsTest { ) assertEquals(null, notificationSettingChange(NotificationSettingPayload("k", "pager", true))) } + + private fun reorderRow(id: Long, playlistId: String, order: List) = CachedMutationEntity( + id = id, + kind = MutationKind.PLAYLIST_REORDER, + payload = json.encodeToString( + PlaylistReorderPayload.serializer(), + PlaylistReorderPayload(playlistId, order), + ), + ) + + @Test + fun `only a playlist's last queued reorder is sent`() { + val rows = listOf( + reorderRow(1, "p1", listOf("a", "b")), + reorderRow(2, "p2", listOf("x", "y")), + reorderRow(3, "p1", listOf("b", "a")), + ) + assertEquals(setOf(1L), supersededToggleIds(rows, json)) + } + + @Test + fun `every playlist change names its playlist, so one list's changes wait in order`() { + val create = CachedMutationEntity( + id = 1, + kind = MutationKind.PLAYLIST_CREATE, + payload = json.encodeToString( + PlaylistCreatePayload.serializer(), + PlaylistCreatePayload("p1", "Road Songs"), + ), + ) + val append = CachedMutationEntity( + id = 2, + kind = MutationKind.PLAYLIST_APPEND, + payload = json.encodeToString( + PlaylistAppendPayload.serializer(), + PlaylistAppendPayload("p1", listOf("t1")), + ), + ) + val like = likeRow(3, "artist-1", desired = true) + assertEquals(listOf("p1", "p1", null), listOf(create, append, like).map { playlistIdOf(it, json) }) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt index 161cb8b6..2ce0ecce 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt @@ -71,10 +71,10 @@ class HomeRepositoryTest { assertEquals("al1", skeleton[0].id) assertNull(skeleton[0].value) // skeleton in position - albumFlow.value = AlbumRef(id = "al1", title = "Geogaddi", artistId = "a1") + albumFlow.value = AlbumRef(id = "al1", title = "Geomantic", artistId = "a1") val revealed = awaitItem() assertEquals("al1", revealed[0].id) - assertEquals("Geogaddi", revealed[0].value?.title) // tile reveals + assertEquals("Geomantic", revealed[0].value?.title) // tile reveals cancelAndIgnoreRemainingEvents() } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt index 2315074a..aacbda94 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt @@ -4,6 +4,7 @@ import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.models.SystemPlaylistsStatus import org.junit.jupiter.api.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertTrue class BuildPlaylistsRowTest { @@ -103,4 +104,55 @@ class BuildPlaylistsRowTest { assertTrue(buildSongsLikeRow(emptyList(), SystemPlaylistsStatus(), offline = true).isEmpty()) } + + private fun genreMix(name: String, cached: Boolean, rank: Int = 0) = PlaylistRef( + id = name, + userId = "u", + name = name, + systemVariant = "genre_mix", + trackCount = 50, + fullyCached = cached, + shelfRank = rank, + ) + + @Test + fun `genre mixes get their own row in name order and stay out of the carousel`() { + val owned = listOf( + genreMix("Shoegaze mix", cached = true), + genreMix("dub mix", cached = true), + genreMix("Jazz mix", cached = true), + user("u1", cached = true), + ) + val row = buildGenreMixRow(owned, offline = false) + val names = row.filterIsInstance().map { it.playlist.name } + assertEquals(listOf("dub mix", "Jazz mix", "Shoegaze mix"), names) + + val carousel = buildPlaylistsRow(owned, SystemPlaylistsStatus(), offline = false) + .filterIsInstance().map { it.playlist.id } + assertEquals(listOf("u1"), carousel) + } + + @Test + fun `ranked genre mixes lead with the genre played most, the unranked follow by name`() { + val owned = listOf( + genreMix("Ambient mix", cached = true, rank = 3), + genreMix("Zydeco mix", cached = true), + genreMix("Pop mix", cached = true, rank = 1), + genreMix("Blues mix", cached = true), + genreMix("Jazz mix", cached = true, rank = 2), + ) + val names = buildGenreMixRow(owned, offline = false) + .filterIsInstance().map { it.playlist.name } + assertEquals(listOf("Pop mix", "Jazz mix", "Ambient mix", "Blues mix", "Zydeco mix"), names) + } + + @Test + fun `genre mixes are not refreshable, so a cached one plays offline`() { + assertFalse(genreMix("Jazz mix", cached = true).refreshable) + val owned = listOf(genreMix("A mix", cached = false), genreMix("B mix", cached = true)) + val names = buildGenreMixRow(owned, offline = true) + .filterIsInstance().map { it.playlist.name } + assertEquals(listOf("B mix", "A mix"), names) + assertTrue(buildGenreMixRow(emptyList(), offline = false).isEmpty()) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt new file mode 100644 index 00000000..7f91c122 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt @@ -0,0 +1,25 @@ +package com.fabledsword.minstrel.library.data + +import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class LibraryMappersTest { + @Test + fun `a cached artist with a fetched picture shows the artist image`() { + val artist = CachedArtistEntity( + id = "r1", + name = "Tin Orchard", + sortName = "Tin Orchard", + artistThumbPath = "/data/artist-art/r1/thumb.jpg", + ).toDomain(coverAlbumId = "a1") + assertEquals("http://placeholder.invalid/api/artists/r1/image", artist.displayCoverUrl) + } + + @Test + fun `a cached artist without a picture falls back to an album cover`() { + val artist = CachedArtistEntity(id = "r1", name = "Tin Orchard", sortName = "Tin Orchard") + .toDomain(coverAlbumId = "a1") + assertEquals("http://placeholder.invalid/api/albums/a1/cover", artist.displayCoverUrl) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt index c4c459af..93f64a93 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt @@ -55,7 +55,7 @@ class LibraryRepositoryTest { every { artistDao.observeAll() } returns flowOf( listOf( - CachedArtistEntity(id = "a1", name = "Boards of Canada", sortName = "Boards of Canada"), + CachedArtistEntity(id = "a1", name = "Fields of Ontario", sortName = "Fields of Ontario"), ), ) // observeArtists now combines with albums (to derive the tile @@ -67,7 +67,7 @@ class LibraryRepositoryTest { val first = awaitItem() assertEquals(1, first.size) assertEquals("a1", first[0].id) - assertEquals("Boards of Canada", first[0].name) + assertEquals("Fields of Ontario", first[0].name) awaitComplete() } } @@ -82,13 +82,13 @@ class LibraryRepositoryTest { """ { "id": "a1", - "name": "Boards of Canada", - "sort_name": "Boards of Canada", + "name": "Fields of Ontario", + "sort_name": "Fields of Ontario", "album_count": 2, "cover_url": "", "albums": [ - {"id": "al1", "title": "Music Has the Right to Children", "artist_id": "a1", "sort_title": "Music Has the Right to Children"}, - {"id": "al2", "title": "Geogaddi", "artist_id": "a1", "sort_title": "Geogaddi"} + {"id": "al1", "title": "Music Has the Right to Wander", "artist_id": "a1", "sort_title": "Music Has the Right to Wander"}, + {"id": "al2", "title": "Geomantic", "artist_id": "a1", "sort_title": "Geomantic"} ] } """.trimIndent(), @@ -103,14 +103,4 @@ class LibraryRepositoryTest { coVerify { artistDao.upsertAll(match { it.size == 1 && it[0].id == "a1" }) } coVerify { albumDao.upsertAll(match { it.size == 2 && it[0].id == "al1" && it[1].id == "al2" }) } } - - @Test - fun `getArtist returns null when DAO is empty`() = runTest { - coEvery { artistDao.getById("missing") } returns null - val repo = LibraryRepository(artistDao, albumDao, trackDao, retrofit) - - val result = repo.getArtist("missing") - - assertEquals(null, result) - } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt index 494cb4cb..434f1d4c 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt @@ -73,9 +73,9 @@ class LibraryViewModelTest { fun `Success when DAOs emit content`() = runTest { val repo = mockk() every { repo.observeArtists() } returns - flowOf(listOf(ArtistRef(id = "a1", name = "Boards of Canada", sortName = "Boards"))) + flowOf(listOf(ArtistRef(id = "a1", name = "Fields of Ontario", sortName = "Fields"))) every { repo.observeAlbums() } returns - flowOf(listOf(AlbumRef(id = "al1", title = "Geogaddi", artistId = "a1"))) + flowOf(listOf(AlbumRef(id = "al1", title = "Geomantic", artistId = "a1"))) val vm = LibraryViewModel( repo, diff --git a/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt new file mode 100644 index 00000000..1a4eb83a --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt @@ -0,0 +1,101 @@ +package com.fabledsword.minstrel.likes.data + +import com.fabledsword.minstrel.api.endpoints.LikesApi +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao +import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao +import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao +import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao +import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity +import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.likeToggleKey +import com.fabledsword.minstrel.models.UserRef +import com.fabledsword.minstrel.models.wire.LikedIdsWire +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import retrofit2.Retrofit +import java.io.IOException +import kotlin.test.assertEquals + +/** + * A like or unlike is offline-first, and the user's last action wins: one + * made while an older toggle for the same entity is still queued queues + * behind it, and a refresh keeps what is still queued over the server's + * answer. + */ +class LikesRepositoryTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined) + private val api: LikesApi = mockk(relaxed = true) + private val likeDao: CachedLikeDao = mockk(relaxed = true) + private val queue: MutationQueue = mockk(relaxed = true) + private val auth: AuthController = mockk { + every { currentUser } returns MutableStateFlow(UserRef(id = "u1", username = "listener")) + } + private val retrofit: Retrofit = mockk { + every { create(LikesApi::class.java) } returns api + } + private val repo = LikesRepository( + likeDao, mockk(), mockk(), mockk(), + queue, auth, scope, retrofit, + ) + + @AfterEach + fun teardown() = scope.cancel() + + @Test + fun `a toggle with nothing queued goes live`() = runTest { + coEvery { queue.pendingLikeStates() } returns emptyMap() + + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) + + coVerify { api.unlike("tracks", "t1") } + coVerify(exactly = 0) { queue.enqueueLikeToggle(any(), any(), any()) } + } + + @Test + fun `a toggle behind a queued one queues too, so the older one cannot land last`() = runTest { + coEvery { queue.pendingLikeStates() } returns + mapOf(likeToggleKey(LikesRepository.ENTITY_TRACK, "t1") to true) + + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) + + coVerify(exactly = 0) { api.unlike(any(), any()) } + coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", false) } + } + + @Test + fun `a toggle that cannot reach the server is queued`() = runTest { + coEvery { queue.pendingLikeStates() } returns emptyMap() + coEvery { api.like(any(), any()) } throws IOException("offline") + + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = true) + + coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", true) } + } + + @Test + fun `refresh keeps the likes and unlikes still queued over the server's list`() = runTest { + coEvery { api.ids() } returns LikedIdsWire(trackIds = listOf("kept", "unliked-here")) + coEvery { queue.pendingLikeStates() } returns mapOf( + likeToggleKey(LikesRepository.ENTITY_TRACK, "unliked-here") to false, + likeToggleKey(LikesRepository.ENTITY_TRACK, "liked-here") to true, + ) + val rows = slot>() + coEvery { likeDao.replaceAllForUser("u1", capture(rows)) } returns Unit + + repo.refreshIds() + + assertEquals(setOf("kept", "liked-here"), rows.captured.map { it.entityId }.toSet()) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/models/ArtistSuggestionReasonTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/models/ArtistSuggestionReasonTest.kt deleted file mode 100644 index e002c3e6..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/models/ArtistSuggestionReasonTest.kt +++ /dev/null @@ -1,85 +0,0 @@ -package com.fabledsword.minstrel.models - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -/** - * The card's subtitle line. Wording is kept in lockstep with the web - * client's reasonText() in SuggestionFeed.svelte — these assertions are the - * record of what that wording IS, so a change on one client without the other - * shows up as a failure rather than as silent divergence between the two - * surfaces. - */ -class ArtistSuggestionReasonTest { - - private val seeds = listOf( - SeedContributionRef(name = "Seed", isLiked = true), - ) - - private fun suggestion( - matched: List = emptyList(), - attribution: List = seeds, - ) = ArtistSuggestionRef( - mbid = "mb", - name = "Candidate", - attribution = attribution, - matchedTags = matched, - ) - - @Test - fun `one matched tag reads in the singular`() { - assertEquals( - "Matches your taste in shoegaze.", - suggestion(matched = listOf("shoegaze")).reasonText, - ) - } - - @Test - fun `two matched tags join with and`() { - assertEquals( - "Matches your taste in shoegaze and dream pop.", - suggestion(matched = listOf("shoegaze", "dream pop")).reasonText, - ) - } - - @Test - fun `three matched tags use an Oxford comma`() { - assertEquals( - "Matches your taste in a, b, and c.", - suggestion(matched = listOf("a", "b", "c")).reasonText, - ) - } - - // The server caps at 3, but the client must not render a run-on line if a - // future server sends more. - @Test - fun `more than three matched tags are capped at three`() { - assertEquals( - "Matches your taste in a, b, and c.", - suggestion(matched = listOf("a", "b", "c", "d", "e")).reasonText, - ) - } - - // The COMMON case: most candidates have no cached tags, so the card - // must fall back to seed attribution rather than going blank. - @Test - fun `no matched tags falls back to seed attribution`() { - assertEquals("Because you liked Seed.", suggestion().reasonText) - } - - // Nothing to say at all — a candidate with neither tags nor attribution - // yields an empty line, which the tile suppresses rather than rendering as - // a blank row. - @Test - fun `neither tags nor attribution yields an empty line`() { - assertEquals("", suggestion(attribution = emptyList()).reasonText) - } - - // The taste reason WINS over attribution when both exist: describing the - // music beats describing the similarity graph. - @Test - fun `a taste match supersedes seed attribution`() { - val got = suggestion(matched = listOf("shoegaze")).reasonText - assertEquals("Matches your taste in shoegaze.", got) - } -} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt index ecbf67f7..fd1e39fa 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/models/CoverUrlsTest.kt @@ -1,16 +1,19 @@ package com.fabledsword.minstrel.models +import com.fabledsword.minstrel.api.BaseUrlInterceptor +import okhttp3.HttpUrl.Companion.toHttpUrl import org.junit.jupiter.api.Test import kotlin.test.assertEquals class CoverUrlsTest { + // A cover is fetched through the placeholder host, which BaseUrlInterceptor + // rewrites to the live server and AuthCookieInterceptor signs; any other + // host would load without the session. A blank id has no picture. @Test - fun `albumCoverPath builds the placeholder cover URL`() { - assertEquals("http://placeholder.invalid/api/albums/a1/cover", albumCoverPath("a1")) - } - - @Test - fun `albumCoverPath is empty for a blank id`() { + fun `covers and artist images go through the host the interceptors rewrite`() { + assertEquals(BaseUrlInterceptor.PLACEHOLDER_HOST, albumCoverPath("a1").toHttpUrl().host) + assertEquals(BaseUrlInterceptor.PLACEHOLDER_HOST, artistImagePath("r1").toHttpUrl().host) assertEquals("", albumCoverPath("")) + assertEquals("", artistImagePath("")) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/models/SuggestionSnoozeRefTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/models/SuggestionSnoozeRefTest.kt deleted file mode 100644 index d777af99..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/models/SuggestionSnoozeRefTest.kt +++ /dev/null @@ -1,83 +0,0 @@ -package com.fabledsword.minstrel.models - -import kotlinx.datetime.Instant -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -/** - * `returnsIn` phrasing for the parked-suggestions list. The clock is - * injected rather than frozen, so these assertions are stable. - */ -class SuggestionSnoozeRefTest { - - private val now = 1_800_000_000_000L // fixed epoch ms; any value works - - private fun snoozeIn(days: Double) = SuggestionSnoozeRef( - mbid = "mb", - name = "Parked", - snoozedUntil = Instant - .fromEpochMilliseconds(now + (days * 86_400_000L).toLong()) - .toString(), - ) - - @Test - fun `the default 90-day snooze reads as about 3 months`() { - assertEquals("in about 3 months", snoozeIn(90.0).returnsIn(now)) - } - - @Test - fun `a month reads in the singular`() { - assertEquals("in about a month", snoozeIn(30.0).returnsIn(now)) - } - - @Test - fun `under the month threshold it counts days`() { - assertEquals("in 14 days", snoozeIn(14.0).returnsIn(now)) - } - - // Pins the days→months boundary. The singular branch was originally dead - // code because the threshold (45) sat above the divisor (30), so no day - // count could ever round to one month without being caught by the days - // branch first. Asserting both sides of the seam keeps that from - // regressing silently. - @Test - fun `the days-to-months boundary is exactly at 30 days`() { - assertEquals("in 29 days", snoozeIn(29.0).returnsIn(now)) - assertEquals("in about a month", snoozeIn(30.0).returnsIn(now)) - } - - @Test - fun `well past a month still reads in the singular rather than jumping to two`() { - assertEquals("in about a month", snoozeIn(40.0).returnsIn(now)) - } - - @Test - fun `tomorrow is named, not rendered as 1 days`() { - assertEquals("tomorrow", snoozeIn(1.0).returnsIn(now)) - } - - @Test - fun `later today rounds down to today rather than going negative`() { - assertEquals("today", snoozeIn(0.1).returnsIn(now)) - } - - // The server only ever returns unexpired rows, so a past timestamp means - // our clock and the server's disagree. The row is on screen either way, so - // say something plausible rather than leaving the line blank. - @Test - fun `an already-past expiry degrades to shortly`() { - assertEquals("shortly", snoozeIn(-5.0).returnsIn(now)) - } - - @Test - fun `an unparseable timestamp degrades to shortly`() { - val row = SuggestionSnoozeRef(mbid = "mb", name = "Parked", snoozedUntil = "not-a-date") - assertEquals("shortly", row.returnsIn(now)) - } - - @Test - fun `an empty timestamp degrades to shortly`() { - val row = SuggestionSnoozeRef(mbid = "mb", name = "Parked", snoozedUntil = "") - assertEquals("shortly", row.returnsIn(now)) - } -} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt index 4ec205c1..93ade546 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt @@ -38,7 +38,7 @@ class NotificationSettingsRepositoryTest { private val settings = NotificationSettingsWire( kinds = listOf( - NotificationKindSettingWire("request_completed", false, inbox = true, phone = true, email = true), + NotificationKindSettingWire("new_music", false, inbox = true, phone = true, email = true), ), emailAvailable = true, ) @@ -58,12 +58,12 @@ class NotificationSettingsRepositoryTest { val body = slot() coEvery { api.putSettings(capture(body)) } returns settings - repo.set("request_completed", NotificationChannel.EMAIL, false) + repo.set("new_music", NotificationChannel.EMAIL, false) val optimistic = json.decodeFromString(NotificationSettingsWire.serializer(), saved.first().json) assertFalse(optimistic.kinds.single().email) assertEquals( - listOf(NotificationSettingChangeWire(kind = "request_completed", email = false)), + listOf(NotificationSettingChangeWire(kind = "new_music", email = false)), body.captured.kinds, ) coVerify(exactly = 0) { queue.enqueueNotificationSettingSet(any()) } @@ -75,10 +75,10 @@ class NotificationSettingsRepositoryTest { coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns false coEvery { api.putSettings(any()) } throws IOException("offline") - repo.set("request_completed", NotificationChannel.PHONE, false) + repo.set("new_music", NotificationChannel.PHONE, false) coVerify { - queue.enqueueNotificationSettingSet(NotificationSettingPayload("request_completed", "phone", false)) + queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "phone", false)) } } @@ -87,11 +87,11 @@ class NotificationSettingsRepositoryTest { cached() coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns true - repo.set("request_completed", NotificationChannel.INBOX, false) + repo.set("new_music", NotificationChannel.INBOX, false) coVerify(exactly = 0) { api.putSettings(any()) } coVerify { - queue.enqueueNotificationSettingSet(NotificationSettingPayload("request_completed", "inbox", false)) + queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "inbox", false)) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt index 1b8807ca..c394d782 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt @@ -41,10 +41,10 @@ class NotificationsRepositoryTest { private fun row(id: String, created: String, readAt: Instant? = null) = CachedNotificationEntity( id = id, - kind = "request_completed", + kind = "new_music", title = "t", body = "b", - link = "/requests", + link = "/", createdAt = Instant.parse(created), readAt = readAt, ) @@ -108,8 +108,8 @@ class NotificationsRepositoryTest { coEvery { dao.getAll() } returns listOf(row("a", "2026-10-08T10:00:00Z", readAt = readHere)) coEvery { api.list(any()) } returns NotificationsPageWire( items = listOf( - NotificationWire("a", "request_completed", "t", "b", "/requests", "2026-10-08T10:00:00Z", null), - NotificationWire("b", "request_completed", "t", "b", "/requests", "2026-10-08T11:00:00Z", null), + NotificationWire("a", "new_music", "t", "b", "/", "2026-10-08T10:00:00Z", null), + NotificationWire("b", "new_music", "t", "b", "/", "2026-10-08T11:00:00Z", null), ), unreadCount = 2, ) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt index 2cb85222..9e37ba20 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt @@ -17,14 +17,14 @@ class DeliveryPlanTest { private fun notice( id: String, minutes: Long, - kind: String = "request_approved", + kind: String = "new_music", read: Boolean = false, ) = CachedNotificationEntity( id = id, kind = kind, title = "t-$id", body = "b-$id", - link = "/requests", + link = "/", createdAt = Instant.fromEpochMilliseconds(t0.toEpochMilliseconds() + minutes * 60_000), readAt = if (read) t0 else null, ) @@ -75,17 +75,17 @@ class DeliveryPlanTest { fun `phone prefs come from the cached settings, with every kind on when none are cached`() { val settings = NotificationSettingsWire( kinds = listOf( - NotificationKindSettingWire("request_approved", false, inbox = true, phone = false, email = true), - NotificationKindSettingWire("request_completed", false, inbox = false, phone = true, email = true), - NotificationKindSettingWire("request_rejected", false, inbox = true, phone = true, email = true), + NotificationKindSettingWire("new_music", false, inbox = true, phone = false, email = true), + NotificationKindSettingWire("tracks_missing", true, inbox = false, phone = true, email = true), + NotificationKindSettingWire("quarantine_flagged", true, inbox = true, phone = true, email = true), ), emailAvailable = true, ) val phoneOn = phoneOnFor(settings) - assertFalse(phoneOn("request_approved")) - assertFalse(phoneOn("request_completed"), "phone rides on the inbox") - assertTrue(phoneOn("request_rejected")) - assertTrue(phoneOnFor(null)("tracks_missing")) + assertFalse(phoneOn("new_music")) + assertFalse(phoneOn("tracks_missing"), "phone rides on the inbox") + assertTrue(phoneOn("quarantine_flagged")) + assertTrue(phoneOnFor(null)("scan_failed")) } @Test @@ -97,7 +97,7 @@ class DeliveryPlanTest { val five = (1..5).map { notice("n$it", it.toLong()) } val pile = assertIs(announcementFor(five)) assertEquals(5, pile.count) - assertEquals(ShadeChannel.YOUR_REQUESTS, pile.channel) + assertEquals(ShadeChannel.NEW_MUSIC, pile.channel) assertEquals("5 new notifications", pileText(pile.count)) assertEquals(listOf("t-n5", "t-n4", "t-n3", "t-n2", "t-n1"), pile.lines) assertNull(pileMore(pile)) @@ -116,15 +116,14 @@ class DeliveryPlanTest { val admin = (1..4).map { notice("a$it", it.toLong(), kind = "tracks_missing") } assertEquals(ShadeChannel.LIBRARY_HEALTH, assertIs(announcementFor(admin)).channel) val mixed = admin + notice("r", 9) - assertEquals(ShadeChannel.YOUR_REQUESTS, assertIs(announcementFor(mixed)).channel) + assertEquals(ShadeChannel.NEW_MUSIC, assertIs(announcementFor(mixed)).channel) } @Test - fun `listener kinds are their requests, the rest is library health`() { - listOf("request_approved", "request_rejected", "request_completed").forEach { - assertEquals(ShadeChannel.YOUR_REQUESTS, shadeChannelFor(it)) - } - listOf("request_pending", "quarantine_flagged", "scan_failed", "tracks_missing").forEach { + fun `new music has its own channel, the rest is library health`() { + assertEquals(ShadeChannel.NEW_MUSIC, shadeChannelFor("new_music")) + assertTrue(ShadeChannel.entries.none { it.id in retiredShadeChannelIds }, "a live channel is never deleted") + listOf("quarantine_flagged", "scan_failed", "tracks_missing").forEach { assertEquals(ShadeChannel.LIBRARY_HEALTH, shadeChannelFor(it)) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt index f988ac13..cf3b1c3d 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt @@ -3,10 +3,9 @@ package com.fabledsword.minstrel.notifications.ui import com.fabledsword.minstrel.api.endpoints.NotificationKindSettingWire import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.AdminQuarantine -import com.fabledsword.minstrel.nav.AdminRequests import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.Requests +import com.fabledsword.minstrel.nav.Home import com.fabledsword.minstrel.notifications.data.NotificationChannel import com.fabledsword.minstrel.shared.widgets.badgeLabel import kotlinx.datetime.Instant @@ -19,10 +18,11 @@ import kotlin.test.assertTrue class NotificationUiTest { @Test fun `server links open the matching screens`() { + assertEquals(Home, routeForLink("/")) + // A pile carries no link: it opens the inbox, not Home. + assertNull(routeForLink("")) assertEquals(AlbumDetail("al-1"), routeForLink("/albums/al-1")) assertEquals(ArtistDetail("ar-1"), routeForLink("/artists/ar-1")) - assertEquals(Requests, routeForLink("/requests")) - assertEquals(AdminRequests, routeForLink("/admin/requests")) assertEquals(AdminQuarantine, routeForLink("/collection/reports")) // Library health pages the app has no screen for open the Admin landing. assertEquals(Admin, routeForLink("/collection/duplicates")) @@ -30,6 +30,9 @@ class NotificationUiTest { assertEquals(Admin, routeForLink("/collection/missing")) assertEquals(Admin, routeForLink("/admin")) assertNull(routeForLink("/somewhere-new")) + // A link to a page the app has no screen for and Admin does not hold + // opens nothing, rather than an empty screen. + assertNull(routeForLink("/requests")) } @Test @@ -51,7 +54,7 @@ class NotificationUiTest { @Test fun `phone and email ride on the inbox, and email needs to be available`() { - val on = NotificationKindSettingWire("request_completed", false, inbox = true, phone = true, email = true) + val on = NotificationKindSettingWire("new_music", false, inbox = true, phone = true, email = true) val off = on.copy(inbox = false) assertTrue(channelEnabled(on, NotificationChannel.PHONE, emailAvailable = true)) assertFalse(channelEnabled(off, NotificationChannel.PHONE, emailAvailable = true)) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt index afa33564..865e39ff 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt @@ -29,10 +29,10 @@ class NotificationsViewModelTest { private fun row(id: String, read: Boolean) = CachedNotificationEntity( id = id, - kind = "request_completed", + kind = "new_music", title = "t", body = "b", - link = "/requests", + link = "/", createdAt = Instant.parse("2026-10-23T12:00:00Z"), readAt = if (read) Instant.parse("2026-10-23T12:05:00Z") else null, ) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/PreviousTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/PreviousTest.kt new file mode 100644 index 00000000..38bc9758 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/PreviousTest.kt @@ -0,0 +1,39 @@ +package com.fabledsword.minstrel.player + +import com.fabledsword.minstrel.models.TrackRef +import org.junit.jupiter.api.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Previous works as the web player's does: past the first 3 seconds it starts + * the song over; before that it goes back a song. It greys out only in the + * opening seconds of the queue's first song, where it has nothing to do. + */ +class PreviousTest { + private val track = TrackRef(id = "t-1", title = "A song", albumId = "al-1", artistId = "ar-1") + + @Test + fun `past three seconds, Previous starts the song over`() { + assertTrue(previousRestarts(positionMs = 3_000, hasPrevious = true)) + assertTrue(PlayerUiState(currentTrack = track, positionMs = 45_000, hasPrevious = true).previousRestarts) + } + + @Test + fun `in the first three seconds, Previous goes back a song`() { + assertFalse(previousRestarts(positionMs = 2_999, hasPrevious = true)) + } + + @Test + fun `with nothing before it, Previous starts the song over`() { + assertTrue(previousRestarts(positionMs = 500, hasPrevious = false)) + } + + @Test + fun `Previous greys out only at the very start of the first song`() { + assertFalse(PlayerUiState(currentTrack = track, positionMs = 1_000, hasPrevious = false).canSkipPrevious) + assertTrue(PlayerUiState(currentTrack = track, positionMs = 3_000, hasPrevious = false).canSkipPrevious) + assertTrue(PlayerUiState(currentTrack = track, positionMs = 0, hasPrevious = true).canSkipPrevious) + assertFalse(PlayerUiState(currentTrack = null, positionMs = 10_000, hasPrevious = false).canSkipPrevious) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt index e444e0b7..e3ff5e38 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt @@ -7,47 +7,18 @@ import kotlin.test.assertTrue class RemotePlayerStateTest { + // A renderer error stops playback and is kept to report, but what the + // listener asked for survives it, so a failed play can resume locally. @Test - fun `starts in idle state`() { - val state = RemotePlayerState() - assertFalse(state.isPlaying) - assertEquals(0L, state.positionMs) - assertEquals(0L, state.durationMs) - } - - @Test - fun `applyPositionInfo updates position, duration, and trackNumber`() { - val state = RemotePlayerState() - state.applyPositionInfo( - positionMs = 65_000L, durationMs = 210_000L, trackUri = "x", trackNumber = 3, - ) - assertEquals(65_000L, state.positionMs) - assertEquals(210_000L, state.durationMs) - assertEquals("x", state.currentTrackUri) - assertEquals(3, state.trackNumber) - } - - @Test - fun `applyTransportPlaying flips isPlaying true`() { + fun `an error stops playback and is recorded, and the play intent survives it`() { val state = RemotePlayerState() state.applyTransportPlaying() - assertTrue(state.isPlaying) - } - - @Test - fun `applyTransportPaused flips isPlaying false`() { - val state = RemotePlayerState().apply { applyTransportPlaying() } - state.applyTransportPaused() - assertFalse(state.isPlaying) - } - - @Test - fun `applyError resets to idle and records error`() { - val state = RemotePlayerState().apply { applyTransportPlaying() } - val ex = RuntimeException("disconnected") + state.setPlayIntent(true) + val ex = RuntimeException("connect timeout") state.applyError(ex) assertFalse(state.isPlaying) assertEquals(ex, state.lastError) + assertTrue(state.lastPlayIntent) } @Test @@ -69,24 +40,6 @@ class RemotePlayerStateTest { assertFalse(state.recordPollFailure()) } - @Test - fun `play intent survives a SOAP error so a failed play can resume locally`() { - val state = RemotePlayerState() - state.setPlayIntent(true) - state.applyError(RuntimeException("connect timeout")) - // isPlaying is cleared by the error, but the user's intent persists. - assertFalse(state.isPlaying) - assertTrue(state.lastPlayIntent) - } - - @Test - fun `pausing clears play intent`() { - val state = RemotePlayerState() - state.setPlayIntent(true) - state.setPlayIntent(false) - assertFalse(state.lastPlayIntent) - } - @Test fun `reset clears play intent`() { val state = RemotePlayerState() diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt index 8aa91a05..960f86b6 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt @@ -1,55 +1,25 @@ package com.fabledsword.minstrel.player.output -import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource import kotlin.test.assertEquals +/** + * The idle timer arms when a speaker sits paused, and is cancelled by + * playing again or leaving the speaker; anything else leaves it as it is. + */ class IdleRevertDecisionTest { - @Test - fun `engaged and paused and not armed arms the timer`() { - assertEquals( - IdleRevertAction.ARM, - idleRevertAction(upnpEngaged = true, isPlaying = false, armed = false), - ) - } - - @Test - fun `engaged and paused and already armed is ignored`() { - assertEquals( - IdleRevertAction.IGNORE, - idleRevertAction(upnpEngaged = true, isPlaying = false, armed = true), - ) - } - - @Test - fun `resuming playback cancels an armed timer`() { - assertEquals( - IdleRevertAction.CANCEL, - idleRevertAction(upnpEngaged = true, isPlaying = true, armed = true), - ) - } - - @Test - fun `playing with no timer armed is ignored`() { - assertEquals( - IdleRevertAction.IGNORE, - idleRevertAction(upnpEngaged = true, isPlaying = true, armed = false), - ) - } - - @Test - fun `disengaging UPnP cancels an armed timer`() { - assertEquals( - IdleRevertAction.CANCEL, - idleRevertAction(upnpEngaged = false, isPlaying = false, armed = true), - ) - } - - @Test - fun `disengaged with no timer armed is ignored`() { - assertEquals( - IdleRevertAction.IGNORE, - idleRevertAction(upnpEngaged = false, isPlaying = true, armed = false), - ) + @ParameterizedTest(name = "engaged={0} playing={1} armed={2} -> {3}") + @CsvSource( + "true, false, false, ARM", + "true, false, true, IGNORE", + "true, true, true, CANCEL", + "true, true, false, IGNORE", + "false, false, true, CANCEL", + "false, true, false, IGNORE", + ) + fun `the idle timer`(engaged: Boolean, playing: Boolean, armed: Boolean, want: String) { + assertEquals(want, idleRevertAction(upnpEngaged = engaged, isPlaying = playing, armed = armed).name) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt index c690bb43..3261bb80 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt @@ -21,9 +21,9 @@ class SingleTrackQueueTest { name = "Room", manufacturer = manufacturer, modelName = "", - avTransportControlUrl = "http://192.168.0.2:1400/AVTransport/Control".toHttpUrl(), + avTransportControlUrl = "http://198.51.100.2:1400/AVTransport/Control".toHttpUrl(), renderingControlUrl = null, - zoneGroupTopologyControlUrl = if (zgt) "http://192.168.0.2:1400/ZGT/Control".toHttpUrl() else null, + zoneGroupTopologyControlUrl = if (zgt) "http://198.51.100.2:1400/ZGT/Control".toHttpUrl() else null, ) @Test diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt index 6d4e67e7..7a1892e7 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt @@ -6,38 +6,23 @@ import kotlin.test.assertEquals /** * The Sonos queue plays straight through, so a track's album play is judged - * from its neighbours in the list sent. + * from its neighbours in the list sent. The rule itself is GainMath's and is + * tested there; this checks the queue hands it each track's neighbours, and + * that a track with no album counts as none. */ class SonosAlbumPlayTest { - private fun t(album: String, n: Int?, disc: Int? = null) = - TrackRef(id = "$album-$disc-$n", title = "", albumId = album, artistId = "", trackNumber = n, discNumber = disc) + private fun t(album: String, n: Int?) = + TrackRef(id = "$album-$n", title = "", albumId = album, artistId = "", trackNumber = n) private fun asAlbum(queue: List) = queue.indices.map { SonosQueueLoader.playingAsAlbum(queue, it) } @Test - fun `an album in order plays as an album throughout`() { - assertEquals(listOf(true, true, true), asAlbum(listOf(t("a", 1), t("a", 2), t("a", 3)))) - } - - @Test - fun `a mix of albums plays as singles`() { - assertEquals(listOf(false, false, false), asAlbum(listOf(t("a", 1), t("b", 1), t("c", 4)))) - } - - @Test - fun `album order runs across discs`() { - assertEquals(listOf(true, true), asAlbum(listOf(t("a", 12, disc = 1), t("a", 1, disc = 2)))) - } - - @Test - fun `shuffled tracks of one album are not album play`() { - assertEquals(listOf(false, false), asAlbum(listOf(t("a", 3), t("a", 1)))) - } - - @Test - fun `unnumbered tracks and missing albums are never album play`() { - assertEquals(listOf(false, false), asAlbum(listOf(t("a", null), t("a", null)))) + fun `each track is judged by its own neighbours in the queue`() { + assertEquals( + listOf(true, true, false, false), + asAlbum(listOf(t("a", 1), t("a", 2), t("b", 7), t("c", 1))), + ) assertEquals(listOf(false, false), asAlbum(listOf(t("", 1), t("", 2)))) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt index 44fcd435..7996035e 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt @@ -104,18 +104,6 @@ class AVTransportClientTest { assertEquals(TransportState.UNKNOWN, info.state) } - @Test - fun `removeAllTracksFromQueue sends correct SOAP action`() = runTest { - server.enqueue(emptyResponse("RemoveAllTracksFromQueue")) - client.removeAllTracksFromQueue() - val request = server.takeRequest() - assertTrue(request.getHeader("SOAPACTION").orEmpty().contains("RemoveAllTracksFromQueue")) { - "SOAPACTION header missing action: ${request.getHeader("SOAPACTION")}" - } - val body = request.body.readUtf8() - assertTrue(body.contains("RemoveAllTracksFromQueue")) { "body: $body" } - } - @Test fun `addURIToQueue sends EnqueuedURI and DIDL-Lite metadata`() = runTest { server.enqueue(emptyResponse("AddURIToQueue")) @@ -137,26 +125,6 @@ class AVTransportClientTest { assertTrue(body.contains("audio/mpeg")) { "mime missing: $body" } } - @Test - fun `next sends Next SOAP action`() = runTest { - server.enqueue(emptyResponse("Next")) - client.next() - val request = server.takeRequest() - assertTrue(request.getHeader("SOAPACTION").orEmpty().endsWith("#Next\"")) { - "SOAPACTION: ${request.getHeader("SOAPACTION")}" - } - } - - @Test - fun `previous sends Previous SOAP action`() = runTest { - server.enqueue(emptyResponse("Previous")) - client.previous() - val request = server.takeRequest() - assertTrue(request.getHeader("SOAPACTION").orEmpty().endsWith("#Previous\"")) { - "SOAPACTION: ${request.getHeader("SOAPACTION")}" - } - } - @Test fun `seekToTrack sends TRACK_NR unit with 1-based target`() = runTest { server.enqueue(emptyResponse("Seek")) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt index 28187353..8de7e22b 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt @@ -1,44 +1,26 @@ package com.fabledsword.minstrel.player.output.upnp -import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource import kotlin.test.assertEquals +/** + * A Sonos names one speaker several ways: the renderer's route id carries + * `uuid:` and an `_MR` suffix, a media server `_MS`, and the zone-group + * topology neither. Bare, they compare equal. + */ class BareUdnTest { - @Test - fun `strips uuid prefix`() { - assertEquals("RINCON_ABC", "uuid:RINCON_ABC".bareUdn()) - } - - @Test - fun `strips MR suffix`() { - assertEquals("RINCON_ABC", "RINCON_ABC_MR".bareUdn()) - } - - @Test - fun `strips MS suffix`() { - assertEquals("RINCON_ABC", "RINCON_ABC_MS".bareUdn()) - } - - @Test - fun `strips both uuid prefix and MR suffix`() { - assertEquals("RINCON_ABC", "uuid:RINCON_ABC_MR".bareUdn()) - } - - @Test - fun `strips both uuid prefix and MS suffix`() { - assertEquals("RINCON_ABC", "uuid:RINCON_ABC_MS".bareUdn()) - } - - @Test - fun `leaves already bare UDN unchanged`() { - assertEquals("RINCON_ABC", "RINCON_ABC".bareUdn()) - } - - @Test - fun `MR suffix comparison crosses MediaRenderer vs ZGT response`() { - val routeId = "uuid:RINCON_5CAAFD794B6401400_MR" - val zgtMemberUdn = "RINCON_5CAAFD794B6401400" - assertEquals(routeId.bareUdn(), zgtMemberUdn.bareUdn()) + @ParameterizedTest(name = "{0}") + @CsvSource( + "uuid:RINCON_ABC", + "RINCON_ABC_MR", + "RINCON_ABC_MS", + "uuid:RINCON_ABC_MR", + "uuid:RINCON_ABC_MS", + "RINCON_ABC", + ) + fun `every form of a speaker's id is the same bare id`(udn: String) { + assertEquals("RINCON_ABC", udn.bareUdn()) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt index 2668d066..130be113 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt @@ -17,7 +17,7 @@ import kotlin.test.assertNull */ class DeviceDescriptionTest { - private val base = "http://192.168.1.50:1400/xml/device_description.xml".toHttpUrl() + private val base = "http://198.51.100.50:1400/xml/device_description.xml".toHttpUrl() @Test fun `parses Sonos-shaped description`() { @@ -51,11 +51,11 @@ class DeviceDescriptionTest { assertEquals("Sonos One", desc.modelName) assertEquals("uuid:RINCON_ABC", desc.udn) assertEquals( - "http://192.168.1.50:1400/MediaRenderer/AVTransport/Control", + "http://198.51.100.50:1400/MediaRenderer/AVTransport/Control", desc.avTransportControlUrl.toString(), ) assertEquals( - "http://192.168.1.50:1400/MediaRenderer/RenderingControl/Control", + "http://198.51.100.50:1400/MediaRenderer/RenderingControl/Control", desc.renderingControlUrl?.toString(), ) assertNull(desc.zoneGroupTopologyControlUrl) @@ -108,7 +108,7 @@ class DeviceDescriptionTest { val desc = DeviceDescription.parse(xml, base) assertNotNull(desc) assertEquals( - "http://192.168.1.50:1400/ZoneGroupTopology/Control", + "http://198.51.100.50:1400/ZoneGroupTopology/Control", desc.zoneGroupTopologyControlUrl?.toString(), ) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt index 3fcdf6f8..4f65f5ef 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt @@ -7,6 +7,8 @@ import okhttp3.mockwebserver.MockWebServer import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue @@ -46,8 +48,9 @@ class RenderingControlClientTest { ) } - @Test - fun `setVolume clamps and sends DesiredVolume`() = runTest { + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource("150, 100", "-5, 0", "40, 40") + fun `setVolume clamps to the renderer's range and sends DesiredVolume`(asked: Int, sent: Int) = runTest { server.enqueue(MockResponse().setBody( """ @@ -56,23 +59,8 @@ class RenderingControlClientTest { xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1"/> """.trimIndent())) - client.setVolume(150) + client.setVolume(asked) val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("100")) { body } - } - - @Test - fun `setVolume clamps below VOLUME_MIN to zero`() = runTest { - server.enqueue(MockResponse().setBody( - """ - - - - - """.trimIndent())) - client.setVolume(-5) - val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("0")) { body } + assertTrue(body.contains("$sent")) { body } } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt index 23caef85..ef05ea95 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt @@ -13,7 +13,7 @@ class SonosTopologyTest { + Location="http://198.51.100.10:1400/xml/device_description.xml"/> @@ -33,10 +33,10 @@ class SonosTopologyTest { @@ -82,7 +82,7 @@ class SonosTopologyTest { + Location="http://198.51.100.10:1400/xml/device_description.xml"/> @@ -98,7 +98,7 @@ class SonosTopologyTest { <ZoneGroups> <ZoneGroup Coordinator="RINCON_A" ID="RINCON_A:1"> <ZoneGroupMember UUID="RINCON_A" ZoneName="Kitchen" - Location="http://192.168.1.10:1400/xml/device_description.xml"/> + Location="http://198.51.100.10:1400/xml/device_description.xml"/> </ZoneGroup> </ZoneGroups> </ZoneGroupState> diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/ui/QueueDragMathTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/ui/QueueDragMathTest.kt deleted file mode 100644 index deeb9c10..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/ui/QueueDragMathTest.kt +++ /dev/null @@ -1,78 +0,0 @@ -package com.fabledsword.minstrel.player.ui - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -/** - * The queue drag math. The delta cases mirror web's - * queue-row-math.test.ts one for one, so a change to either client's - * rounding shows up as a disagreement here rather than as a drop that lands - * one row off on one platform only. - */ -class QueueDragMathTest { - - @Test - fun `zero offset moves nothing`() { - assertEquals(0, queueDragDelta(0f, 64)) - } - - @Test - fun `a full row down moves one`() { - assertEquals(1, queueDragDelta(64f, 64)) - } - - @Test - fun `just under half a row rounds down`() { - assertEquals(0, queueDragDelta(31f, 64)) - } - - @Test - fun `half a row or more rounds up`() { - assertEquals(1, queueDragDelta(32f, 64)) - } - - @Test - fun `drag up is symmetric, with ties toward positive infinity as in JS`() { - assertEquals(-1, queueDragDelta(-64f, 64)) - assertEquals(0, queueDragDelta(-32f, 64)) - } - - @Test - fun `several rows`() { - assertEquals(3, queueDragDelta(192f, 64)) - assertEquals(-2, queueDragDelta(-128f, 64)) - } - - @Test - fun `a row not yet measured moves nothing`() { - assertEquals(0, queueDragDelta(100f, 0)) - assertEquals(0, queueDragDelta(100f, -1)) - } - - @Test - fun `the measured row height is what counts`() { - assertEquals(1, queueDragDelta(56f, 56)) - assertEquals(1, queueDragDelta(28f, 56)) - } - - @Test - fun `a drag past either end stops at the first or last row`() { - assertEquals(0, queueDragTarget(index = 1, offsetPx = -640f, rowHeightPx = 64, queueSize = 5)) - assertEquals(4, queueDragTarget(index = 3, offsetPx = 640f, rowHeightPx = 64, queueSize = 5)) - } - - @Test - fun `a sub-half-row drag lands where it started`() { - assertEquals(2, queueDragTarget(index = 2, offsetPx = 20f, rowHeightPx = 64, queueSize = 5)) - } - - @Test - fun `before the row is measured a drag lands where it started`() { - assertEquals(2, queueDragTarget(index = 2, offsetPx = 300f, rowHeightPx = 0, queueSize = 5)) - } - - @Test - fun `an empty queue does not throw`() { - assertEquals(0, queueDragTarget(index = 0, offsetPx = 64f, rowHeightPx = 64, queueSize = 0)) - } -} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/ShelfTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/ShelfTest.kt new file mode 100644 index 00000000..f9a0cada --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/ShelfTest.kt @@ -0,0 +1,143 @@ +package com.fabledsword.minstrel.playlists + +import com.fabledsword.minstrel.models.PlaylistRef +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.MethodSource +import java.time.Instant +import java.time.ZoneOffset +import kotlin.math.pow +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class ShelfTest { + + private val utc = ZoneOffset.UTC + private val now = Instant.parse("2026-11-23T15:00:00Z") + + private fun mix( + covers: List = emptyList(), + tracks: Int = 100, + createdAt: String = "2026-11-23T08:00:00Z", + variant: String? = "for_you", + name: String = "Mix", + ) = PlaylistRef( + id = name, + userId = "u", + name = name, + systemVariant = variant, + trackCount = tracks, + coverAlbumIds = covers, + createdAt = createdAt, + ) + + @Test + fun `each tile takes the first album no earlier tile shows`() { + val got = assignShelfCovers( + listOf(mix(listOf("a", "b", "c")), mix(listOf("a", "d")), mix(listOf("a", "d", "e"))), + perTile = 1, + ) + assertEquals(listOf(listOf("a"), listOf("d"), listOf("e")), got) + } + + @Test + fun `a band takes three unused albums`() { + val got = assignShelfCovers( + listOf(mix(listOf("a", "b", "c", "d")), mix(listOf("b", "c", "e", "f", "g"))), + perTile = 3, + ) + assertEquals(listOf(listOf("a", "b", "c"), listOf("e", "f", "g")), got) + } + + @Test + fun `a tile whose albums are all taken reuses its own rather than showing nothing`() { + val got = assignShelfCovers(listOf(mix(listOf("a")), mix(listOf("a"))), perTile = 1) + assertEquals(listOf(listOf("a"), listOf("a")), got) + } + + @Test + fun `equal sizes and the same refresh read as one line`() { + assertEquals("25 songs each · refreshed today", shelfMeta(listOf(mix(tracks = 25), mix(tracks = 25)), now, utc)) + } + + @Test + fun `sizes within a tenth of each other read as about`() { + val mixes = listOf(95, 97, 99, 100).map { mix(tracks = it) } + assertEquals("About 100 songs each · refreshed today", shelfMeta(mixes, now, utc)) + } + + @Test + fun `sizes that differ widely are left to the tiles`() { + assertEquals("Refreshed today", shelfMeta(listOf(mix(tracks = 20), mix(tracks = 100)), now, utc)) + } + + @Test + fun `user playlists do not count, and a shelf of only them says nothing`() { + val mine = mix(tracks = 3, variant = null, createdAt = "2025-01-01T00:00:00Z") + assertEquals("", shelfMeta(listOf(mine), now, utc)) + assertEquals("50 songs each · refreshed today", shelfMeta(listOf(mix(tracks = 50), mine), now, utc)) + } + + @Test + fun `different refresh days are not summarised`() { + val mixes = listOf(mix(), mix(createdAt = "2026-11-20T08:00:00Z")) + assertEquals("100 songs each", shelfMeta(mixes, now, utc)) + } + + @Test + fun `refreshed label counts calendar days`() { + val noon = Instant.parse("2026-11-23T12:00:00Z") + assertEquals("Refreshed yesterday", refreshedLabel("2026-11-22T12:00:00Z", noon, utc)) + assertEquals("Refreshed 3 days ago", refreshedLabel("2026-11-20T12:00:00Z", noon, utc)) + assertEquals("", refreshedLabel("not a date", noon, utc)) + } + + @Test + fun `songs like tiles drop the shelf-wide prefix`() { + assertEquals("Low Tide Choir", songsLikeArtist(mix(name = "Songs like Low Tide Choir"))) + assertEquals("Something else", songsLikeArtist(mix(name = "Something else"))) + } + + @Test + fun `a dark cover keeps its own colour`() { + assertEquals(Rgb(30, 60, 90), washTone(Rgb(30, 60, 90))) + } + + // A tile's gradient is the tone mixed 62% toward #0e1013 at its lightest + // end. Its text is parchment at 90% or more; this checks 80%, a margin + // the web client's tiles also hold to. + @ParameterizedTest(name = "{0} cover") + @MethodSource("lightCovers") + fun `a light or loud cover still leaves the faintest text at 4_5 to 1`(name: String, cover: Rgb) { + val ground = blend(washTone(cover).toD(), 0.62, Triple(14.0, 16.0, 19.0)) + val text = blend(Triple(232.0, 228.0, 216.0), 0.8, ground) + val ratio = (lum(text) + 0.05) / (lum(ground) + 0.05) + assertTrue(ratio >= 4.5, "$name: $ratio") + } + + private fun Rgb.toD() = Triple(r.toDouble(), g.toDouble(), b.toDouble()) + + private fun blend(a: Triple, t: Double, b: Triple) = Triple( + a.first * t + b.first * (1 - t), + a.second * t + b.second * (1 - t), + a.third * t + b.third * (1 - t), + ) + + private fun lum(c: Triple): Double { + fun ch(v: Double): Double { + val s = v / 255 + return if (s <= 0.03928) s / 12.92 else ((s + 0.055) / 1.055).pow(2.4) + } + return 0.2126 * ch(c.first) + 0.7152 * ch(c.second) + 0.0722 * ch(c.third) + } + + companion object { + @JvmStatic + fun lightCovers() = listOf( + arrayOf("beige", Rgb(200, 190, 160)), + arrayOf("near white", Rgb(245, 245, 245)), + arrayOf("acid yellow", Rgb(240, 240, 20)), + arrayOf("light grey", Rgb(170, 175, 180)), + ) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt new file mode 100644 index 00000000..6a091be4 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt @@ -0,0 +1,64 @@ +package com.fabledsword.minstrel.playlists.data + +import com.fabledsword.minstrel.models.PlaylistRef +import com.fabledsword.minstrel.models.PlaylistTrackRef +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** How the playlist screen shows a change before the server's copy comes back. */ +class PlaylistEditsTest { + + private fun row(position: Int, trackId: String?) = PlaylistTrackRef( + position = position, + trackId = trackId, + title = trackId ?: "gone", + albumId = null, + artistId = null, + ) + + private fun detail(vararg ids: String?) = PlaylistDetailRef( + playlist = PlaylistRef(id = "p", userId = "me", name = "Road Songs", trackCount = ids.size), + tracks = ids.mapIndexed { i, id -> row(i, id) }, + ) + + private fun PlaylistDetailRef.ids() = tracks.map { it.trackId } + + private fun PlaylistDetailRef.positions() = tracks.map { it.position } + + @Test + fun `removing an entry closes the gap and counts one fewer`() { + val out = detail("a", "b", "c").withoutEntry(1) + assertEquals(listOf("a", "c"), out.ids()) + assertEquals(listOf(0, 1), out.positions()) + assertEquals(2, out.playlist.trackCount) + } + + @Test + fun `moving an entry down and back up`() { + val down = detail("a", "b", "c").withEntryMoved(0, 2) + assertEquals(listOf("b", "c", "a"), down.ids()) + assertEquals(listOf(0, 1, 2), down.positions()) + assertEquals(listOf("a", "b", "c"), down.withEntryMoved(2, 0).ids()) + } + + @Test + fun `a move nowhere or out of range changes nothing`() { + val d = detail("a", "b") + assertSame(d, d.withEntryMoved(1, 1)) + assertSame(d, d.withEntryMoved(0, 5)) + assertSame(d, d.withoutEntry(-1)) + } + + @Test + fun `the order sent leaves out an entry whose song has left the library`() { + assertEquals(listOf("a", "b"), detail("a", null, "b").trackOrder()) + } + + @Test + fun `entry keys stay with the entry when an earlier one goes`() { + val d = detail("a", "b", "a", null) + assertEquals(listOf("a#1", "b#1", "a#2", "gone#1"), d.entryKeys()) + assertEquals(listOf("a#1", "a#2", "gone#1"), d.withoutEntry(1).entryKeys()) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt index b93d938e..c30a3d65 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt @@ -3,49 +3,30 @@ package com.fabledsword.minstrel.playlists.data import com.fabledsword.minstrel.cache.db.dao.PlaylistCachedCount import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue class PlaylistsRepositoryCacheMergeTest { private fun playlist(id: String, trackCount: Int) = CachedPlaylistEntity(id = id, userId = "u", name = id, trackCount = trackCount) - @Test - fun `fully cached when every member track is resident`() { + // Fully cached means every member track is resident; an empty playlist + // never is, and no count row means nothing is resident. + @ParameterizedTest(name = "{0} of {1} resident -> {2}") + @CsvSource( + "3, 3, true", + "2, 3, false", + ", 3, false", + "0, 0, false", + ) + fun `fully cached only when every track is resident`(cached: Int?, tracks: Int, want: Boolean) { val out = mergePlaylistsWithCache( - rows = listOf(playlist("p", trackCount = 3)), - counts = listOf(PlaylistCachedCount("p", cachedCount = 3)), + rows = listOf(playlist("p", trackCount = tracks)), + counts = listOfNotNull(cached?.let { PlaylistCachedCount("p", cachedCount = it) }), ) - assertTrue(out.single().fullyCached) - } - - @Test - fun `not fully cached when only some tracks are resident`() { - val out = mergePlaylistsWithCache( - rows = listOf(playlist("p", trackCount = 3)), - counts = listOf(PlaylistCachedCount("p", cachedCount = 2)), - ) - assertFalse(out.single().fullyCached) - } - - @Test - fun `not fully cached when no tracks are resident (missing count row)`() { - val out = mergePlaylistsWithCache( - rows = listOf(playlist("p", trackCount = 3)), - counts = emptyList(), - ) - assertFalse(out.single().fullyCached) - } - - @Test - fun `empty playlist is never fully cached`() { - val out = mergePlaylistsWithCache( - rows = listOf(playlist("p", trackCount = 0)), - counts = listOf(PlaylistCachedCount("p", cachedCount = 0)), - ) - assertFalse(out.single().fullyCached) + assertEquals(want, out.single().fullyCached) } @Test @@ -61,4 +42,24 @@ class PlaylistsRepositoryCacheMergeTest { assertEquals(true, byId.getValue("full").fullyCached) assertEquals(false, byId.getValue("partial").fullyCached) } + + @Test + fun `cover albums and creation time come back from the cached row`() { + val row = playlist("p", trackCount = 3).copy(coverAlbumIds = "a1,a2", createdAt = "2026-11-23T08:00:00Z") + val out = mergePlaylistsWithCache(rows = listOf(row), counts = emptyList()).single() + assertEquals(listOf("a1", "a2"), out.coverAlbumIds) + assertEquals("2026-11-23T08:00:00Z", out.createdAt) + } + + @Test + fun `a genre mix keeps its shelf rank through the cache`() { + val row = playlist("p", trackCount = 3).copy(shelfRank = 2) + assertEquals(2, mergePlaylistsWithCache(rows = listOf(row), counts = emptyList()).single().shelfRank) + } + + @Test + fun `a row cached before cover albums existed has none`() { + val out = mergePlaylistsWithCache(rows = listOf(playlist("p", trackCount = 3)), counts = emptyList()) + assertEquals(emptyList(), out.single().coverAlbumIds) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt new file mode 100644 index 00000000..4abc740c --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt @@ -0,0 +1,142 @@ +package com.fabledsword.minstrel.playlists.data + +import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest +import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest +import com.fabledsword.minstrel.api.endpoints.PlaylistsApi +import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao +import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao +import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity +import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.PlaylistAppendPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistCreatePayload +import com.fabledsword.minstrel.cache.mutations.PlaylistRemoveTrackPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistReorderPayload +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.models.UserRef +import com.fabledsword.minstrel.models.wire.PlaylistsListWire +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.runTest +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.jupiter.api.Test +import retrofit2.HttpException +import retrofit2.Response +import retrofit2.Retrofit +import java.io.IOException +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * A listener's playlist changes are offline-first: the device shows each at + * once, sends it, and queues it when the server can't be reached. + */ +class PlaylistsRepositoryWritesTest { + private val api: PlaylistsApi = mockk(relaxed = true) + private val playlistDao: CachedPlaylistDao = mockk(relaxed = true) + private val trackDao: CachedPlaylistTrackDao = mockk(relaxed = true) + private val queue: MutationQueue = mockk(relaxed = true) + private val auth: AuthController = mockk { + every { currentUser } returns MutableStateFlow(UserRef(id = "me", username = "me")) + } + private val retrofit: Retrofit = mockk { + every { create(PlaylistsApi::class.java) } returns api + } + private val repo = PlaylistsRepository(playlistDao, trackDao, queue, auth, retrofit) + + @Test + fun `a new playlist is shown at once and sent under the id the device made`() = runTest { + val sent = slot() + coEvery { api.create(capture(sent)) } returns Unit + val shown = slot>() + coEvery { playlistDao.upsertAll(capture(shown)) } returns Unit + + val (id, outcome) = repo.createPlaylist("Road Songs") + + assertEquals(WriteOutcome.Synced, outcome) + assertEquals(id, sent.captured.id) + assertEquals(listOf(id), shown.captured.map { it.id }) + assertEquals("me", shown.captured.single().userId) + coVerify(exactly = 0) { queue.enqueuePlaylistCreate(any()) } + } + + @Test + fun `a new playlist made offline is queued under the same id`() = runTest { + coEvery { api.create(any()) } throws IOException("offline") + val queued = slot() + coEvery { queue.enqueuePlaylistCreate(capture(queued)) } returns 1L + + val (id, outcome) = repo.createPlaylist("Road Songs") + + assertEquals(WriteOutcome.Queued, outcome) + assertEquals(PlaylistCreatePayload(id = id, name = "Road Songs"), queued.captured) + } + + @Test + fun `an append whose reply is lost is queued under the request id it was sent with`() = runTest { + val sent = slot() + coEvery { api.appendTracks("p1", capture(sent)) } throws IOException("reply lost") + val queued = slot() + coEvery { queue.enqueuePlaylistAppend(capture(queued)) } returns 1L + + val outcome = repo.appendTrack("p1", "t1") + + assertEquals(WriteOutcome.Queued, outcome) + assertNotNull(sent.captured.requestId) + assertEquals(PlaylistAppendPayload("p1", listOf("t1"), sent.captured.requestId), queued.captured) + } + + @Test + fun `a removal made offline is queued with the song expected at that place`() = runTest { + coEvery { api.removeTrack(any(), any(), any()) } throws IOException("offline") + + repo.removeTrack("p1", position = 2, trackId = "t3") + + coVerify { trackDao.deleteTracksFromPlaylist("p1", listOf("t3")) } + coVerify { queue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload("p1", 2, "t3")) } + } + + @Test + fun `a reorder sends the songs in their new order`() = runTest { + repo.reorderTracks("p1", listOf("t2", "t1")) + + coVerify { api.reorder("p1", ReorderTracksRequest(trackIds = listOf("t2", "t1"))) } + coVerify(exactly = 0) { queue.enqueuePlaylistReorder(any()) } + } + + @Test + fun `a reorder made offline is queued`() = runTest { + coEvery { api.reorder(any(), any()) } throws IOException("offline") + + repo.reorderTracks("p1", listOf("t2", "t1")) + + coVerify { queue.enqueuePlaylistReorder(PlaylistReorderPayload("p1", listOf("t2", "t1"))) } + } + + @Test + fun `a change the server refuses is not queued`() = runTest { + coEvery { api.delete("p1") } throws HttpException(Response.error(403, "".toResponseBody())) + + val result = runCatching { repo.deletePlaylist("p1") } + + assertTrue(result.exceptionOrNull() is HttpException) + + coVerify(exactly = 0) { queue.enqueuePlaylistDelete(any()) } + } + + @Test + fun `a list refresh keeps a playlist whose create hasn't been sent`() = runTest { + coEvery { api.list(any()) } returns PlaylistsListWire() + coEvery { queue.pendingPlaylistCreateIds() } returns setOf("made-offline") + + repo.refreshList() + + coVerify { playlistDao.replaceList("me", listOf("made-offline"), emptyList()) } + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/PasswordViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/PasswordViewModelTest.kt new file mode 100644 index 00000000..f169f638 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/PasswordViewModelTest.kt @@ -0,0 +1,42 @@ +package com.fabledsword.minstrel.settings.ui + +import com.fabledsword.minstrel.auth.PasswordRules +import com.fabledsword.minstrel.settings.data.MeRepository +import com.fabledsword.minstrel.testutil.MainDispatcherExtension +import io.mockk.coVerify +import io.mockk.mockk +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import kotlin.test.assertEquals + +/** + * A new password is checked as the web app checks it, with the same words, + * before anything is sent: at least 8 characters, and the same twice. + */ +@ExtendWith(MainDispatcherExtension::class) +class PasswordViewModelTest { + private val repository: MeRepository = mockk(relaxed = true) + + private fun attempt(next: String, confirm: String): PasswordViewModel = + PasswordViewModel(repository).apply { + setCurrent("old-password") + setNext(next) + setConfirm(confirm) + change() + } + + @Test + fun `a password shorter than 8 characters is refused without asking the server`() { + val viewModel = attempt(next = "short", confirm = "short") + assertEquals("Password must be at least 8 characters.", viewModel.state.value.message) + coVerify(exactly = 0) { repository.changePassword(any(), any(), any()) } + } + + @Test + fun `a confirmation that differs says so as the web does`() { + val viewModel = attempt(next = "long-enough-1", confirm = "long-enough-2") + assertEquals(PasswordRules.DIFFER, viewModel.state.value.message) + assertEquals("Passwords do not match.", PasswordRules.DIFFER) + coVerify(exactly = 0) { repository.changePassword(any(), any(), any()) } + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/ProfileViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/ProfileViewModelTest.kt new file mode 100644 index 00000000..7af1912b --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/ProfileViewModelTest.kt @@ -0,0 +1,57 @@ +package com.fabledsword.minstrel.settings.ui + +import com.fabledsword.minstrel.models.MyProfile +import com.fabledsword.minstrel.settings.data.MeRepository +import com.fabledsword.minstrel.testutil.MainDispatcherExtension +import io.mockk.coEvery +import io.mockk.mockk +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import java.io.IOException +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * A profile that failed to load is reported as a load failure, which the + * card shows as Try again in place of the form. Reported as an ordinary + * message, it would leave the form up with blank fields that Save would + * write over the real profile. + */ +@ExtendWith(MainDispatcherExtension::class) +class ProfileViewModelTest { + private val profile = MyProfile( + id = "u1", + username = "listener", + displayName = "A Listener", + email = "listener@example.com", + isAdmin = false, + ) + + @Test + fun `a failed load is a load error, not a form message`() { + val repository: MeRepository = mockk { + coEvery { getProfile() } throws IOException("unreachable") + } + + val state = ProfileViewModel(repository).state.value + + assertNotNull(state.loadError) + assertNull(state.message) + assertNull(state.loadedProfile) + } + + @Test + fun `try again after a failed load fills the form`() { + val repository: MeRepository = mockk() + coEvery { repository.getProfile() } throws IOException("unreachable") andThen profile + val viewModel = ProfileViewModel(repository) + + viewModel.refresh() + + val state = viewModel.state.value + assertNull(state.loadError) + assertEquals("A Listener", state.displayName) + assertEquals("listener@example.com", state.email) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/shared/PluralTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/shared/PluralTest.kt new file mode 100644 index 00000000..c502fade --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/shared/PluralTest.kt @@ -0,0 +1,50 @@ +package com.fabledsword.minstrel.shared + +import org.junit.jupiter.api.Test +import java.io.File +import java.util.Locale +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class PluralTest { + @Test + fun `says a count with the noun that agrees with it, in the listener's number format`() { + val saved = Locale.getDefault() + Locale.setDefault(Locale.US) + try { + assertEquals("1 track", plural(1, "track", "tracks")) + assertEquals("0 tracks", plural(0, "track", "tracks")) + assertEquals("12,345 tracks", plural(12_345, "track", "tracks")) + } finally { + Locale.setDefault(saved) + } + } + + // One way to say a count, so every count agrees on wording and the + // thousands separator. A hand-written copy has a tell this guard looks for: + // - a branch that spells the one: `if (n == 1) "1 album" else ...`; + // - the number beside a choice of noun: `"${n} ${if (n == 1) ...}"`; + // - a choice of noun alone: `if (n == 1) "track" else "tracks"`; + // - a count with a fixed plural, which reads "1 tracks": `"${x.trackCount} tracks"`. + private val handRolled = listOf( + Regex("""== 1\) "1 """), + Regex("""\$\{?([\w.]+)\}? \$\{if \(\1 == 1\)"""), + Regex("""== 1\) "[a-z]+" else "[a-z]+s""""), + Regex("""\$\{[\w.]+(?:Count|\.size)\} (?:tracks|albums|songs|artists|playlists|files|users)\b"""), + ) + + /** Comments describe the forbidden shape; strip them before asserting its absence. */ + private fun stripComments(s: String) = s.replace(Regex("""^\s*(//|\*|/\*).*$""", RegexOption.MULTILINE), "") + + @Test + fun `every count in the app is said by plural()`() { + val root = File("src/main/java") + val sources = root.walkTopDown().filter { it.extension == "kt" }.toList() + assertTrue(sources.size > 100, "expected the app's sources under ${root.absolutePath}") + val offenders = sources.filter { f -> + val text = stripComments(f.readText()) + handRolled.any { it.containsMatchIn(text) } + }.map { it.relativeTo(root).path } + assertEquals(emptyList(), offenders) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt new file mode 100644 index 00000000..53561202 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt @@ -0,0 +1,59 @@ +package com.fabledsword.minstrel.shared.widgets + +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import kotlin.test.assertEquals + +/** + * The drag-to-reorder math shared by the queue and playlists. The delta cases mirror web's + * queue-row-math.test.ts one for one, so a change to either client's + * rounding shows up as a disagreement here rather than as a drop that lands + * one row off on one platform only. + */ +class ReorderDragMathTest { + + @ParameterizedTest(name = "{0}px on {1}px rows -> {2}") + @CsvSource( + "0, 64, 0", + "64, 64, 1", + "31, 64, 0", + "32, 64, 1", + "56, 56, 1", + "28, 56, 1", + "192, 64, 3", + "-64, 64, -1", + "-32, 64, 0", // ties toward positive infinity, as in JS + "-128, 64, -2", + "100, 0, 0", // a row not yet measured moves nothing + "100, -1, 0", + ) + fun `a drag moves by the whole rows it crosses, half a row counting as one`( + offset: Float, + rowHeight: Int, + want: Int, + ) { + assertEquals(want, reorderDragDelta(offset, rowHeight)) + } + + @Test + fun `a drag past either end stops at the first or last row`() { + assertEquals(0, reorderDragTarget(index = 1, offsetPx = -640f, rowHeightPx = 64, count = 5)) + assertEquals(4, reorderDragTarget(index = 3, offsetPx = 640f, rowHeightPx = 64, count = 5)) + } + + @Test + fun `a sub-half-row drag lands where it started`() { + assertEquals(2, reorderDragTarget(index = 2, offsetPx = 20f, rowHeightPx = 64, count = 5)) + } + + @Test + fun `before the row is measured a drag lands where it started`() { + assertEquals(2, reorderDragTarget(index = 2, offsetPx = 300f, rowHeightPx = 0, count = 5)) + } + + @Test + fun `an empty queue does not throw`() { + assertEquals(0, reorderDragTarget(index = 0, offsetPx = 64f, rowHeightPx = 64, count = 0)) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt index 1e295e79..5b783995 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt @@ -60,11 +60,6 @@ class UpdateRepositoryTest { assertIs(repo().check()) } - @Test - fun `the same app built again at a later minute is not offered`() = runTest { - assertEquals(Offer.Current, repo(version = { wire(version = "2026.10.20.0900") }).check()) - } - @Test fun `a server with no app to offer is not a problem`() = runTest { val none = repo(version = { throw HttpException(Response.error(404, "".toResponseBody())) }) @@ -92,6 +87,16 @@ class UpdateRepositoryTest { assertEquals(1, downloads) } + @Test + fun `the download under way is visible to anyone waiting on it, and settles back to zero`() = runTest { + val r = repo() + val info = (r.check() as Offer.Newer).info + val seen = mutableListOf() + r.download(info) { done -> seen += r.downloadProgress.value.also { assertEquals(done, it) } } + assertEquals(1f, seen.last()) + assertEquals(0f, r.downloadProgress.value) + } + @Test fun `a download cut off partway is not taken for the build`() = runTest { val r = repo(body = { apkBytes.copyOf(5) }) diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index 1f6a799d..2780adfa 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -64,6 +64,7 @@ okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } okhttp-logging = { module = "com.squareup.okhttp3:logging-interceptor", version.ref = "okhttp" } okhttp-sse = { module = "com.squareup.okhttp3:okhttp-sse", version.ref = "okhttp" } okhttp-mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "okhttp" } +okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okhttp" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } diff --git a/ci-requirements.md b/ci-requirements.md index d5418f6f..7aa1482c 100644 --- a/ci-requirements.md +++ b/ci-requirements.md @@ -12,7 +12,7 @@ git.fabledsword.com/bvandeusen/ci-go:1.26 git.fabledsword.com/bvandeusen/ci-android:36 ``` -- `ci-go:1.26` — the `go`, `integration` and `web` lanes, `release-assets`, and the container build (`image-release`). All CI lives in that one workflow so every publishing job can depend on every lane. +- `ci-go:1.26` — the `go`, `integration` and `web` lanes, and the container build and public release (`image-release`). All CI lives in that one workflow so every publishing job can depend on every lane. - `golang:1.26-bookworm` (Docker Hub) — the `govulncheck` lane. Deliberately the same image as the Dockerfile's builder stage rather than `ci-go`, so the standard library it checks is the one in the shipped binary. Keep the two in step. - `ci-android:36` — native Kotlin/Compose client: ktlint + detekt + unit tests (the `android` lane), and the signed release APK (`android-release`). @@ -28,7 +28,7 @@ while pulling `ci-android:36`, per the label/image split below. - **golangci-lint** — lint pass in the `go` lane. - **docker CLI** — bridge-IP discovery of the per-job Postgres service container in the `integration` lane (via the runner's shared `/var/run/docker.sock`). - **docker buildx** — release container build + push in `release.yml`. -- **curl** — release-asset polling / upload in `release.yml`. +- **git, perl, node** — the public release in `image-release`: `git archive` for the export, `ci/leakgate.sh` (perl joins comment lines), `ci/releases.mjs` (node's fetch) for the release pages on GitHub and this forge. ### From `ci-android:36` - **JDK 25** — Gradle launcher + Android build. Requires Gradle 9.1.0+ in @@ -41,8 +41,7 @@ while pulling `ci-android:36`, per the label/image split below. the `android` lane. Image pins track `android/gradle/libs.versions.toml` so local and CI checks agree. - **git** — `actions/checkout@v4` baseline (and any shell git operations). -- **base64 + curl** — keystore decode + release-asset upload in `release.yml`'s - `android-release` job. +- **base64** — keystore decode in `release.yml`'s `android-release` job. ## Per-job tool installs @@ -53,7 +52,8 @@ None. - **Label/image split.** Workflows keep `runs-on: go-ci` / `runs-on: flutter-ci` as the scheduling label per the [`ci-runners.md`](https://…/FabledRulebook/ci-runners.md) "label = scheduling handle, image = `container.image`" pattern. The labels are intentional handles, not toolchain assertions — which is why the Android jobs still schedule on `flutter-ci` while pulling `ci-android:36`. Switch them to `android-ci` if that runner label is ever registered; nothing breaks either way. - **Integration-job docker-socket dependency.** The `integration` lane uses the runner's shared docker socket (`/var/run/docker.sock`) to bridge-IP-discover the per-job Postgres service container by name + network intersection — the dev compose's `minstrel-postgres-*` containers are explicitly skipped as belt-and-suspenders. Depends on `act_runner.valid_volumes` whitelisting the socket; if that ever stops auto-mounting, integration tests fail at the `docker inspect` step. - **Go toolchain pin.** `go.mod` is on `go 1.25.0` because `golang.org/x/crypto v0.51.0` declares 1.25 as its minimum. `ci-go:1.26` satisfies this with headroom. Future `x/crypto` bumps that move the Go floor should be paired with an image-tag bump in this file + the workflows. -- **In-app update channel — `needs:`, not polling.** `release.yml`'s `image-release` job declares `needs: [android-release]`, so on dev and tag pushes the signed APK is guaranteed present before the image build starts — no polling window, no race. On `main` pushes `android-release` is skipped and `image-release` instead pulls the most recent release's APK and the version sidecar recorded beside it, so `:latest` never ships without an update channel. It degrades to an empty `client/` — never a wrong version — if no release or APK asset can be resolved. +- **In-app update channel — `needs:`, not polling.** `release.yml`'s `image-release` job declares `needs: [android-release]`, so on dev and main pushes the signed APK built from the same commit is guaranteed present before the image build starts — no polling window, no race. No APK is attached to any release page; phones get the app from the server image. +- **Public release secrets.** `PUBLIC_PUSH_TOKEN` (push to github.com/Fabled-Sword/minstrel and create its releases), `GHCR_USER` and `GHCR_TOKEN` (push to ghcr.io/fabled-sword/minstrel), and `CI_TOKEN` (this forge's release page). A dev push warns when one is missing; a main push stops before anything is pushed. - **Cache server reachability.** The `web` lane does NOT use `cache: 'npm'` on `actions/setup-node` — the Gitea Actions cache server isn't reachable from this runner's container network, so `setup-node` would spend minutes on ETIMEDOUT before failing open. `setup-node` is not used at all (Node is in the image). The cache concern reappears if a change introduces a network-dependent action. - **Artifacts — stock `actions/upload-artifact@v7` and `actions/download-artifact@v8`; never `@v3`.** ```yaml diff --git a/ci/changelog-skip.txt b/ci/changelog-skip.txt new file mode 100644 index 00000000..aa324fc1 --- /dev/null +++ b/ci/changelog-skip.txt @@ -0,0 +1,3 @@ +# Commits ci/changelog.sh leaves out of the public changelog, one full hash per +# line, each with a comment saying why. For a subject that names something that +# must not be published; the private changelog still lists it. diff --git a/ci/changelog.sh b/ci/changelog.sh new file mode 100755 index 00000000..52aa0b17 --- /dev/null +++ b/ci/changelog.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# +# A release's changelog, in the two versions a release publishes: +# +# private.md every commit subject since the previous release, as written +# public.md the same list with record ids cut out ("(#1234)", "rule 12"), +# and the commits that only touch CI or tests left out, since +# neither ships +# +# The previous release is the newest public-release tag (v, from +# PUBLIC_SINCE on) that is not on the commit being released. With none, this is +# the first public release, and both versions are a fixed note rather than the +# whole history before it. +# +# PUBLIC_SINCE exists because this repository also holds older v* tags, from +# releases made on this forge alone before the public ones began. Those are not +# public releases, so a changelog never counts from them. +# +# A commit whose subject must not reach the public list (it names something +# private) is left out by listing its full hash in changelog-skip.txt. The +# subject itself is never rewritten: the history is not. +# +# Usage: ci/changelog.sh [] (default HEAD; needs the +# full history and tags, fetch-depth: 0) +set -euo pipefail + +readonly PUBLIC_SINCE='v2026.12.04' + +out="${1:?usage: $0 []}" +ref="${2:-HEAD}" +here="$(cd "$(dirname "$0")" && pwd)" +mkdir -p "$out" + +head="$(git rev-parse "$ref^{commit}")" +previous="" +for tag in $(git tag -l 'v*' --sort=-v:refname); do + # sort -V puts the older of the two first. + if [ "$(printf '%s\n%s\n' "$PUBLIC_SINCE" "$tag" | sort -V | head -1)" != "$PUBLIC_SINCE" ]; then + break + fi + if [ "$(git rev-parse "$tag^{commit}")" != "$head" ]; then + previous="$tag" + break + fi +done + +if [ -z "$previous" ]; then + note='The first public release of Fabled Minstrel, a self-hosted music server with its own Android app. The README says what it does and how to run it.' + printf '%s\n' "$note" >"$out/private.md" + printf '%s\n' "$note" >"$out/public.md" + echo "changelog: first release, the fixed note" + exit 0 +fi + +subjects="$(git log --no-merges --reverse --format='%H %s' "$previous..$head")" + +{ + printf 'Changes since %s:\n\n' "$previous" + printf '%s\n' "$subjects" | sed -E '/^$/d; s/^[0-9a-f]+ /- /' +} >"$out/private.md" + +skip="$(grep -oE '^[0-9a-f]{40}' "$here/changelog-skip.txt" || true)" +{ + printf 'Changes since %s:\n\n' "$previous" + printf '%s\n' "$subjects" | while IFS=' ' read -r hash subject; do + [ -n "$hash" ] || continue + if printf '%s\n' "$skip" | grep -qx "$hash"; then continue; fi + # The area before the colon, as a list: "server, web, ci". A type with a + # scope, "test(web)", counts by its type. + area="${subject%%:*}" + if [ "$area" != "$subject" ] && + ! printf '%s\n' "$area" | sed -E 's/\(.*\)//' | tr ',' '\n' | sed -E 's/^ +| +$//g' | + grep -qvxE 'ci|tests?|[a-z]+ tests?'; then + continue + fi + printf -- '- %s\n' "$subject" + done | sed -E ' + s/ *\(((rule|preference|lesson|snippet|process|milestone|task|issue) )?#?[0-9]+(, *#?[0-9]+)*\)//gI + s/ *\b(rule|preference|lesson|snippet|process|milestone|task|issue) #?[0-9]+//gI + s/ *#[0-9]{3,5}\b//g + s/ *\( *\)//g + s/ +([,;.])/\1/g + s/[,;] *$//' +} >"$out/public.md" + +echo "changelog: $(grep -c '^- ' "$out/private.md" || true) commits since $previous, $(grep -c '^- ' "$out/public.md" || true) public" diff --git a/ci/db-test-packages.sh b/ci/db-test-packages.sh new file mode 100755 index 00000000..5920d6a3 --- /dev/null +++ b/ci/db-test-packages.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# +# Prints the Go packages that hold database tests, one import path per line. +# +# A database test gets its Postgres from MINSTREL_TEST_DATABASE_URL, either +# through internal/dbtest or by reading the variable itself. A package whose +# tests mention neither cannot reach the database, so its tests are all unit +# tests: the `go` lane already runs them, and the `integration` lane skips the +# package instead of compiling and running it a second time, serially. +# +# Usage: go test -p 1 -race $(sh ci/db-test-packages.sh) +set -eu + +go list -f '{{if or .TestGoFiles .XTestGoFiles}}{{.ImportPath}} {{.Dir}}{{end}}' ./... | + while read -r pkg dir; do + if grep -qs -e 'dbtest\.' -e 'MINSTREL_TEST_DATABASE_URL' "$dir"/*_test.go; then + echo "$pkg" + fi + done diff --git a/ci/leak-allow.txt b/ci/leak-allow.txt new file mode 100644 index 00000000..91de4a7e --- /dev/null +++ b/ci/leak-allow.txt @@ -0,0 +1,20 @@ +# Known false positives of ci/leakgate.sh, one extended regex per line, matched +# without regard to case. Each is cut out of a hit line before the line is +# tested again, so keep a pattern as narrow as the thing it allows. + +# Words that contain a banned one. +jsonarray +readarray + +# Drawing paths: SVG d attributes, Android pathData, and the path strings the +# web and Android icon sets keep, all of which start with a moveto, "M12". +d="[^"]*"? +pathdata="[^"]*"? +'M[0-9][^']*' +# The continuation lines of a long drawing path: numbers and path commands only. +^[-0-9 .,cmlzhvsqta]+$ + +# Material 3, the Android design system, in comments about its defaults. +\bM3('s)?\b +# CSS colours in hex, written as design tokens. +--[a-z-]+: [#][0-9a-f]{3,6}; diff --git a/ci/leakgate.sh b/ci/leakgate.sh new file mode 100755 index 00000000..abf3b1e0 --- /dev/null +++ b/ci/leakgate.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# +# The automatic half of the leak standard, run on what a public release would +# publish: the exported tree and the public changelog. Two kinds of hit fail it: +# +# words that must never ship the names of tools and services this project +# has nothing to do with in public +# private record ids "#1234", "rule 12", "milestone 7": pointers into +# a tracker no reader of the release can open +# +# The ids are also searched with comment continuation lines joined, because a +# citation split at a line break ("see rule\n// 12") passes a per-line search. +# +# The by-eye half (people, titles, quotes, images) is not here: a search cannot +# decide it. +# +# Known false positives are listed in leak-allow.txt, one pattern per line. A +# pattern is cut out of a hit line before the line is tested again, so an +# allowed word never hides a real hit beside it. +# +# Usage: ci/leakgate.sh ... (directories are searched recursively) +# Prints each hit and exits 1 if there is one. +set -euo pipefail + +readonly HARD='sluice|storehouse|prospector|bookbag|musicbox|fabledexchange|lidarr|readarr|chaptarr|prowlarr|jackett|sonarr|radarr|qbittorrent|deluge|sabnzbd|nzbget|slskd|soulseek|deemix|torrent|usenet|\bnzb\b|magnet:|grimoire|\bscribe\b|traefik\.internal|vdnt' +readonly IDS='(\(|\s)#[0-9]{3,5}\b|\bM[0-9]{1,3}\b|\b(rule|preference|lesson|snippet|process|milestone) #?[0-9]{1,5}\b' +# Joined across comment lines, only the worded citations: the bare forms above +# are already whole on one line. +readonly JOINED='\b(?:rule|preference|lesson|snippet|process|milestone|task|issue)\s+#?\d{1,5}\b|\b(?:reference|measured)\s+library\b' + +[ "$#" -gt 0 ] || { echo "usage: $0 ..." >&2; exit 2; } + +here="$(cd "$(dirname "$0")" && pwd)" +strip="$(mktemp)" +trap 'rm -f "$strip"' EXIT +# One sed substitution per allowed pattern, case-insensitive like the search. +# \x01 delimits, so a pattern may hold any other character. +while IFS= read -r pattern; do + case "$pattern" in '' | '#'*) continue ;; esac + printf 's\x01%s\x01\x01gI\n' "$pattern" >>"$strip" +done <"$here/leak-allow.txt" + +# Reads grep's path:line:text and prints the hits that still match once the +# allowed patterns are cut out of the text. +still() { + local hit text + while IFS= read -r hit; do + text="${hit#*:*:}" + if printf '%s\n' "$text" | sed -E -f "$strip" | grep -qiE -- "$1"; then + printf '%s\n' "$hit" + fi + done +} + +found="$( + { + grep -rnHIiE -- "$HARD" "$@" || true + grep -rnHIiE -- "$IDS" "$@" || true + } | still "$HARD|$IDS" + # -I skips binary files, as grep does above. Each joined hit is printed as + # path:joined:text, so the same filter applies. + find "$@" -type f -exec grep -lIZ '' {} + 2>/dev/null \ + | xargs -0 -r perl -0777 -ne ' + s/\n[ \t]*(?:\/\/+|--|\*|#+)[ \t]*/ /g; + while (/('"$JOINED"')/gi) { (my $m = $1) =~ s/\s+/ /g; print "$ARGV:joined:$m\n" }' \ + | still "$(printf '%s' "$JOINED" | sed -E 's/\(\?:/(/g; s/\\s/[[:space:]]/g; s/\\d/[0-9]/g')" +)" + +if [ -n "$found" ]; then + printf '%s\n' "$found" | sort -u + echo "leakgate: the hits above would be published; reword them, or list a false positive in ci/leak-allow.txt" >&2 + exit 1 +fi +echo "leakgate: clean" diff --git a/ci/release_test.go b/ci/release_test.go new file mode 100644 index 00000000..8b63fe06 --- /dev/null +++ b/ci/release_test.go @@ -0,0 +1,175 @@ +package ci + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// leakgate runs leakgate.sh over one file holding text, and says whether it +// passed. +func leakgate(t *testing.T, text string) (bool, string) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "f.go"), []byte(text), 0o644); err != nil { + t.Fatal(err) + } + out, err := exec.Command("bash", "leakgate.sh", dir).CombinedOutput() + return err == nil, string(out) +} + +// The gate fails on a banned word or a private record id, wherever it sits on +// the line, and passes the known false positives. +func TestTheLeakGateRefusesWhatMustNotBePublished(t *testing.T) { + for _, c := range []struct{ name, text string }{ + {"a banned word", "// a folder some downloader called Lidarr made\n"}, + {"a banned word in a fixture path", `{".sluice-held/Artist/01.flac", true},` + "\n"}, + {"a banned word beside an allowed one", "var list JsonArray // the torrent's files\n"}, + {"a ticket", "// fixed in (#4321)\n"}, + {"a worded citation", "// as milestone 635 decided\n"}, + {"a short milestone id", "// added in m7-scan-progress\n"}, + {"a citation split across comment lines", "// as the rule\n// 12 says\n"}, + {"a library measured, split across lines", "// counted on the reference\n// library\n"}, + {"an id beside a drawing path", " see rule 9\n"}, + {"an id beside Material 3", "// M3's default, as M12 chose\n"}, + } { + if passed, out := leakgate(t, c.text); passed { + t.Errorf("%s: passed %q\n%s", c.name, c.text, out) + } + } +} + +func TestTheLeakGatePassesItsKnownFalsePositives(t *testing.T) { + text := strings.Join([]string{ + "import kotlinx.serialization.json.JsonArray", + ``, + `android:pathData="M17,3H7c-1.1,0 -1.99,0.9 -1.99,2L5,21z" />`, + `back: 'M15 5l-7 7 7 7',`, + "97 -322 147 -488 125z m928 -812 c53 -27 39 -34", + "// M3 inactive default is secondaryContainer; drops M3's stop", + `expect(css).toMatch(/--fs-obsidian: #000;[\s\S]*--fs-parchment: #FFF;/);`, + "// a song called the rule of three is fine", + }, "\n") + "\n" + if passed, out := leakgate(t, text); !passed { + t.Errorf("refused a known false positive:\n%s", out) + } +} + +// repo makes a git repository whose commits carry the given subjects, and +// returns its path. +func repo(t *testing.T, subjects ...string) string { + t.Helper() + dir := t.TempDir() + git(t, dir, "init", "-q", "-b", "main") + for _, s := range subjects { + commit(t, dir, s) + } + return dir +} + +// commit makes one commit with the given subject, changing a file so that it +// is never empty. +func commit(t *testing.T, dir, subject string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, "f"), []byte(subject), 0o644); err != nil { + t.Fatal(err) + } + git(t, dir, "add", "f") + git(t, dir, "commit", "-q", "-m", subject) +} + +func git(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@example.com"}, args...)...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) +} + +// changelog runs changelog.sh in dir and returns the private and public lists. +func changelog(t *testing.T, dir string) (string, string) { + t.Helper() + script, err := filepath.Abs("changelog.sh") + if err != nil { + t.Fatal(err) + } + out := t.TempDir() + cmd := exec.Command("bash", script, out) + cmd.Dir = dir + if msg, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("changelog.sh: %v\n%s", err, msg) + } + read := func(name string) string { + b, err := os.ReadFile(filepath.Join(out, name)) + if err != nil { + t.Fatal(err) + } + return string(b) + } + return read("private.md"), read("public.md") +} + +// The first public release has no public release before it, and its changelog +// is the fixed note rather than every commit the project ever made. A v* tag +// from before the public releases began is not a public release, so it does +// not count as one. +func TestTheFirstReleaseIsAFixedNote(t *testing.T) { + dir := repo(t, "library: the first commit") + git(t, dir, "tag", "v2026.10.26.1520") + commit(t, dir, "web: after the forge-only release") + private, public := changelog(t, dir) + if private != public || strings.Contains(public, "web:") || !strings.Contains(public, "first public release") { + t.Errorf("private %q, public %q: want the same fixed note", private, public) + } +} + +// A later release lists what changed since the previous one. The public list +// loses its record ids and the commits that only touch CI or tests. +func TestALaterReleaseListsWhatChangedSinceThePrevious(t *testing.T) { + dir := repo(t, "library: before the release") + git(t, dir, "tag", "v2026.12.05.0000") + for _, s := range []string{ + "fix(library): a song keeps its title (#4321)", + "web, ci: a page and its lane (rule 12, #77)", + "ci: a faster lane", + "test(web): one test fewer", + "web tests: one more", + "server, tests: a route, as milestone 635 asks", + } { + commit(t, dir, s) + } + + private, public := changelog(t, dir) + if strings.Contains(private, "before the release") { + t.Errorf("the private list reaches past the previous release:\n%s", private) + } + if !strings.Contains(private, "(#4321)") || !strings.Contains(private, "- ci: a faster lane") { + t.Errorf("the private list is not as written:\n%s", private) + } + want := "Changes since v2026.12.05.0000:\n\n" + + "- fix(library): a song keeps its title\n" + + "- web, ci: a page and its lane\n" + + "- server, tests: a route, as asks\n" + if public != want { + t.Errorf("public list:\n%s\nwant:\n%s", public, want) + } +} + +// A re-run of a release finds its own tag on the commit, and lists from the +// release before it. +func TestARerunListsFromTheReleaseBefore(t *testing.T) { + dir := repo(t, "library: before") + git(t, dir, "tag", "v2026.12.05.0000") + commit(t, dir, "web: after") + git(t, dir, "tag", "v2026.12.06.0000") + _, public := changelog(t, dir) + if !strings.Contains(public, "since v2026.12.05.0000") || !strings.Contains(public, "- web: after") { + t.Errorf("re-run list:\n%s", public) + } +} diff --git a/ci/releases.mjs b/ci/releases.mjs new file mode 100644 index 00000000..076d725c --- /dev/null +++ b/ci/releases.mjs @@ -0,0 +1,106 @@ +// Creates a release's page on a forge, or updates it in place when the run is +// repeated, so a re-run never fails on the release it made the first time. +// +// node ci/releases.mjs github +// the public repository's GitHub Release, with PUBLIC_PUSH_TOKEN. The tag +// must already be pushed there. +// node ci/releases.mjs forge +// this repository's release on its own forge, with FORGE_TOKEN, tagging +// when the tag does not exist yet. +// node ci/releases.mjs forge-probe +// whether FORGE_TOKEN may write releases, without writing one: an update +// of a release that does not exist answers 404 to a token that may, and +// 403 to one that may not. +// +// Prints the release's page. +import { readFileSync } from 'node:fs'; + +const PUBLIC_REPO = 'Fabled-Sword/minstrel'; + +const [kind, tag, bodyFile, commit] = process.argv.slice(2); + +function need(name) { + const value = process.env[name]; + if (!value) throw new Error(`${name} is empty or unset`); + return value; +} + +async function call(method, url, headers, body) { + const res = await fetch(url, { + method, + headers: { 'Content-Type': 'application/json', ...headers }, + body: body === undefined ? undefined : JSON.stringify(body) + }); + const text = await res.text(); + return { status: res.status, json: text ? safeJSON(text) : null, text }; +} + +function safeJSON(text) { + try { + return JSON.parse(text); + } catch { + return null; + } +} + +function ok(res, what) { + if (res.status < 200 || res.status >= 300) { + throw new Error(`${what}: HTTP ${res.status} ${res.text.slice(0, 300)}`); + } + return res.json; +} + +// The same steps on either forge: find the release by its tag, then update it +// or create it. +async function upsert(api, headers, fields) { + const found = await call('GET', `${api}/releases/tags/${encodeURIComponent(tag)}`, headers); + if (found.status === 200) { + return ok(await call('PATCH', `${api}/releases/${found.json.id}`, headers, fields), 'update'); + } + if (found.status !== 404) ok(found, 'look up'); + return ok(await call('POST', `${api}/releases`, headers, { tag_name: tag, ...fields }), 'create'); +} + +async function main() { + if (kind === 'forge-probe') { + const res = await call( + 'PATCH', + `${need('GITHUB_SERVER_URL')}/api/v1/repos/${need('GITHUB_REPOSITORY')}/releases/0`, + { Authorization: `token ${need('FORGE_TOKEN')}` }, + {} + ); + if (res.status !== 404) throw new Error(`the token may not write releases: HTTP ${res.status} ${res.text.slice(0, 200)}`); + console.log('the forge token may write releases'); + return; + } + if (!tag || !bodyFile) throw new Error('usage: node ci/releases.mjs github|forge []'); + const body = readFileSync(bodyFile, 'utf8'); + const name = `Fabled Minstrel ${tag}`; + let release; + if (kind === 'github') { + release = await upsert( + `https://api.github.com/repos/${PUBLIC_REPO}`, + { + Authorization: `Bearer ${need('PUBLIC_PUSH_TOKEN')}`, + Accept: 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28' + }, + { name, body } + ); + } else if (kind === 'forge') { + if (!commit) throw new Error('forge needs the commit to tag'); + release = await upsert( + `${need('GITHUB_SERVER_URL')}/api/v1/repos/${need('GITHUB_REPOSITORY')}`, + { Authorization: `token ${need('FORGE_TOKEN')}` }, + { name, body, target_commitish: commit } + ); + } else { + throw new Error(`unknown forge ${kind}`); + } + console.log(release.html_url); +} + +main().catch((err) => { + console.error(`releases: ${err.message}`); + process.exit(1); +}); diff --git a/ci/testcount/main.go b/ci/testcount/main.go new file mode 100644 index 00000000..3404cfbc --- /dev/null +++ b/ci/testcount/main.go @@ -0,0 +1,152 @@ +// Command testcount reads `go test -json` on stdin and prints what plain +// `go test` would have printed: one line per package, and the whole output of +// every test that failed. It ends with how many tests ran, so each CI run +// records the size of the suite it verified. +// +// It never decides whether the run passed. The lane exits with go test's own +// status, which is why the pipe keeps it aside: +// +// { rc=0; go test -json ./... || rc=$?; echo "$rc" > /tmp/go-test-rc; } | testcount +// exit "$(cat /tmp/go-test-rc 2>/dev/null || echo 1)" +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "os" + "strings" +) + +type event struct { + Action string + Package string + Test string + Output string +} + +type tally struct{ passed, failed, skipped int } + +func (t *tally) add(action string) { + switch action { + case "pass": + t.passed++ + case "fail": + t.failed++ + case "skip": + t.skipped++ + } +} + +func (t tally) String() string { + return fmt.Sprintf("%d passed, %d failed, %d skipped", t.passed, t.failed, t.skipped) +} + +// pkgState holds one package's output until the package ends, keyed by test +// name ("" for the package itself), in the order each test first spoke. +type pkgState struct { + order []string + out map[string][]string +} + +func main() { + if err := run(os.Stdin, os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, "testcount:", err) + os.Exit(1) + } +} + +// printer keeps the first write error, so run can report a closed stdout +// once instead of checking every line. +type printer struct { + w io.Writer + err error +} + +func (p *printer) print(s string) { + if p.err == nil { + _, p.err = io.WriteString(p.w, s) + } +} + +// lines writes a test's output without the run/pause/continue markers that +// -json adds and plain go test leaves out. +func (p *printer) lines(lines []string) { + for _, line := range lines { + if !strings.HasPrefix(strings.TrimLeft(line, " "), "=== ") { + p.print(line) + } + } +} + +func run(r io.Reader, w io.Writer) error { + out := &printer{w: w} + var tests, subtests tally + pkgs := map[string]*pkgState{} + state := func(pkg string) *pkgState { + p := pkgs[pkg] + if p == nil { + p = &pkgState{out: map[string][]string{}} + pkgs[pkg] = p + } + return p + } + + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 64*1024), 64*1024*1024) + for sc.Scan() { + var e event + if err := json.Unmarshal(sc.Bytes(), &e); err != nil || e.Action == "" { + // Not an event (the go command's own complaints): pass it on. + out.print(sc.Text() + "\n") + continue + } + switch e.Action { + case "build-output": + out.print(e.Output) + case "output": + p := state(e.Package) + if _, seen := p.out[e.Test]; !seen { + p.order = append(p.order, e.Test) + } + p.out[e.Test] = append(p.out[e.Test], e.Output) + case "pass", "fail", "skip": + p := state(e.Package) + if e.Test != "" { + if strings.Contains(e.Test, "/") { + subtests.add(e.Action) + } else { + tests.add(e.Action) + } + if e.Action == "fail" { + out.lines(p.out[e.Test]) + } + delete(p.out, e.Test) + continue + } + if e.Action == "fail" { + // A test still holding output here never finished: the + // binary panicked or timed out while it ran. + for _, name := range p.order { + if name != "" { + out.lines(p.out[name]) + } + } + out.lines(p.out[""]) + } else { + for _, line := range p.out[""] { + if strings.HasPrefix(line, "ok ") || strings.HasPrefix(line, "?") { + out.print(line) + } + } + } + delete(pkgs, e.Package) + } + } + if err := sc.Err(); err != nil { + return err + } + out.print(fmt.Sprintf("\ntests: %s\nsubtests: %s\n", tests, subtests)) + return out.err +} diff --git a/client/README.md b/client/README.md index 165b4db6..af4bd4a4 100644 --- a/client/README.md +++ b/client/README.md @@ -4,22 +4,12 @@ Holds the Android APK (`minstrel.apk`) and its version sidecar (`minstrel.apk.version`) that the server serves via `/api/client/version` and `/api/client/apk` for the in-app update flow. -## Production +## Release images -CI fills this directory in `release.yml` before every image build: - -- **Dev push (`:dev`) and tag release (`v*`):** the `android-release` job - builds and signs the APK and uploads it as a workflow artifact; - `image-release` downloads it here as `minstrel.apk` and writes the - sidecar from that build's version outputs. A tag release also attaches - both files to the Gitea release. -- **Main push (`:latest` + `:`):** no APK is built, but the image - still moves `:latest`, so `image-release` downloads the most recent - release's APK and the sidecar recorded beside it. `:latest` keeps its - update channel between releases. - -Either way, `docker buildx build` bakes both files into the image via -`COPY client/ /app/client/`. +The release build signs the APK, writes its sidecar, and places both here +before the image is built. `docker buildx build` bakes them into the image +via `COPY client/ /app/client/`, so a server always offers the app built +alongside it. ## The sidecar diff --git a/cmd/minstrel/admin.go b/cmd/minstrel/admin.go index 26103e30..4fc59ca7 100644 --- a/cmd/minstrel/admin.go +++ b/cmd/minstrel/admin.go @@ -11,10 +11,10 @@ import ( "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/config" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/logging" + "github.com/Fabled-Sword/minstrel/internal/config" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/logging" ) // runMigrate applies the embedded migrations and exits. The server also diff --git a/cmd/minstrel/main.go b/cmd/minstrel/main.go index 7768650d..0897983d 100644 --- a/cmd/minstrel/main.go +++ b/cmd/minstrel/main.go @@ -15,32 +15,32 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/acoustid" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/config" - "git.fabledsword.com/bvandeusen/minstrel/internal/coplay" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" - "git.fabledsword.com/bvandeusen/minstrel/internal/gc" - "git.fabledsword.com/bvandeusen/minstrel/internal/importer" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" - "git.fabledsword.com/bvandeusen/minstrel/internal/lifecycle" - "git.fabledsword.com/bvandeusen/minstrel/internal/logging" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" - "git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition" - "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings" - "git.fabledsword.com/bvandeusen/minstrel/internal/requests" - "git.fabledsword.com/bvandeusen/minstrel/internal/scrobble" - "git.fabledsword.com/bvandeusen/minstrel/internal/scrobble/listenbrainz" - "git.fabledsword.com/bvandeusen/minstrel/internal/server" - "git.fabledsword.com/bvandeusen/minstrel/internal/similarity" - "git.fabledsword.com/bvandeusen/minstrel/internal/subsonic" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" - "git.fabledsword.com/bvandeusen/minstrel/internal/tags" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" + "github.com/Fabled-Sword/minstrel/internal/acoustid" + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/buildinfo" + "github.com/Fabled-Sword/minstrel/internal/catalogue" + "github.com/Fabled-Sword/minstrel/internal/config" + "github.com/Fabled-Sword/minstrel/internal/coplay" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/eventbus" + "github.com/Fabled-Sword/minstrel/internal/gc" + "github.com/Fabled-Sword/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/logging" + "github.com/Fabled-Sword/minstrel/internal/lookups" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/periodic" + "github.com/Fabled-Sword/minstrel/internal/playlists" + "github.com/Fabled-Sword/minstrel/internal/recsettings" + "github.com/Fabled-Sword/minstrel/internal/scrobble" + "github.com/Fabled-Sword/minstrel/internal/scrobble/listenbrainz" + "github.com/Fabled-Sword/minstrel/internal/secret" + "github.com/Fabled-Sword/minstrel/internal/server" + "github.com/Fabled-Sword/minstrel/internal/similarity" + "github.com/Fabled-Sword/minstrel/internal/subsonic" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/tags" ) func main() { @@ -58,14 +58,40 @@ func main() { os.Exit(1) } return + case "restore": + if err := runRestore(os.Args[2:]); err != nil { + fmt.Fprintf(os.Stderr, "minstrel restore: %v\n", err) + os.Exit(1) + } + return } } - if err := run(); err != nil { + err := run() + if errors.Is(err, errRestart) { + err = restartInPlace() + } + if err != nil { fmt.Fprintf(os.Stderr, "minstrel: %v\n", err) os.Exit(1) } } +// errRestart is run's answer when the server stopped in order to start again: +// after a web restore, so the restored settings are read at boot. +var errRestart = errors.New("restart requested") + +// restartInPlace replaces this process with a fresh start of the same binary, +// arguments and environment. The process id stays the same, so a container +// keeps running without needing a restart policy. +func restartInPlace() error { + exe, err := os.Executable() + if err != nil { + return fmt.Errorf("restart: %w", err) + } + // Exec returns only when it failed. + return fmt.Errorf("restart: %w", syscall.Exec(exe, os.Args, os.Environ())) +} + // safetyNetScanInterval backstops the fsnotify watcher with a low-frequency // full delta walk, catching anything the watcher missed (inotify watch-limit // exhaustion, dropped events). Fixed — there is no operator configuration. @@ -77,22 +103,15 @@ const safetyNetScanInterval = 12 * time.Hour func runSafetyNetScans(ctx context.Context, pool *pgxpool.Pool, scanner *library.Scanner, enricher *coverart.Enricher, logger *slog.Logger, scanCfg library.RunScanConfig, ) { - ticker := time.NewTicker(safetyNetScanInterval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - started, existing, err := library.TryStartScan(ctx, pool, scanner, enricher, logger, scanCfg) - if err != nil { - logger.Error("safety-net scan: try start failed", "err", err) - } else if !started && existing != nil { - logger.Info("safety-net scan skipped — prior still in flight", - "in_flight_id", existing.ID) - } + periodic.Run(ctx, logger, "safety-net scan", safetyNetScanInterval, func(ctx context.Context) { + started, existing, err := library.TryStartScan(ctx, pool, scanner, enricher, logger, scanCfg) + if err != nil { + logger.Error("safety-net scan: try start failed", "err", err) + } else if !started && existing != nil { + logger.Info("safety-net scan skipped — prior still in flight", + "in_flight_id", existing.ID) } - } + }, periodic.Delayed()) } func run() error { @@ -118,6 +137,9 @@ func run() error { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() + if err := db.WaitReady(ctx, cfg.Database.URL, logger); err != nil { + return fmt.Errorf("database: %w", err) + } if err := db.Migrate(cfg.Database.URL, logger); err != nil { return fmt.Errorf("migrate: %w", err) } @@ -128,6 +150,18 @@ func run() error { } defer pool.Close() + // Stored credentials are sealed under a key derived from the stream + // secret. Install it before anything reads one, and seal any value still + // stored in the clear. + secret.Install(cfg.StreamSecret) + sealed, err := secret.SealStored(ctx, pool) + if err != nil { + return fmt.Errorf("seal stored credentials: %w", err) + } + if sealed > 0 { + logger.Info("sealed stored credentials", "count", sealed) + } + // Fingerprinting settings: one instance, shared by the scanner, // the fingerprint backfill, the duplicate sweep and the admin API, so a save // reaches all of them without a restart. A load failure is logged, not fatal: @@ -156,27 +190,31 @@ func run() error { logger.Warn("loudness settings: using defaults", "err", loudErr) } + // Switches for ListenBrainz similarity and MusicBrainz track lists: + // shared by the similarity worker, the duplicate resolver and the admin + // API. A load failure leaves both on, as on a new install. + lookupSettings, lookupErr := lookups.New(ctx, pool) + if lookupErr != nil { + logger.Warn("lookup settings: using defaults", "err", lookupErr) + } + // AcoustID lookup settings: shared by the lookup worker and the // admin API. A load failure leaves the lookup off. acoustIDSettings, acoustIDErr := library.NewAcoustIDSettingsService(ctx, pool) if acoustIDErr != nil { logger.Warn("acoustid settings: using defaults (lookup off)", "err", acoustIDErr) } - // One AcoustID client, so the lookup worker and the import's check share - // its pace (AcoustID allows three requests a second per key). + // One AcoustID client, so every lookup shares its pace (AcoustID allows + // three requests a second per key). acoustIDClient := acoustid.New(acoustid.DefaultBaseURL) acoustIDLookup := library.NewAcoustIDLookupWorker(pool, logger.With("component", "acoustid_lookup"), acoustIDSettings, acoustIDClient) - contact := cfg.Library.ContactEmail - if contact == "" { - contact = "https://git.fabledsword.com/bvandeusen/minstrel" - } // Swap in the production User-Agent + MinPeriod on the registered // MBCAA provider. init() registered it with default config; this // updates the running instance. coverart.NewMBCAAProviderFromConfig(coverart.FetcherConfig{ - UserAgent: fmt.Sprintf("Minstrel/dev (%s)", contact), + UserAgent: buildinfo.UserAgent(cfg.Library.ContactEmail), MinPeriod: time.Second, }) @@ -191,8 +229,7 @@ func run() error { logger.Info("coverart: registered provider set changed; version bumped", "new_version", newVer) } - coverEnricher := coverart.NewEnricher(pool, logger.With("component", "coverart"), coverSettings) - coverEnricher.DataDir = cfg.Storage.DataDir + coverEnricher := coverart.NewEnricher(pool, logger.With("component", "coverart"), coverSettings, cfg.Storage.DataDir) // Recommendation tuning: seeds the shipped defaults on first boot and // pushes the daily-mix weights and taste config into package playlists. @@ -205,9 +242,11 @@ func run() error { // One unified scan chain: library walk → MBID backfill → cover enrich. // Boot-time scan and manual-trigger scans share this path; results land - // in scan_runs for the admin overview. + // in scan_runs for the admin overview. A run the last shutdown cut off is + // closed first, so it doesn't read as a scan still going. + library.RecoverScanRuns(ctx, pool, logger.With("component", "scan_run")) if cfg.Library.ScanOnStartup && len(roots) > 0 { - go func() { + go periodic.Safe(ctx, logger, "startup scan", func(ctx context.Context) { if _, err := library.RunScan(ctx, pool, scanner, coverEnricher, logger.With("component", "scan_run"), library.RunScanConfig{ @@ -219,11 +258,11 @@ func run() error { ); err != nil { logger.Warn("startup scan run failed", "err", err) } - }() + }) } else { // No startup file walk, but still run backfill + enrich so cover // art keeps arriving with scan-on-startup off. - go func() { + go periodic.Safe(ctx, logger, "boot scan", func(ctx context.Context) { if _, err := library.RunScan(ctx, pool, nil, coverEnricher, logger.With("component", "scan_run"), library.RunScanConfig{ @@ -235,7 +274,7 @@ func run() error { ); err != nil { logger.Warn("boot-only scan run failed", "err", err) } - }() + }) } // ListenBrainz scrobble worker: every 30s, drains up to 50 pending rows. @@ -246,7 +285,9 @@ func run() error { // Similarity ingest worker: hourly, fetches ListenBrainz similarity for up // to 5 played tracks and 5 played artists, each re-fetched at most weekly. // The endpoints are public, so no token is needed. + // An admin can switch it off under Metadata sources. similarityWorker := similarity.NewWorker(pool, listenbrainz.NewClient(), logger.With("component", "similarity")) + similarityWorker.Enabled = func() bool { return lookupSettings.Get().ListenBrainzSimilarity } go similarityWorker.Run(ctx) // Household co-play worker: recomputes artist–artist @@ -314,44 +355,12 @@ func run() error { // same pool and bus. notifier := notifications.New(pool, bus, logger.With("component", "notifications")) - // The request reconciler completes approved requests once the library - // holds what they asked for. - requestReconciler := requests.NewReconciler(pool, logger.With("component", "requests"), bus) - requestReconciler.SetNotifier(notifier) library.SetNotifier(notifier) - go requestReconciler.Run(ctx) - // Release catalogue: re-reads discographies older than a - // week from MusicBrainz, a batch an hour, through the process-wide - // MusicBrainz pacer it shares with tag enrichment. + // Release track lists from MusicBrainz, read on demand by the duplicate + // resolver through the process-wide MusicBrainz pacer it shares with tag + // enrichment. cat := catalogue.New(pool, nil, logger.With("component", "catalogue")) - go cat.Run(ctx) - - // The wanted list: reads followed artists' discographies - // daily for new releases and marks wants held once the library has them. - go wanted.New(pool, cat, logger.With("component", "wanted")).Run(ctx) - - // Search and grab: every ten minutes, searches the - // configured indexers for wants due, paced by each source's - // searches-per-hour, and hands the best release to the download client - // when auto-grab is on. - go wanted.NewSearcher(pool, cat, logger.With("component", "search")).Run(ctx) - - // Import with verification: every minute, finished - // downloads are checked against their album (AcoustID, lengths, tags) - // and filed into the library with MusicBrainz tags, or refused. - var printer importer.Printer - if acoustIDSettings != nil { - printer = &importer.AcoustIDPrinter{Settings: acoustIDSettings, Client: acoustIDClient} - } - imp := importer.New(pool, scanner, cat, printer, scanner.Roots, logger.With("component", "import")) - imp.DataDir = cfg.Storage.DataDir - go imp.Run(ctx) - - // Download lifecycle: every ten minutes, a download that - // failed or that nobody shares is retried, then given up and its album - // searched again; an imported one seeds, then is removed. - go lifecycle.New(pool, logger.With("component", "lifecycle")).Run(ctx) // Duplicate resolver: classifies the sweep's groups and, with auto-resolve // on, merges the copies that are safe to merge. @@ -359,23 +368,16 @@ func run() error { // catalogue for the track list of an album whose wrong slot it must // decide, a few a pass. See internal/library/duplicate_resolve.go. go library.NewDuplicateResolveWorker(pool, logger.With("component", "duplicate_resolve"), - cfg.Storage.DataDir, fpSettings, library.ResolveSources{ - TrackLists: cat.RefreshReleaseGroup, Identify: acoustIDLookup.IdentifyRecordings, + fpSettings, library.ResolveSources{ + TrackLists: func(ctx context.Context, releaseGroupMBID string) error { + if !lookupSettings.Get().MusicBrainzTrackLists { + return library.ErrLookupOff + } + return cat.RefreshReleaseGroup(ctx, releaseGroupMBID) + }, + Identify: acoustIDLookup.IdentifyRecordings, }).Run(ctx) - // Missing-file re-acquisition: wants back albums whose files have been - // gone longer than the grace window, for the search schedule to find. - // Hourly, because the grace window is measured in hours. - // - // A settings-load failure is logged, not fatal: NewSettingsService always - // returns a usable service holding the defaults. - reacqSettings, reacqErr := reacquisition.NewSettingsService( - ctx, pool, logger.With("component", "reacquisition")) - if reacqErr != nil { - logger.Warn("reacquisition: using default settings", "err", reacqErr) - } - go reacquisition.NewSweeper(pool, reacqSettings, logger.With("component", "reacquisition")).Run(ctx) - // library_changes compactor: daily, deletes // rows older than the configured retention so the change-log table // doesn't grow unbounded. Clients that drop offline longer than @@ -434,11 +436,11 @@ func run() error { // fsnotify, scanning just the affected paths + enriching their albums // inline. Replaces the removed configurable scan scheduler. watcher := library.NewWatcher(scanner, coverEnricher, logger.With("component", "watcher")) - go func() { + go periodic.Safe(ctx, logger, "library watcher", func(ctx context.Context) { if werr := watcher.Run(ctx); werr != nil { logger.Warn("library watcher exited", "err", werr) } - }() + }) // Safety-net delta walk backstops the watcher (inotify limits / dropped // events) at a fixed low frequency. No operator config. go runSafetyNetScans(ctx, pool, scanner, coverEnricher, @@ -454,10 +456,21 @@ func run() error { srv.FingerprintSettings = fpSettings srv.LoudnessSettings = loudSettings srv.AcoustIDLookup = acoustIDLookup - // The sweeper above holds this same instance, so a save from the admin - // card changes what it does on its next tick. - srv.ReacqSettings = reacqSettings + srv.LookupSettings = lookupSettings + // The server's own backup: the loop runs the nightly schedule, and the + // admin page starts, tests and configures the same instance. + backups := backup.NewService(pool, logger.With("component", "backup"), buildinfo.Version) + backups.Roots = scanner.Roots + go backups.Loop(ctx) + srv.Backups = backups srv.StreamSecret = cfg.StreamSecret + restart := make(chan struct{}, 1) + srv.Restart = func() { + select { + case restart <- struct{}{}: + default: + } + } httpServer := &http.Server{ Addr: cfg.Server.Address, Handler: srv.Router(), @@ -483,20 +496,32 @@ func run() error { close(errCh) }() + restarting := false select { case <-ctx.Done(): logger.Info("shutdown signal received") + case <-restart: + logger.Info("restarting to load the restored backup") + restarting = true case err := <-errCh: if err != nil { return fmt.Errorf("server: %w", err) } } + // Ends the background work (scans, workers, schedules) as a signal would. + stop() shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := httpServer.Shutdown(shutdownCtx); err != nil { return fmt.Errorf("shutdown: %w", err) } + // A backup still running is stopped and records that it was cut off. + backups.Close() + if restarting { + logger.Info("minstrel stopped; starting again") + return errRestart + } logger.Info("minstrel stopped") return nil } diff --git a/cmd/minstrel/restore.go b/cmd/minstrel/restore.go new file mode 100644 index 00000000..3ea8a171 --- /dev/null +++ b/cmd/minstrel/restore.go @@ -0,0 +1,76 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/config" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/logging" +) + +const restoreUsage = "usage: minstrel restore [-config PATH] FILE" + +// runRestore loads a backup file into a new Minstrel's database: one with no +// accounts and no library yet. It brings the schema up to date first, so a +// backup from an older Minstrel loads into this one. The server isn't running +// meanwhile, so the library scan waits for it to start. +func runRestore(args []string) error { + fs := flag.NewFlagSet("restore", flag.ContinueOnError) + configPath := fs.String("config", os.Getenv("MINSTREL_CONFIG"), "path to YAML config file") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() != 1 { + return errors.New(restoreUsage) + } + cfg, err := config.Load(*configPath) + if err != nil { + return fmt.Errorf("load config: %w", err) + } + if cfg.Database.URL == "" { + return errors.New("no database URL configured (set it in the config file or MINSTREL_DATABASE_URL)") + } + logger, err := logging.New(os.Stderr, cfg.Log.Level, cfg.Log.Format) + if err != nil { + return fmt.Errorf("init logger: %w", err) + } + + f, err := os.Open(fs.Arg(0)) + if err != nil { + return err + } + defer func() { _ = f.Close() }() + manifest, contents, err := backup.Read(f) + if err != nil { + return err + } + if err := db.Migrate(cfg.Database.URL, logger); err != nil { + return fmt.Errorf("migrate: %w", err) + } + ctx := context.Background() + pool, err := db.Open(ctx, cfg.Database.URL) + if err != nil { + return fmt.Errorf("open db: %w", err) + } + defer pool.Close() + if err := backup.Restore(ctx, pool, contents); err != nil { + return err + } + printRestored(os.Stdout, manifest) + return nil +} + +// printRestored says what came back and what happens next. +func printRestored(w io.Writer, m backup.Manifest) { + _, _ = fmt.Fprintf(w, "minstrel: restored the backup made %s by Minstrel %s (%d accounts, %d tracks, %d playlists).\n", + m.CreatedAt.Local().Format("2 Jan 2006 15:04 MST"), m.Build, + m.Rows["users"], m.Rows["tracks"], m.Rows["playlists"]) + _, _ = fmt.Fprintln(w, "Start the server. The library scan (at startup, or Scan now under Admin › Library) finds each music file at its path, and the artwork, tags and analysis the backup leaves out are fetched and worked out again.") + _, _ = fmt.Fprintln(w, "Everyone signs in with the password they had. Subsonic apps are signed out: each person makes a new Subsonic password in their own Settings, and saves their ListenBrainz token there again. Keys for other services, and the backup's own destination, are entered again in Admin.") +} diff --git a/config.example.yaml b/config.example.yaml index b5b7bf7c..cdf70ede 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -30,7 +30,7 @@ library: branding: app_name: "Minstrel" # MINSTREL_BRANDING_APP_NAME - description: "Self-hosted music server with Subsonic compatibility, smart shuffle, and music acquisition." # MINSTREL_BRANDING_DESCRIPTION + description: "Self-hosted music server with Subsonic compatibility and smart shuffle." # MINSTREL_BRANDING_DESCRIPTION subsonic: # Accept the plaintext `p=` password on /rest/*. Leave off unless a client diff --git a/docker-compose.yml b/docker-compose.yml index 83437538..2d1cf0b4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,17 +20,13 @@ services: # Creates minstrel_test on a fresh volume. On an existing volume, # make test-integration creates it instead. - ./deploy/initdb:/docker-entrypoint-initdb.d:ro - healthcheck: - test: ["CMD-SHELL", "pg_isready -U minstrel -d minstrel"] - interval: 5s - timeout: 5s - retries: 10 minstrel: build: . + # Minstrel waits for the database itself at startup, so it needs no + # healthcheck to gate on. depends_on: - postgres: - condition: service_healthy + - postgres environment: MINSTREL_DATABASE_URL: postgres://minstrel:minstrel@postgres:5432/minstrel?sslmode=disable MINSTREL_LOG_FORMAT: text diff --git a/docs/hosting.md b/docs/hosting.md index ab544713..50f197d3 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -83,6 +83,76 @@ Creating the first account (which becomes the admin) requires that token, so whoever reaches a newly exposed server first can't claim it. The token changes on every restart until an account exists. +## Backups + +Minstrel can back itself up once a night: accounts, likes, playlists, +listening history and settings, in one file. It is off until an +admin switches it on under **Admin › Backups**. Anything Minstrel can fetch +or work out again (artwork, fingerprints, MusicBrainz data) is left out, and +so are the keys and passwords Minstrel keeps for other services, which are +entered again on a restored server. Sign-in passwords are kept. + +A backup goes to one of: +- **an S3 bucket**, path-style (MinIO, Garage, or any S3-compatible store). + The key only needs to add and list objects. Files land under `database/`. +- **a folder** on the server, under `database/` inside it. Mount a volume + there; Minstrel refuses to write into a folder that isn't there. + +Minstrel only adds files, named by date, and never deletes one. Keep as many +as you like with the destination's own retention. **Test destination** lists +what is there without writing anything. + +**Include the music** also sends the library's files to `music/` in the same +destination, laid out as they are under the library folders. After each +night's database file has landed, Minstrel sends the files it hasn't sent +yet, one at a time, for up to six hours; a large library takes several +nights the first time, and the panel shows how much is in. After that, a +night sends only new files and files that changed. A changed file goes to +its old name, and Minstrel still never deletes anything there, so a file +taken out of the library stays in the backup. On a bucket that keeps +versions or locks objects, set its retention to keep what you want. A file +the bucket refuses (an overwrite a locked object won't take) is listed on +the panel and goes again once it changes or the settings are saved; three +refusals in a row stop that night's music, since that is usually a key that +may not write under `music/`. A bucket's upload limit applies +to the music as well. + +### Restoring + +A backup restores into a new Minstrel: one nobody has signed up to yet. If +it has already scanned the music, that's fine; the backup's library takes +the place of what the scan found. + +1. **Put the music back first**, at the path the library had. The restored + settings name the old library folders, and each track is found again by + its path. If the backup includes the music, copy what is inside `music/` + into the library folder (with several library folders, into the folder + that holds them all). +2. **Load the backup**, either way: + - In the web app, choose **Create account**, then **Restore a backup**. + Pick a `minstrel-….tar` file from the backup's `database/` folder and + enter the setup token from the log (see *First account*). Minstrel + restarts by itself once the backup is in, so it runs on the restored + settings. + - Or, with the server stopped, run + `docker compose run --rm minstrel restore /backups/database/minstrel-20261102T030000Z.tar`, + with the file on a volume the container can read. It brings the database + schema up to date first, so a backup from an older Minstrel loads into a + newer one; a backup from a newer Minstrel is refused. +3. **Sign in** with the password you had. Everyone else's accounts, likes, + playlists and history are back too. + +The library scan then finds each file, and the artwork, tags, fingerprints +and loudness are fetched or worked out again over the following hours. Keys +for other services (AcoustID, artwork and tag providers, email) and the +backup's own destination are entered again under **Admin**. An app that +synced with the old server starts its sync over. + +Subsonic apps are signed out. Each person makes a new Subsonic password in +their own **Settings › Connections** and enters it in their apps, and saves +their ListenBrainz token there again (ListenBrainz comes back switched off +until they do). An app that signs in with an API key keeps working. + ## Android app The app connects over whatever URL you give it, HTTP or HTTPS. Once the diff --git a/docs/screenshots/README.md b/docs/screenshots/README.md index c7306c6f..dd603652 100644 --- a/docs/screenshots/README.md +++ b/docs/screenshots/README.md @@ -1,19 +1,21 @@ # README screenshots -Drop the files below into this directory with these **exact names** — the -root `README.md` already references them, so no Markdown editing is needed. -Export as PNG. Capture while logged in as admin and *after* the first -library scan so nothing looks empty; keep the same browser width and theme -across all shots for a consistent look. +Every artist, album, cover and song in these screenshots is invented. They +come from the demo library in [`tools/demo-library`](../../tools/demo-library), +which also holds the steps and the script that retake them, so the set can be +rebuilt whenever the UI changes. Retake them all at once, so they show the same +library, account and listening history. -| Filename | Route | What to capture | +| File | Page | Shows | |---|---|---| -| `home.png` | `/` | The home page with a populated library (system playlists / recently added) | -| `register.png` | `/register` | The account-creation form on a fresh instance | -| `library-scan.png` | `/admin` | The library scan running in stages (grab it mid-scan so stage tallies show) | -| `integrations.png` | `/admin/acquisition` | Indexers, download clients and searching | -| `android-download.png` | `/settings` | The "Install the Android app" download card | -| `invite-users.png` | `/admin/users` | The invite-token generation / users list | +| `home.png` | `/` | Home with two months of listening: the daily mixes, Songs like, and genre mixes | +| `home-phone.png` | `/` | Home at phone width | +| `now-playing.png` | `/now-playing` | A track playing, with its queue | +| `album.png` | an album | A track list where one song has a featured guest | +| `library.png` | `/library/albums` | The album grid | +| `register.png` | `/register` | Creating the first account on a new server | +| `android-download.png` | `/settings` | The Android app download card | -Tip: to control display width in the README, you can swap the Markdown -`![alt](path)` for an HTML tag, e.g. `...`. +The root `README.md` shows `home.png`, `now-playing.png` and `home-phone.png`. +To set the display width there, use an HTML tag instead of Markdown, e.g. +`...`. diff --git a/docs/screenshots/album.png b/docs/screenshots/album.png new file mode 100644 index 00000000..19fc3eca Binary files /dev/null and b/docs/screenshots/album.png differ diff --git a/docs/screenshots/android-download.png b/docs/screenshots/android-download.png index 3775bb54..ba5bc9b5 100644 Binary files a/docs/screenshots/android-download.png and b/docs/screenshots/android-download.png differ diff --git a/docs/screenshots/home-phone.png b/docs/screenshots/home-phone.png new file mode 100644 index 00000000..4272badd Binary files /dev/null and b/docs/screenshots/home-phone.png differ diff --git a/docs/screenshots/home.png b/docs/screenshots/home.png index e7d2841b..753ae548 100644 Binary files a/docs/screenshots/home.png and b/docs/screenshots/home.png differ diff --git a/docs/screenshots/integrations.png b/docs/screenshots/integrations.png deleted file mode 100644 index 2173f375..00000000 Binary files a/docs/screenshots/integrations.png and /dev/null differ diff --git a/docs/screenshots/invite-users.png b/docs/screenshots/invite-users.png deleted file mode 100644 index a48b756b..00000000 Binary files a/docs/screenshots/invite-users.png and /dev/null differ diff --git a/docs/screenshots/library-scan.png b/docs/screenshots/library-scan.png deleted file mode 100644 index 148d454a..00000000 Binary files a/docs/screenshots/library-scan.png and /dev/null differ diff --git a/docs/screenshots/library.png b/docs/screenshots/library.png new file mode 100644 index 00000000..31ff0266 Binary files /dev/null and b/docs/screenshots/library.png differ diff --git a/docs/screenshots/now-playing.png b/docs/screenshots/now-playing.png new file mode 100644 index 00000000..d7c3f6ad Binary files /dev/null and b/docs/screenshots/now-playing.png differ diff --git a/docs/screenshots/register.png b/docs/screenshots/register.png index 6346428d..b604f1f3 100644 Binary files a/docs/screenshots/register.png and b/docs/screenshots/register.png differ diff --git a/docs/security.md b/docs/security.md index 7ed8472a..e91fca85 100644 --- a/docs/security.md +++ b/docs/security.md @@ -14,13 +14,17 @@ decisions that look odd at first. For deployment steps, see password, so timing doesn't reveal which accounts exist. - **Sessions** are random 256-bit tokens; the server stores only their SHA-256. A session ends after 30 days unused or 365 days in total. Changing - your password signs out your other devices; a password reset, or an admin - resetting it, signs out all of them. + your password signs out your other devices, and your Subsonic apps too if + you tick "Sign out Subsonic apps too". A password reset, or an admin + resetting it, signs out all of them and every Subsonic app: the API key and + Subsonic password stop working, and you make new ones in Settings. - **API keys** (the OpenSubsonic `apiKey`) are stored as SHA-256 too, so a key is shown once, when you generate it in Settings, and can only be replaced after that. - **The first account** on an empty server needs the setup token from the server log (see [hosting](./hosting.md#first-account)). +- **Every other account needs an invite** that an admin makes in + **Admin › Users**. There is no open sign-up. - **Password-reset links** are built only from the configured public address, never from the request's `Host` header. @@ -49,22 +53,42 @@ cross-origin preflight. Requests authenticated with a bearer token or the Subsonic query parameters carry nothing a browser attaches on its own, so they aren't checked. -## Subsonic sign-in, and the one password stored in plain text +## Credentials Minstrel has to read back + +Some credentials can't be hashed, because Minstrel has to send or compare the +value itself: +- the AcoustID key, and the cover-art and tag provider keys; +- the SMTP password; +- the secret key of the S3 bucket backups go to; +- each user's ListenBrainz token and Subsonic password. + +These are encrypted in the database (AES-256-GCM). Each column has its own key, +derived from the stream secret (`MINSTREL_STREAM_SECRET`, or the +`stream_secret` file in the data directory), and each value is bound to its +row. The stream secret is never stored in the database, so a copy of the +database alone doesn't reveal any of them. None of them is ever sent back to a +browser: Settings only shows whether one is set. + +**Keep the stream secret with the data directory, and don't change it +casually.** If it changes, every stored credential reads as not set, and each +one has to be entered again in Settings (Subsonic passwords generated again). +Minstrel logs a warning for each one that no longer opens. + +## Subsonic sign-in Classic Subsonic clients sign in with `t` and `s`: the MD5 of the password followed by a random salt. To check that, the server has to know the password itself, so supporting this sign-in method means storing a password Minstrel -can read. That is the Subsonic password, and it is the only credential -Minstrel keeps unhashed. +can read: the Subsonic password, encrypted as described above. - **The recommended way in is the API key.** Clients that support the OpenSubsonic `apiKey` should use it. The key is stored hashed and can be replaced at any time in Settings. - **The Subsonic password is never your login password.** Minstrel generates it (**Settings → Subsonic password**), shows it once, and lets you replace - or turn it off. Because it is random, a copy of the database exposes access - to this server's Subsonic API and nothing else: it can't be a password you - also use somewhere else. + or turn it off. Because it is random, even someone holding both the database + and the stream secret gains access to this server's Subsonic API and nothing + else: it can't be a password you also use somewhere else. - **`t`/`s` and `p=` sign-in are off for an account until it has a Subsonic password.** Plain `p=` sign-in is additionally off server-wide unless `subsonic.allow_plaintext_password` is enabled. @@ -90,16 +114,45 @@ across the internet exposes the session cookie in transit, which is why the On the phone, the session cookie is encrypted with a key held in the Android Keystore, so a copy of the app's files doesn't yield a usable session. +## What Minstrel contacts + +Minstrel runs with no internet access at all: every page, font and script is +served by the server itself, and each service below fails quietly when it +can't be reached. With internet access, a new server contacts these on its +own: + +| Service | What is sent | When | To turn it off | +| --- | --- | --- | --- | +| MusicBrainz (`musicbrainz.org`) | A song's or artist's MusicBrainz id | To fetch genre tags | **Admin › Metadata sources › Tags** | +| MusicBrainz (`musicbrainz.org`) | An album's MusicBrainz release-group id | When the duplicate resolver needs the album's track list | **Admin › Metadata sources › Other lookups** | +| Cover Art Archive (`coverartarchive.org`) | An album's MusicBrainz id | To fetch a missing album cover | **Admin › Metadata sources › Cover art** | +| Deezer (`api.deezer.com`) | An artist's name, or an artist and album title | To fetch a missing cover or artist picture | **Admin › Metadata sources › Cover art** | +| TheAudioDB (`theaudiodb.com`) | An album's or artist's MusicBrainz id | To fetch a missing cover or artist picture | **Admin › Metadata sources › Cover art** | +| ListenBrainz Labs (`labs.api.listenbrainz.org`) | MusicBrainz ids of songs and artists people have played | Hourly, for radio's similar-song data | **Admin › Metadata sources › Other lookups** | + +These are sent only once you set them up: +- **AcoustID** (`api.acoustid.org`) gets a song's audio fingerprint and length + when an admin adds an AcoustID key. +- **Last.fm** (`ws.audioscrobbler.com`) gets artist, album and song names when + an admin adds a Last.fm key and turns it on under **Metadata sources**. +- **ListenBrainz** (`api.listenbrainz.org`) gets each listen of a person who + adds their own ListenBrainz token in **Settings**. +- **Email** goes to the SMTP server an admin configures, and **backups** to + the S3 bucket an admin configures. + +Nothing sends audio files, usernames, email addresses or play counts to a +metadata service. Requests to each service are paced and back off when it +strains. + ## Build pipeline Nothing is published unless every check passes: the Go, integration, web and Android test suites, `govulncheck` against the toolchain that builds the -image, and `npm audit` on every web dependency, build tooling included. See -`.gitea/workflows/release.yml`. +image, and `npm audit` on every web dependency, build tooling included. ## Reporting a problem Open an issue on the -[repository](https://git.fabledsword.com/bvandeusen/minstrel/issues), or +[repository](https://github.com/Fabled-Sword/minstrel/issues), or contact the maintainer privately first if it's something that shouldn't be public until fixed. diff --git a/docs/smart-music-client-spec.md b/docs/smart-music-client-spec.md deleted file mode 100644 index 0ffa0f70..00000000 --- a/docs/smart-music-client-spec.md +++ /dev/null @@ -1,245 +0,0 @@ -# Project Spec: Smart Music Client (companion app) - -> **History.** This is the original design spec, kept as written. Where it describes an outside library manager doing search, adds and deletes, Minstrel now does that itself. - -## 1. Overview - -A mobile music player client built as the intentional companion to the Smart Music Server (see `smart-music-server-spec.md`). This is not a general-purpose Subsonic client — it is the client that knows how to consume the server's extended API and surface its novel features (contextual likes, session-aware radio, Lidarr integration, server-canonical state) as first-class UX. - -The thesis driving this project, restated: **state and intelligence belong on the server.** The client's job is to be a great playback surface and input device for the server's decisions, not to reimplement them. Compared to existing Subsonic clients (Symfonium, Tempo, Substreamer), this client is thinner in its "brains" and heavier in its integration with a specific server. - -**Scope of this spec:** v1 mobile client. Read the server spec first; this document assumes its terminology and data model. - -## 2. Goals and non-goals - -### Goals - -- Native-feeling mobile app on both iOS and Android from a single codebase. -- Full playback: background audio, lock screen controls, notification controls, Bluetooth/headset button handling, CarPlay/Android Auto *awareness* (not necessarily full integration in v1 — see non-goals). -- Offline cache with explicit user control. -- First-class UX for the dual-like model: clear, fast distinction between "like generally" and "like in this context." -- Real-time session awareness: the client knows what session it's in, shows the user what the server thinks the current context is, and surfaces contextually relevant actions. -- Radio flow that feels like a single gesture (seed → queue → playing) with clear affordances for "keep this vibe," "shift vibe," and "stop." -- Lidarr search and add directly from the player when listening to suggested additions. -- Multi-device consistency: state (likes, play counts, current queue if desired) reflects the canonical server state. Two devices signed in to the same user should see the same world. - -### Non-goals (v1) - -- CarPlay / Android Auto full integration. v1 should not *break* when these launch (lock screen controls must work, basic media session must be present) but dedicated CarPlay UI is deferred. -- Desktop client. The server's web UI covers desktop for v1. -- Cross-server support. This client talks to the Smart Music Server specifically and uses its extended API. Pointing it at a stock Navidrome is not a goal. -- Chromecast / AirPlay. Nice-to-have, not v1. -- Lyrics display. -- Equalizer / DSP. -- Playlist editing UI beyond basic add/remove (full playlist management lives in the server web UI). -- Social features (sharing, following, comments). - -## 3. Technology choices - -- **Framework:** Flutter. Rationale in the server spec conversation; the audio ecosystem (`just_audio`, `audio_service`) is the most mature cross-platform option for this use case. -- **Language:** Dart. -- **State management:** Riverpod. Rationale: testable, compile-time safe, well-suited to the amount of server state this app reflects. Avoid Bloc's boilerplate; avoid Provider's looseness. -- **HTTP:** `dio` with a typed client layer generated from the server's OpenAPI spec if the server publishes one; otherwise hand-written. -- **Local storage:** - - `sqflite` or `drift` for structured local data (cached library, offline play event queue). - - `path_provider` + direct filesystem for cached audio files. - - `flutter_secure_storage` for credentials. -- **Audio:** `just_audio` for playback, `just_audio_background` / `audio_service` for lock screen and background. -- **Navigation:** `go_router`. -- **Packaging:** standard Flutter build pipeline, published as APK/AAB for Android and TestFlight build for iOS. App store publication is out of scope for v1 (sideload / personal use). - -## 4. Architecture - -### Layers - -1. **Transport layer** — wraps the server's Subsonic and extended APIs. Handles auth, retries, connectivity changes. Exposes typed methods to higher layers. -2. **Repository layer** — merges local cache and remote data. Owns the decision of "when do I serve cached data vs. fetch fresh." Exposes streams that UI subscribes to. -3. **Playback engine** — wraps `just_audio`. Owns the queue, position, playback state. Emits events consumed by the session reporter. -4. **Session reporter** — background worker that translates playback engine events into server event API calls (play start, skip, seek, complete). Batches and retries when offline. -5. **Offline cache manager** — owns the disk cache of audio files and cover art. Implements eviction policy, explicit user-pinned downloads. -6. **UI layer** — Flutter widgets consuming Riverpod providers that wrap repositories. - -### Key architectural decisions - -- **Server is source of truth, local is cache.** The client does not hold authoritative state for likes, play counts, or queue membership. All user actions are fire-and-persist-locally, then sync to server. Conflict resolution favors server on write failures (with local retry). -- **Offline mode is first-class.** Every user action — liking, skipping, playing — must work offline and sync later. This means local event queue with retry, and UI that doesn't lie about server state it couldn't confirm. -- **No client-side recommendation logic.** Shuffle, radio, "play similar" all round-trip to the server. If offline, fall back to a simple random-from-cache with a UI indicator that smart features are degraded. -- **Optimistic UI.** Liking a song updates the UI immediately; sync happens in the background. Failed syncs surface as a non-blocking indicator, not a modal. - -### Threading model - -Flutter's main isolate handles UI. Playback and audio service run on their platform-native background threads (handled by `audio_service`). The session reporter and cache manager run as long-lived providers on the main isolate but do their work in async. Heavy operations (e.g. bulk cache cleanup) use `compute()` to offload to a worker isolate. - -## 5. Data flow examples - -### Starting a play session - -1. User taps a track. -2. UI calls playback engine: load queue, start playback. -3. Playback engine emits "track started" event. -4. Session reporter calls `POST /api/v1/events/play` with start metadata. -5. Server creates or updates session, computes session vector, returns session info. -6. Client updates a "current session" provider; UI can display session context (e.g. "tagged: rock, energetic"). -7. As playback progresses, session reporter periodically sends progress; on completion or skip, sends terminal event. - -### Liking a song - -Two buttons in the player UI: **Like** (general) and **Like this vibe** (contextual). Contextual like is only enabled when there is an active session of sufficient length (per server spec, ≥3 tracks in session). - -1. User taps Like this vibe. -2. UI optimistically marks the track as contextually liked in this session; shows a brief toast confirming. -3. Client calls `POST /api/v1/likes/contextual`. The server computes the session vector from its own records (the client does not send it — the server is authoritative). -4. On success, the like is confirmed. On failure, the action is queued for retry; UI shows a subtle indicator. - -### Starting radio - -1. User long-presses a track or taps a "Radio from here" affordance. -2. UI calls `GET /api/v1/radio?seed_track=`. -3. Server returns a queue and optional "suggested additions" (tracks not in library). -4. Playback engine replaces queue; UI renders the queue with suggested additions grouped separately at the bottom with Lidarr-add buttons. -5. As the queue drains, client requests a refresh at 80% consumption. - -### Offline playback - -1. User goes offline. -2. Client continues playback from cached files. -3. Play/skip events accumulate in the local event queue with their timestamps. -4. On reconnect, event queue is flushed to server in order. Server is expected to backfill events with their original timestamps, reconstruct sessions correctly even retroactively. -5. If a user liked a track offline, the like is queued the same way. - -## 6. UI structure - -### Screens - -- **Sign-in** — server URL, username, password. Remember server. Option to save multiple servers (for dev/prod, single household use). -- **Home** — suggested radios, recently played, recent likes, continue listening. All served by server endpoints. -- **Library** — artists, albums, tracks, playlists browse. Subsonic-standard. -- **Search** — searches server. Also offers "search Lidarr for this" affordance on empty results. -- **Now playing** — full-screen player. Primary affordances: play/pause/skip/seek, like general, like contextual, radio-from-here, add-to-playlist, queue view, session inspector. -- **Queue** — current queue with drag-to-reorder. Shows suggested additions below the real queue. -- **Session inspector** — shows the server's current session vector in human-readable form (recent tracks, detected tags, detected artists). Useful for debugging and for user trust in the "why is this playing" question. Accessible from the now-playing screen. -- **Downloads** — pinned/cached content, cache size, eviction controls. -- **Settings** — account, offline behavior, audio quality, cache size, server info, log out. - -### Now-playing affordances (design constraint) - -The now-playing screen is where the novel UX lives. It must make the following feel natural: - -- A single-tap way to like this song generally. -- A single-tap way to like this song in this context. Visually distinct from general like. -- Clear indication of whether either or both likes are active for the current track. -- An obvious but not-dominant "radio from here" action. -- When playback is inside a radio queue, a "keep this vibe" action that pins the current context, and a "shift" action that mutates it. (Exact semantics tunable; start with "keep" = re-seed radio from current track with current session vector, "shift" = re-seed ignoring session vector.) - -The exact visual design is deferred; the spec requires these *capabilities* be reachable without drilling into menus. Buried features won't get used and the contextual like is the whole point. - -### Design constraint: don't lie about server state - -If an action hasn't succeeded on the server yet, the UI may show the optimistic result but must not present it as fully confirmed. A subtle pending indicator on the like button, for instance. Errors that affect user perception of their library (e.g. a like that never synced) must be surfaceable, not silently dropped. - -## 7. Offline cache - -### Two kinds of cached content - -1. **Transient cache** — populated automatically during playback. LRU-evicted. Size-capped per user config (default 2 GB). -2. **Pinned downloads** — user-explicit "download this album / playlist." Not evicted automatically. Pinned content can be browsed in the Downloads screen. - -### Cache decisions - -- Cached files are stored at the audio quality the server was asked to deliver. Quality is chosen per user config (e.g. "always original," "transcode to 192k on cellular"). -- Cover art cached separately, smaller budget. -- Cache survives app reinstall if possible (Android: scoped external storage; iOS: app container — accepting that iOS reinstall loses it). -- User-visible cache size accounting must be accurate. - -### Offline UI - -An offline indicator appears in the top chrome when the client can't reach the server. All server-dependent actions show degraded affordances (e.g. smart shuffle shows "shuffling cached tracks only"). Pinned downloads remain fully usable. - -## 8. API usage - -### Endpoints consumed - -From the server's Subsonic surface: `ping`, `getMusicFolders`, `getIndexes`/`getArtists`, `getArtist`, `getAlbum`, `getAlbumList2`, `search3`, `stream`, `getCoverArt`, `getPlaylists`, `getPlaylist`, `createPlaylist`, `updatePlaylist`, `getRandomSongs`, `star`/`unstar` (for general likes — though the extended API's equivalent is preferred for future-proofing). - -From the server's extended API: all of `/api/v1/*` described in the server spec. Specifically depended on: -- `POST /api/v1/events/play` (with all event types the server supports) -- `POST /api/v1/likes/contextual` -- `DELETE /api/v1/likes/contextual/:id` -- `GET /api/v1/session/current` -- `GET /api/v1/radio` -- `POST /api/v1/lidarr/search` -- `POST /api/v1/lidarr/add` -- `POST /api/v1/quarantine/:track_id` -- `GET /api/v1/stats/user` - -### Auth - -Standard Subsonic auth for Subsonic endpoints (token + salt scheme). Bearer token for extended API. Client holds both; transport layer adds them transparently. - -### Versioning - -Client sends its version in a header on every extended API request. Server may respond with compatibility warnings. Major server API changes bump a version the client checks on startup. - -## 9. Reliability - -### Event queue durability - -Play/skip/like events are written to local SQL before any network attempt. The sync worker drains the queue FIFO with exponential backoff on failures. Events older than 30 days in the queue without successful sync are logged and dropped (with user visibility — a "some events failed to sync" notification). - -### Playback robustness - -- Network interruption during streaming: if the track is partially buffered, finish it from buffer; on exhaustion, pause and show offline state. -- Track not found (deleted between queue build and playback): skip forward, log, don't crash. -- Corrupt cache file: purge it, redownload or skip. - -### Battery and data - -- Don't prefetch aggressively on cellular unless user opts in. -- Audio session must release properly when playback ends; no background drain. - -## 10. Testing - -- Widget tests for the novel UI components (like buttons, session inspector, radio queue). -- Unit tests for the event queue and sync logic — this is where silent bugs lose user trust. -- Integration tests against a local server instance for the full happy-path flows. -- Manual test matrix documented: playback across lock/unlock, app backgrounded, headphone disconnect, network loss mid-stream, receive call mid-stream. - -## 11. Implementation order - -The client should not start before server step 4 (usable Subsonic baseline). Once that milestone is reached, client work proceeds in parallel: - -1. Project skeleton, Riverpod setup, routing, theme. -2. Auth + sign-in screen. Talk to `ping`. Store credentials securely. -3. Library browse: artists, albums, tracks. Read-only against Subsonic API. -4. Playback engine: `just_audio` integration, queue, background audio, lock screen. **Milestone: can play music from the server.** -5. Event ingestion against server (requires server step 5 complete): play start, complete, skip events wired to server. -6. Like buttons (general) wired to Subsonic `star`. -7. Contextual like button + session inspector (requires server step 8). -8. Radio flow (requires server step 11). -9. Lidarr search/add integration (requires server step 12). -10. Offline cache manager. -11. Pinned downloads. -12. Quarantine action from player. -13. Settings polish, stats screen. -14. Packaging, release pipeline. - -Steps 5, 7, 8, 9 gate on server features. Plan accordingly; don't block client work on those, sequence around them. - -## 12. Open questions to resolve during implementation - -- Whether queue state should itself be server-synced (so starting playback on one device resumes on another). Technically appealing but a significant complication — may defer to v2. -- Whether to offer a "this song is playing because of these contextual likes" explanation affordance. Requires server API to expose the reasoning, and it isn't currently in the server spec. Worth considering adding. -- Exact wording and iconography for general vs. contextual like. This needs user testing (even if the user is just you). -- Whether offline-created contextual likes are a good idea at all — the server is the authority on session vectors, and the client's view of a session may drift offline. Possibly contextual likes require connectivity while general likes do not. -- How aggressive to be about prefetching the radio queue in advance for offline continuation. - -## 13. Out of scope reminders - -If during development any of the following come up, stop and reconsider scope: -- CarPlay / Android Auto native UI -- Chromecast / AirPlay -- Lyrics -- EQ / DSP -- Cross-server support -- Desktop port -- Social / sharing diff --git a/docs/smart-music-server-spec.md b/docs/smart-music-server-spec.md deleted file mode 100644 index ad380759..00000000 --- a/docs/smart-music-server-spec.md +++ /dev/null @@ -1,342 +0,0 @@ -# Project Spec: Smart Music Server (working name) - -> **History.** This is the original design spec, kept as written. Where it describes an outside library manager doing search, adds and deletes, Minstrel now does that itself. - -## 1. Overview - -A self-hosted music server and streaming backend built to close a real gap in the self-hosted music ecosystem: **state and intelligence belong on the server, not the client.** Existing Subsonic-compatible servers (Navidrome, Gonic, Airsonic-Advanced) defer all of the "smart" behavior — shuffle logic, radio, play count semantics, like management — to clients. The result is fragmented experience across devices: a song liked on one client is unknown to another; shuffle quality depends on which app you opened; play counts diverge. This project centralizes those decisions on the server so every client sees the same canonical state. - -Primary differentiator: a **dual-like model** (general likes vs. contextual likes tied to the recent listening session) combined with **session-aware weighted shuffle** and **"smart radio" playlist generation** that considers user history, session context, and external similarity data from ListenBrainz/MusicBrainz. - -The system also integrates with Lidarr for library management and scrobbles to ListenBrainz. - -**Scope of this spec:** the backend server. A companion Flutter mobile client is part of the v1 product and is specified in a separate document (`smart-music-client-spec.md`). The two are co-designed: the extended API in this spec is shaped by what the client needs, and the client spec assumes the server features described here. Implementation proceeds in parallel after the server reaches Subsonic-compatible baseline. - -## 2. Goals and non-goals - -### Goals - -- Self-hosted music server running on Linux (primary target: Docker container on Ubuntu/CachyOS). -- OpenSubsonic API compatibility so existing clients (Symfonium, Tempo, Feishin, etc.) work out of the box. -- Server-side smart shuffle that beats random playback in a measurable way for the user. -- Server-side "radio" feature: seed from a track, artist, or album and generate a contextually coherent queue. -- Dual-like model (contextual and general) with retrievable contextual signal. -- Session tracking with play/skip/seek/complete events persisted as first-class data. -- ListenBrainz scrobbling (outbound) and similarity data pull (inbound). -- Lidarr integration: search and add from the server UI; quarantine-based removal workflow (never auto-delete). -- Web UI sufficient to manage the library, likes, Lidarr integration, and system settings. - -### Non-goals (v1) - -- Multi-tenant / public-facing deployment. Single-household use assumed; multi-user within household is a goal but not hardened against adversarial users. -- Audio fingerprinting / deduplication beyond what MusicBrainz IDs provide. -- Local ML embedding generation. Use ListenBrainz/MusicBrainz similarity data instead. -- Transcoding profiles beyond what OpenSubsonic expects. -- Podcast support. -- Video support. -- Internet radio streaming. - -### Explicit non-goals to push back on later - -If during implementation there is pressure to add: local audio feature extraction (Essentia/librosa), neural embeddings, or auto-delete-on-dislike — stop and re-scope. These are v2+ discussions. - -## 3. Technology choices - -- **Language:** Go. Rationale: single-binary deployment, strong concurrency model for streaming + background workers, mature ecosystem for HTTP services, good fit for home lab containerized deployment. -- **HTTP:** Go standard library `net/http` + `chi` or `echo` router. No heavyweight framework. -- **Database:** PostgreSQL. Rationale: the session-vector similarity queries and event aggregations will benefit from real indexing, window functions, and JSONB. SQLite is tempting for single-user deployments but will bottleneck on the analytics queries central to this project's value. -- **Database access:** `sqlc` for typed queries generated from SQL. Migrations via `goose` or `golang-migrate`. -- **Audio/transcoding:** `ffmpeg` as an external binary invoked per stream. Do not bundle or reimplement. -- **Tag reading:** `go-taglib` bindings or `dhowden/tag` for pure-Go tag parsing. -- **MusicBrainz / ListenBrainz:** direct HTTP clients, no wrapper libraries unless a well-maintained one exists at implementation time. -- **Lidarr:** direct HTTP client against Lidarr's v1 API. -- **Web UI:** server-rendered HTML + HTMX for v1. Rationale: avoids a full SPA build pipeline for what is a minority surface. Reconsider for v2 if the UI grows. -- **Auth:** token-based for API clients (OpenSubsonic uses its own auth scheme — support it). Session cookies for the web UI. -- **Deployment:** Dockerfile producing a scratch or distroless image containing the server binary + ffmpeg. Docker Compose example in the repo. -- **Config:** YAML config file with env var override. Sensible defaults. -- **Logging:** structured logging via `log/slog`. Log levels configurable. - -## 4. Architecture - -### High-level components - -1. **Library scanner** — walks configured music folders, parses tags, writes canonical track/artist/album records, resolves MusicBrainz IDs where available. -2. **Stream server** — OpenSubsonic endpoints for browsing, streaming, transcoding on demand. -3. **Event ingestion** — records play/skip/seek/complete events from clients, groups them into sessions. -4. **Session service** — maintains the notion of a "current session" per user, computes session vectors (the previous-N tracks and their aggregate features), handles session timeouts. -5. **Recommendation engine** — the core value layer. Implements weighted shuffle, radio generation, and contextual-like retrieval. Pure functions operating on data from the DB and similarity service. -6. **Similarity service** — wraps ListenBrainz similarity API calls with aggressive caching. Local DB stores similarity edges. -7. **Scrobble worker** — batches completed plays and forwards to ListenBrainz. -8. **Lidarr integration** — adapter for search, add, quarantine operations. -9. **Web UI** — thin surface over the above. -10. **Extended API** — non-Subsonic endpoints for features Subsonic clients cannot express (contextual likes, session inspection, Lidarr actions). - -### Key architectural decisions - -- **OpenSubsonic compatibility first, extensions second.** All existing Subsonic features must work with third-party clients. The novel features live in a parallel API namespace (e.g. `/api/v1/`) that the future custom client will use. -- **Events are append-only.** The events table is the source of truth for listening history. All aggregates (play counts, skip ratios, session vectors) are computed from it. This enables retroactive model changes without data loss. -- **Session computation is online but session similarity is precomputed.** When a track is played, its "session vector at time of play" is computed and stored on the play event. This makes contextual-like retrieval a straightforward query rather than a replay of history. -- **Recommendation is a pure function of DB state.** No in-memory state that would be lost on restart. Caches are explicit and rebuildable. - -### Request lifecycle (streaming) - -Client → auth check → track lookup → (optional) transcode ffmpeg pipeline → byte range response. Play event recorded when client reports progress beyond a threshold (see §6). - -### Request lifecycle (smart shuffle / radio) - -Client → auth → `getRandomSongs` (Subsonic) or `/api/v1/radio` (extended) → recommendation engine → query composer pulls candidate set → weighting applied → ranked list returned. - -## 5. Data model - -The schema below is the v1 target. Prefer explicit, descriptive column names over abbreviations. All timestamps are `timestamptz`. - -### Core library tables - -**`artists`** — id (uuid), name, sort_name, mbid (nullable, unique when present), created_at, updated_at. - -**`albums`** — id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at. - -**`tracks`** — id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path (unique), file_size, file_format, bitrate, mbid, genre (denormalized text for fast filtering), added_at, updated_at. - -**`users`** — id, username, password_hash, api_token, is_admin, created_at. - -### Event and session tables - -**`play_events`** — id, user_id, track_id, started_at, ended_at (nullable until completion reported), duration_played_ms, completion_ratio (computed: duration_played_ms / track.duration_ms), was_skipped (bool), client_id (nullable), session_id, session_vector_at_play (jsonb — see §6), scrobbled_at (nullable). - -**`skip_events`** — id, user_id, track_id, skipped_at, position_ms, session_id. (Subset of play_events where was_skipped=true, but kept as a separate index-friendly table for skip analytics.) - -**`sessions`** — id, user_id, started_at, ended_at (nullable), last_event_at, track_count, client_id. - -### Like tables - -**`general_likes`** — user_id, track_id, liked_at. Primary key (user_id, track_id). A single row per user-track pair. Unliking deletes the row. - -**`contextual_likes`** — id, user_id, track_id, liked_at, session_vector (jsonb, snapshot at time of like), session_id. Multiple rows per user-track pair are allowed and expected — each represents a like in a specific context. - -**`artist_preferences`** — user_id, artist_id, weight (float, -1.0 to 1.0), updated_at. Aggregate signal, computed from likes/skips but directly adjustable by user. - -### Similarity tables - -**`track_similarity`** — track_a_id, track_b_id, score (float), source (enum: listenbrainz, musicbrainz_tag, user_cooccurrence), fetched_at. Primary key (track_a_id, track_b_id, source). - -**`artist_similarity`** — analogous to track_similarity. - -### Integration tables - -**`lidarr_quarantine`** — id, track_id, requested_by_user_id, reason (enum: wrong_match, low_quality, disliked, other), requested_at, resolved_at (nullable), resolution (enum: deleted, restored, nullable). - -**`scrobble_queue`** — id, play_event_id, queued_at, attempts, last_attempt_at, last_error (nullable), submitted_at (nullable). - -### Indexes (non-exhaustive) - -- `play_events (user_id, started_at DESC)` for session assembly. -- `play_events (user_id, track_id)` for per-track history. -- `contextual_likes USING gin (session_vector)` for vector similarity queries. -- `track_similarity (track_a_id, score DESC)` for fast candidate generation. - -## 6. Core algorithms - -### Session definition - -A session is a contiguous sequence of plays by a single user with no gap longer than **30 minutes** between events. The timeout is configurable. A new play event more than 30 minutes after the last event in a session starts a new session. - -### Session vector - -At the moment a track begins playing, compute a vector representing the session context. v1 definition: - -- Last N = 5 tracks played in the current session (if fewer than 5, use what exists; if session just started, vector is marked `seed` and excluded from contextual retrieval until session has ≥3 tracks). -- For each of those N tracks, collect: artist_id, genre tags, MusicBrainz tags if available, approximate BPM/energy if available (optional, skip if not). -- Aggregate into a JSONB structure: - - `artists`: set of artist_ids - - `tags`: bag-of-tags with counts - - `recent_track_ids`: ordered list of the N track ids -- Store this JSONB on the play event and on any contextual_like created during this track. - -### Session similarity - -Two session vectors are compared via weighted Jaccard similarity on the `tags` and `artists` fields. The exact weights should be tunable via config (start with: tags 0.7, artists 0.3). This is simple and good enough for v1; upgrade paths include cosine similarity on tag vectors and eventually audio embeddings. - -### Play vs. skip classification - -A play event is a **skip** if ended before 50% of track duration AND before 30 seconds of playback. Otherwise it's a **play**. A **complete play** is ≥ 90% of duration. Thresholds configurable. - -### Weighted shuffle - -Given a candidate set (e.g. all tracks, or all tracks in an album/playlist/genre), compute a score per track: - -``` -score = base_weight - + (is_general_liked ? LIKE_BOOST : 0) - + (contextual_match_score * CONTEXT_WEIGHT) - + (recency_decay(last_played_at) * RECENCY_WEIGHT) - - (skip_ratio * SKIP_PENALTY) - - (recently_played_penalty) - + small_random_jitter -``` - -- `contextual_match_score` = max session similarity between the current session vector and any contextual_like session vector for this track, for this user. -- `recency_decay` returns a value that is high when a track hasn't been played recently and low when it has, but not infinite for never-played tracks (cold-start handling). -- `recently_played_penalty` hard-suppresses anything played in the last hour to prevent immediate repeats. - -Weights are in config. Ship with reasonable defaults and document how to tune them. - -### Radio generation - -Given a seed (track, artist, or album): - -1. Build a candidate pool from: (a) ListenBrainz similar tracks to the seed, (b) tracks by similar artists, (c) tracks sharing MusicBrainz tags, (d) user's general likes matching those tags. -2. Filter to the user's library (Lidarr-integrated libraries may choose to also propose additions — see §7). -3. Apply weighted shuffle scoring on the pool. -4. Return an ordered queue of configurable length (default 50). -5. Refresh policy: regenerate when the queue is 80% consumed, biased against tracks already played in this radio session. - -### Scrobbling - -A play event is eligible for scrobbling when: -- completion_ratio ≥ 0.5, OR -- duration_played_ms ≥ 4 minutes - -(These are ListenBrainz's recommended thresholds; confirm at implementation time.) Eligible events enter the scrobble_queue and are batched by the scrobble worker. Retries with exponential backoff on network or 5xx errors. Permanent failures (4xx, malformed) are logged and the row is marked failed. - -### ListenBrainz similarity ingest - -On library scan completion, and periodically thereafter, for tracks with MBIDs: -- Query ListenBrainz similarity endpoints in batches. -- Populate `track_similarity` and `artist_similarity`. -- Respect ListenBrainz rate limits. Cache aggressively; re-fetch no more than weekly per track. - -## 7. Lidarr integration - -### Search and add - -Expose an endpoint on the extended API that proxies Lidarr's search. Users can initiate an add from the web UI. The server calls Lidarr with the user's configured root folder and quality profile. After Lidarr reports the download complete, the next library scan picks up the file. - -### Quarantine (never auto-delete) - -When a user flags a track as wrong/low-quality/disliked: -1. A `lidarr_quarantine` row is created. -2. The track is hidden from playback for that user (soft-hide; other users in the household still see it). -3. The file is NOT deleted. -4. An admin UI lists quarantined tracks. An admin can choose to delete (via Lidarr's delete endpoint) or restore. - -**Rationale:** a one-tap deletion of a 40MB FLAC rip during a user-hostile moment is unacceptable. Quarantine is cheap; deletion is destructive. This is the correct tradeoff even though it adds a UI step. - -### Radio with add-suggestions - -When generating a radio queue, if the server has similarity data pointing to tracks not in the library AND Lidarr integration is enabled, surface these as "suggested additions" in the queue response (separate field, not interleaved with playable tracks). The user can one-tap add-to-Lidarr from the client. - -## 8. API surface - -### Subsonic / OpenSubsonic endpoints - -Implement the full OpenSubsonic spec as of implementation time. At minimum: `ping`, `getLicense`, `getMusicFolders`, `getIndexes`, `getArtists`, `getArtist`, `getAlbum`, `getAlbumList2`, `getSong`, `search3`, `stream`, `download`, `scrobble`, `star`, `unstar`, `getStarred2`, `getRandomSongs`, `getSimilarSongs2`, `createPlaylist`, `getPlaylists`, `getPlaylist`, `updatePlaylist`, `deletePlaylist`, `getCoverArt`. - -Map Subsonic concepts onto the extended model: -- Subsonic `star` → creates a `general_likes` row. -- Subsonic `scrobble` with `submission=true` → creates a play_event. -- Subsonic `scrobble` with `submission=false` → updates now-playing state. -- Subsonic `getRandomSongs` → invokes weighted shuffle. -- Subsonic `getSimilarSongs2` → invokes a simplified radio generation. - -### Extended API (`/api/v1/`) - -- `POST /api/v1/events/play` — richer play event reporting (includes seek events, client metadata). -- `POST /api/v1/likes/contextual` — create a contextual like. Server computes session vector. -- `DELETE /api/v1/likes/contextual/:id` — remove a specific contextual like. -- `GET /api/v1/session/current` — inspect the caller's current session. -- `GET /api/v1/radio` — generate radio queue with explicit parameters (seed type, pool size, weights override). -- `POST /api/v1/lidarr/search` — proxy search. -- `POST /api/v1/lidarr/add` — request add. -- `POST /api/v1/quarantine/:track_id` — flag a track. -- `POST /api/v1/quarantine/:id/resolve` — admin resolution. -- `GET /api/v1/stats/user` — listening stats for the caller. - -All extended endpoints use JSON request/response, not Subsonic's XML/JSON hybrid. - -## 9. Web UI - -Server-rendered HTML + HTMX. Pages needed: - -- Login. -- Library overview (artist/album/track browse, mostly a fallback — real browsing happens in clients). -- Now playing / current session view. -- Likes management (both lists, with ability to see contextual likes grouped by detected "contexts"). -- Lidarr search and add. -- Quarantine admin. -- User settings (scrobble target, shuffle weight overrides). -- Server settings (library paths, scan triggers, integration config) — admin only. -- Listening stats. - -Design constraint: functional and legible over fancy. The custom client is where UX effort goes. - -## 10. Configuration - -YAML config at `/etc/smartmusic/config.yaml` by default, overridable with `--config` flag and env vars (prefixed `SMARTMUSIC_`). - -Required config sections: -- `server` (listen address, external URL) -- `database` (postgres connection) -- `library` (scan paths, scan schedule) -- `transcoding` (ffmpeg path, default profiles) -- `listenbrainz` (token, enabled) -- `lidarr` (url, api key, enabled, default root folder, default quality profile) -- `shuffle` (weight overrides) -- `session` (timeout minutes, N for session vector) -- `auth` (token lifetime, admin bootstrap) - -## 11. Testing - -- Unit tests for the recommendation engine with fixed inputs / expected rankings. -- Unit tests for session boundary logic. -- Integration tests for the Subsonic endpoint compatibility using a known-good client's test suite if one exists, otherwise golden-response tests. -- Integration test harness with a Postgres testcontainer. -- Load test for the stream endpoint under concurrent clients. - -Target: ≥70% coverage on the recommendation engine and session code specifically. Do not chase coverage on the Subsonic handler code — those tests should be scenario-driven. - -## 12. Operational concerns - -- **Library scan** should be incremental (by mtime) with a full-rescan option. Large libraries (>100k tracks) should scan in under 10 minutes incremental, under 2 hours full. -- **Streaming** should support byte-range requests correctly for seek support. -- **Transcoding** results should be cacheable on disk with LRU eviction, configurable cache size. -- **Backup** guidance: the Postgres DB is the only stateful component other than the music files themselves. Document pg_dump-based backup in the README. -- **Metrics:** expose `/metrics` in Prometheus format. Key metrics: active streams, scan duration, scrobble queue depth, recommendation latency. - -## 13. Implementation order - -This is the suggested sequencing for the server. The mobile client is specified separately and its work runs in parallel starting from step 5, once the server has a verifiable Subsonic baseline. - -1. Project skeleton, config loading, logging, DB migrations framework. -2. Core schema (library tables, users). -3. Library scanner — walk, tag parse, write records. -4. Basic Subsonic API subset: auth, browse, stream. Verify against a real client (Symfonium or Feishin) end-to-end. **Milestone: usable Subsonic server.** -5. Event ingestion + session service. *(Client work can begin here against a stubbed API.)* -6. Like tables + Subsonic star/unstar wired to general_likes. -7. Recommendation engine v1: weighted shuffle without contextual signal yet. -8. Contextual likes + session vectors + contextual signal in recommendation. -9. ListenBrainz scrobble worker. -10. ListenBrainz similarity ingest. -11. Radio generation. -12. Lidarr integration (search, add, quarantine). -13. Web UI. -14. Metrics, packaging, Docker image, documentation. - -Each step should produce a runnable, testable increment. Don't implement step N+1 before step N is verified working. Server API changes discovered during client development should feed back into this spec and be implemented as they come up, rather than batched. - -## 14. Out of scope reminders - -If during development any of the following come up, stop and reconsider scope: -- Local audio feature extraction -- Neural network anything -- Adversarial multi-user hardening -- Podcast / video / internet radio -- Custom audio format support beyond what ffmpeg handles natively - -## 15. Open questions to resolve during implementation - -- Exact session vector JSONB schema — finalize after looking at real MusicBrainz tag data. -- Whether to store the `session_vector_at_play` on every play event or only on events that generate contextual likes. Storage cost vs. query simplicity tradeoff. -- Whether `getRandomSongs` from Subsonic should use the full weighted shuffle or a lighter version, since some clients call it on a loop. -- Handling of tracks without MBIDs (a significant fraction of many libraries). They can't participate in similarity-based radio. Decide whether to fall back to artist/genre/tag similarity or exclude them from radio entirely. -- Whether contextual likes should decay over time (old contextual likes become weaker signal). diff --git a/go.mod b/go.mod index dd08857a..c595b94f 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module git.fabledsword.com/bvandeusen/minstrel +module github.com/Fabled-Sword/minstrel go 1.25.0 diff --git a/internal/acoustid/client.go b/internal/acoustid/client.go index 4cbfe5f3..98cd7f3c 100644 --- a/internal/acoustid/client.go +++ b/internal/acoustid/client.go @@ -30,6 +30,8 @@ import ( "strconv" "sync" "time" + + "github.com/Fabled-Sword/minstrel/internal/buildinfo" ) // DefaultBaseURL is the lookup endpoint. @@ -45,7 +47,6 @@ const ( // bodyLimit caps the response read. A lookup with meta=recordings for a // popular song runs to tens of kilobytes. bodyLimit = 2 << 20 - userAgent = "Minstrel ( https://git.fabledsword.com/bvandeusen/minstrel )" ) // The server's error codes that the worker treats differently. @@ -127,7 +128,7 @@ func (c *Client) Lookup(ctx context.Context, apiKey, fingerprint string, duratio req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Encoding", "gzip") req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", userAgent) + req.Header.Set("User-Agent", buildinfo.UserAgent("")) resp, err := c.http.Do(req) if err != nil { diff --git a/internal/acoustid/client_test.go b/internal/acoustid/client_test.go index 437388ed..e51b5214 100644 --- a/internal/acoustid/client_test.go +++ b/internal/acoustid/client_test.go @@ -20,13 +20,13 @@ const docSample = `{ "status": "ok", "results": [{ "score": 1.0, - "id": "9ff43b6a-4f16-427c-93c2-92307ca505e0", + "id": "0a11ce00-0000-4000-8000-000000000008", "recordings": [{ "duration": 639, - "releasegroups": [{"type": "Album", "id": "ddaa2d4d-314e-3e7c-b1d0-f6d207f5aa2f", "title": "Before the Dawn Heals Us"}], - "title": "Lower Your Eyelids to Die With the Sun", - "id": "cd2e7c47-16f5-46c6-a37c-a1eb7bf599ff", - "artists": [{"id": "6d7b7cd4-254b-4c25-83f6-dd20f98ceacd", "name": "M83"}] + "releasegroups": [{"type": "Album", "id": "0a11ce00-0000-4000-8000-000000000006", "title": "Before the Gulls Wake Up"}], + "title": "Hum Quietly Under the Pier Lamps", + "id": "0a11ce00-0000-4000-8000-000000000005", + "artists": [{"id": "0a11ce00-0000-4000-8000-000000000007", "name": "K47"}] }] }] }` @@ -55,8 +55,8 @@ func TestParseLookup(t *testing.T) { }{ {"single match", docSample, []Candidate{{ Recording: Recording{ - ID: "cd2e7c47-16f5-46c6-a37c-a1eb7bf599ff", Title: "Lower Your Eyelids to Die With the Sun", - DurationSec: 639, Artists: []string{"M83"}, + ID: "0a11ce00-0000-4000-8000-000000000005", Title: "Hum Quietly Under the Pier Lamps", + DurationSec: 639, Artists: []string{"K47"}, }, Score: 1.0, }}}, diff --git a/internal/acquire/acquire_test.go b/internal/acquire/acquire_test.go deleted file mode 100644 index ac0ebf16..00000000 --- a/internal/acquire/acquire_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "path/filepath" - "strings" - "testing" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/exchange" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" - "git.fabledsword.com/bvandeusen/minstrel/internal/prowlarr" -) - -func validUpdate() Update { - return Update{Label: "Prowlarr", BaseURL: "http://prowlarr:9696", TimeoutMs: 30000, LocalPath: "/downloads", SearchesPerHour: 120} -} - -func TestUpdateValidate(t *testing.T) { - if err := validUpdate().validate(); err != nil { - t.Fatalf("a valid form: %v", err) - } - for name, tc := range map[string]struct { - edit func(*Update) - field string - }{ - "no name": {func(u *Update) { u.Label = "" }, "label"}, - "switched on with no address": {func(u *Update) { u.Enabled, u.BaseURL = true, "" }, "base_url"}, - "an address with no scheme": {func(u *Update) { u.BaseURL = "prowlarr:9696" }, "base_url"}, - "a timeout too short": {func(u *Update) { u.TimeoutMs = 10 }, "timeout_ms"}, - "a relative downloads folder": {func(u *Update) { u.LocalPath = "downloads" }, "local_path"}, - "a relative client folder": {func(u *Update) { u.RemotePath = "data" }, "remote_path"}, - "too many searches": {func(u *Update) { u.SearchesPerHour = 4000 }, "searches_per_hour"}, - } { - u := validUpdate() - tc.edit(&u) - var invalid *InvalidError - if err := u.validate(); !errors.As(err, &invalid) || invalid.Field != tc.field { - t.Errorf("%s: err = %v, want an InvalidError on %s", name, err, tc.field) - } - } - // Switched off, an empty address is a row still being set up. - u := validUpdate() - u.BaseURL = "" - if err := u.validate(); err != nil { - t.Errorf("switched off with no address: %v", err) - } -} - -func TestSourceFor_BuildsTheClientTheProtocolNames(t *testing.T) { - for protocol, check := range map[string]func(Source) bool{ - ProtocolProwlarr: func(s Source) bool { _, ok := s.Search.(*prowlarr.Client); return ok && s.Fetch != nil }, - ProtocolTorznab: func(s Source) bool { _, ok := s.Search.(*indexer.Torznab); return ok && s.Fetch != nil }, - // Exchange's results are all magnets: nothing to fetch through it. - ProtocolExchange: func(s Source) bool { _, ok := s.Search.(*exchange.Client); return ok && s.Fetch == nil }, - } { - src := SourceFor(dbq.AcquisitionService{Code: protocol, Protocol: protocol, SearchesPerHour: 7}) - if !check(src) || src.Code != protocol || src.PerHour != 7 { - t.Errorf("%s: source %+v", protocol, src) - } - } -} - -func TestJobs_AnExchangeDoesWhatItsSwitchesAllow(t *testing.T) { - ex := dbq.AcquisitionService{Kind: KindDownload, Protocol: ProtocolExchange, ServesSearch: true} - if !Searches(ex) || Fetches(ex) { - t.Error("an exchange with only search on should search and not fetch") - } - // A qBittorrent's switches mean nothing: it fetches, whatever they say. - qb := dbq.AcquisitionService{Kind: KindDownload, Protocol: ProtocolQBittorrent, ServesSearch: true} - if Searches(qb) || !Fetches(qb) { - t.Error("a qBittorrent fetches and never searches") - } -} - -func TestTest_NoAddressIsNothingToReach(t *testing.T) { - r := Test(context.Background(), dbq.AcquisitionService{Protocol: ProtocolProwlarr, Kind: KindSearch}) - if r.OK || !strings.Contains(r.Detail, "No address") { - t.Fatalf("result = %+v", r) - } -} - -func TestTest_SearchReportsResultsAndARefusedKey(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("X-Api-Key") != "good" { - w.WriteHeader(http.StatusUnauthorized) - return - } - _, _ = w.Write([]byte(`[{"title": "Radiohead - OK Computer"}]`)) - })) - defer srv.Close() - - row := dbq.AcquisitionService{Kind: KindSearch, Protocol: ProtocolProwlarr, BaseUrl: srv.URL, ApiKey: "good", TimeoutMs: 5000} - if r := Test(context.Background(), row); !r.OK || !strings.Contains(r.Detail, "1 results") { - t.Errorf("a working key: %+v", r) - } - row.ApiKey = "bad" - if r := Test(context.Background(), row); r.OK || !strings.Contains(r.Detail, "refused") { - t.Errorf("a refused key: %+v", r) - } -} - -// fakeExchange answers the three native APIs. -func fakeExchange(t *testing.T) *httptest.Server { - t.Helper() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch { - case r.URL.Path == "/api/downloads": - _, _ = w.Write([]byte(`{"enabled": true, "running": true, "inbound_conns": 3, "downloads": []}`)) - case r.URL.Path == "/api/search": - _, _ = w.Write([]byte(`{"total": 0, "results": []}`)) - case strings.HasPrefix(r.URL.Path, "/api/torrents/"): - w.WriteHeader(http.StatusNotFound) - _, _ = w.Write([]byte(`{"error": "unknown torrent"}`)) - default: - w.WriteHeader(http.StatusNotFound) - } - })) - t.Cleanup(srv.Close) - return srv -} - -func TestTest_AnExchangeReportsEachJobSwitchedOn(t *testing.T) { - srv := fakeExchange(t) - row := dbq.AcquisitionService{ - Kind: KindDownload, Protocol: ProtocolExchange, BaseUrl: srv.URL, TimeoutMs: 5000, - ServesDownloads: true, ServesSearch: true, ServesEnrichment: true, LocalPath: t.TempDir(), - } - r := Test(context.Background(), row) - if !r.OK { - t.Fatalf("all three jobs: %+v", r) - } - for _, job := range []string{"Downloads:", "Search:", "Release details:"} { - if !strings.Contains(r.Detail, job) { - t.Errorf("detail %q does not report %s", r.Detail, job) - } - } - row.ServesDownloads, row.ServesEnrichment = false, false - if r := Test(context.Background(), row); strings.Contains(r.Detail, "Downloads:") || !strings.Contains(r.Detail, "Search:") { - t.Errorf("only search on: %+v", r) - } - row.ServesSearch = false - if r := Test(context.Background(), row); r.OK || !strings.Contains(r.Detail, "switched off") { - t.Errorf("every job off: %+v", r) - } -} - -func TestTest_ADownloadClientNeedsAFolderMinstrelCanSee(t *testing.T) { - srv := fakeExchange(t) - row := dbq.AcquisitionService{ - Kind: KindDownload, Protocol: ProtocolExchange, BaseUrl: srv.URL, TimeoutMs: 5000, - ServesDownloads: true, Category: DefaultCategory, - LocalPath: filepath.Join(t.TempDir(), "not-mounted"), - } - r := Test(context.Background(), row) - if r.OK || !strings.Contains(r.Detail, "cannot see its downloads folder") { - t.Fatalf("a missing folder: %+v", r) - } - row.LocalPath = t.TempDir() - if r := Test(context.Background(), row); !r.OK || !strings.Contains(r.Detail, `"minstrel" category`) { - t.Errorf("a visible, writable folder: %+v", r) - } -} - -func TestDownloadClient_WrapsThePathMapping(t *testing.T) { - d, err := DownloadClient(dbq.AcquisitionService{Protocol: ProtocolQBittorrent, LocalPath: "/downloads", RemotePath: "/data"}) - if err != nil { - t.Fatal(err) - } - if _, plain := d.(*downloader.Client); plain { - t.Error("a row naming two folders should come back wrapped in its mapping") - } - if _, err := DownloadClient(dbq.AcquisitionService{Protocol: ProtocolProwlarr}); err == nil { - t.Error("a search protocol is not a download client") - } -} diff --git a/internal/acquire/build.go b/internal/acquire/build.go deleted file mode 100644 index 882d528c..00000000 --- a/internal/acquire/build.go +++ /dev/null @@ -1,45 +0,0 @@ -package acquire - -import ( - "context" - "fmt" - - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -// Build makes a Service from the settings as they stand: every enabled -// search source behind one paced Fanout, the first enabled download client, -// and the quality profile. Built afresh for each pass and each request, so a -// changed setting takes effect on the next one. -func Build(ctx context.Context, pool *pgxpool.Pool) (*Service, dbq.AcquisitionSetting, error) { - q := dbq.New(pool) - settings, err := q.GetAcquisitionSettings(ctx) - if err != nil { - return nil, settings, fmt.Errorf("acquire: read settings: %w", err) - } - sources, err := Sources(ctx, pool) - if err != nil { - return nil, settings, fmt.Errorf("acquire: read search sources: %w", err) - } - clients, err := q.ListUsableAcquisitionServices(ctx, JobDownload) - if err != nil { - return nil, settings, fmt.Errorf("acquire: read download clients: %w", err) - } - s := &Service{Profile: release.NewProfile(settings.AllowedQualities), Memory: NewMemory(pool)} - fan := &Fanout{Sources: sources, Pace: SearchPace} - if len(sources) > 0 { - s.Search = fan - } - if len(clients) > 0 { - row := clients[0] - client, err := DownloadClient(row) - if err != nil { - return nil, settings, fmt.Errorf("acquire: download client %s: %w", row.Code, err) - } - s.Grabber = &Downloader{Client: client, Code: row.Code, Landing: row.LocalPath, Fetch: fan} - } - return s, settings, nil -} diff --git a/internal/acquire/fanout.go b/internal/acquire/fanout.go deleted file mode 100644 index c4f607c8..00000000 --- a/internal/acquire/fanout.go +++ /dev/null @@ -1,164 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "fmt" - "strings" - "sync" - - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -// Searching every source at once. A source that is down narrows a search rather -// than failing it: the results come back with the list of who did not answer. - -// SourceFailure is one source that could not be reached. -type SourceFailure struct { - Code string - Label string - Err error -} - -// PartialError is a search that reached some sources and not others. It is -// returned alongside the results, not instead of them. -type PartialError struct { - Failures []SourceFailure - // Answered is how many sources did answer. Zero means the search failed. - Answered int -} - -func (e *PartialError) Error() string { - if e == nil || len(e.Failures) == 0 { - return "some sources did not answer" - } - parts := make([]string, 0, len(e.Failures)) - for _, f := range e.Failures { - parts = append(parts, fmt.Sprintf("%s: %s", f.Label, indexer.FirstLine(f.Err.Error()))) - } - return "some sources did not answer — " + strings.Join(parts, "; ") -} - -// Unwrap lets errors.Is find indexer.ErrUnreachable through a partial failure. -func (e *PartialError) Unwrap() []error { - if e == nil { - return nil - } - out := make([]error, 0, len(e.Failures)) - for _, f := range e.Failures { - out = append(out, f.Err) - } - return out -} - -// Fanout searches every source and merges what comes back. It is both the -// Searcher and the Fetcher, routing a .torrent fetch to the source that -// offered the result. -type Fanout struct { - // Sources in code order: the fold keeps a duplicate's first arrival, so - // the order decides which source a grab is fetched through. - Sources []Source - // Pace spaces each source's searches. Nil paces nothing. - Pace *Pacer -} - -// Search asks every source concurrently. Each client bounds its own call by -// its configured timeout, so there is no shared deadline here. -func (f *Fanout) Search(ctx context.Context, query indexer.Query) ([]indexer.Result, error) { - if f == nil || len(f.Sources) == 0 { - return nil, indexer.ErrUnconfigured - } - found := make([][]indexer.Result, len(f.Sources)) - errs := make([]error, len(f.Sources)) - var wg sync.WaitGroup - for i, src := range f.Sources { - if src.Search == nil { - continue - } - f.Pace.spend(src) - wg.Add(1) - go func(i int, src Source) { - defer wg.Done() - found[i], errs[i] = src.Search.Search(ctx, query) - }(i, src) - } - wg.Wait() - - out := make([]indexer.Result, 0, 32) - var failures []SourceFailure - answered, unconfigured := 0, 0 - for i, src := range f.Sources { - if src.Search == nil { - continue - } - if errors.Is(errs[i], indexer.ErrUnconfigured) { - unconfigured++ - continue - } - if rl, ok := indexer.AsRateLimited(errs[i]); ok { - f.Pace.hold(src.Code, rl) - } - if errs[i] != nil { - failures = append(failures, SourceFailure{Code: src.Code, Label: src.Label, Err: errs[i]}) - continue - } - answered++ - for j := range found[i] { - if found[i][j].Source == "" { - found[i][j].Source = src.Code - } - } - out = append(out, found[i]...) - } - switch { - case answered == 0 && len(failures) > 0: - return nil, &PartialError{Failures: failures} - case len(failures) > 0: - return out, &PartialError{Failures: failures, Answered: answered} - case answered == 0 && unconfigured > 0: - return nil, indexer.ErrUnconfigured - } - return out, nil -} - -// Download fetches a result's .torrent from the source that offered it: a -// Prowlarr link carries Prowlarr's key and only Prowlarr can redeem it. -func (f *Fanout) Download(ctx context.Context, r indexer.Result) ([]byte, error) { - if f == nil { - return nil, indexer.ErrUnconfigured - } - for _, src := range f.Sources { - if src.Code != r.Source { - continue - } - if src.Fetch == nil { - return nil, fmt.Errorf("%w: %s cannot fetch torrent files", indexer.ErrUnconfigured, src.Label) - } - return src.Fetch.Download(ctx, r) - } - if r.Source == "" { - return nil, fmt.Errorf("%w: this result does not say which source it came from", indexer.ErrUnconfigured) - } - return nil, fmt.Errorf("%w: %q is no longer a configured source", indexer.ErrUnconfigured, r.Source) -} - -// Narrowing is one source that did not answer, as a page shows it. -type Narrowing struct { - Source string `json:"source"` - Label string `json:"label"` - Reason string `json:"reason"` -} - -// narrowings reads a PartialError out of err, and whether any source -// answered. Nil when err is not a partial failure. -func narrowings(err error) ([]Narrowing, bool) { - var partial *PartialError - if !errors.As(err, &partial) || len(partial.Failures) == 0 { - return nil, false - } - out := make([]Narrowing, 0, len(partial.Failures)) - for _, f := range partial.Failures { - out = append(out, Narrowing{Source: f.Code, Label: f.Label, Reason: indexer.FirstLine(f.Err.Error())}) - } - return out, partial.Answered > 0 -} diff --git a/internal/acquire/grab.go b/internal/acquire/grab.go deleted file mode 100644 index 001814bd..00000000 --- a/internal/acquire/grab.go +++ /dev/null @@ -1,338 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "path" - "strings" - "sync" - "time" - - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -// Taking a release. One live grab per want: a second is tie-broken against -// the download already running. - -// Tag goes on every torrent Minstrel adds, so they can be told apart from -// anything else in the client. -const Tag = "minstrel" - -// MissingClient is Taken.Missing when no download client is set up. -const MissingClient = "download_client" - -// nearlyDone is how far along a running download stays whatever would -// replace it. -const nearlyDone = 0.9 - -// Downloader is the grab half of a Service. -type Downloader struct { - Client downloader.Driver - // Code is the client's acquisition_services row. - Code string - // Landing is the client's downloads folder as Minstrel sees it; each - // grab lands in a folder of its own under it. - Landing string - // Fetch gets a result's .torrent from the source that offered it. - Fetch Fetcher -} - -// Origin says who took a release. -type Origin struct { - By string // OriginSchedule or OriginOperator - User pgtype.UUID -} - -// Contest is how a grab fared against the download already running. -type Contest struct { - // Kept: the running one stays and this grab was not made. Replaced: - // this grab took its place. - Kept, Replaced bool - Reason string - Rival dbq.Grab -} - -// Taken is what came of a grab. -type Taken struct { - Chosen *Candidate - // Added is the only field that means a download started. - Added bool - SavePath string - Grab dbq.Grab - // Gone: the search no longer offers the release. - Gone bool - // Refused: not taken; the reason is on Chosen. - Refused bool - // Unconfigured: Missing names what is not set up ("" for search). - Unconfigured bool - Missing string - Contest *Contest - Error string -} - -// Take searches again and grabs the candidate named by key: a person's -// grab. Searching again keeps the indexer's download link (which can carry -// its key) on the server, and finds a release gone since it was shown. -// force takes what the verdict would not. -func (s *Service) Take(ctx context.Context, want Want, key string, force bool, origin Origin) Taken { - if s.Grabber == nil { - return Taken{Unconfigured: true, Missing: MissingClient} - } - found := s.For(ctx, want) - switch { - case found.Unconfigured: - return Taken{Unconfigured: true} - case found.Error != "": - return Taken{Error: found.Error} - } - chosen := pick(found.Candidates, key) - if chosen == nil { - return Taken{Gone: true} - } - return s.Grab(ctx, want, chosen, found.Candidates, force, origin) -} - -// Grab hands a judged candidate to the download client. The schedule calls -// it with the candidate it has just judged; Take calls it after searching -// again. -func (s *Service) Grab(ctx context.Context, want Want, chosen *Candidate, all []Candidate, force bool, origin Origin) Taken { - out := Taken{Chosen: chosen} - if s.Grabber == nil || s.Grabber.Client == nil { - out.Unconfigured, out.Missing = true, MissingClient - return out - } - if chosen.Verdict == Blocked || (chosen.Verdict != Grab && !force) { - out.Refused = true - return out - } - - unlock := lockWant(want.ID) - defer unlock() - contest := s.contest(ctx, want, chosen, all, origin) - if contest != nil && contest.Kept { - out.Contest = contest - return out - } - - add := downloader.Add{Magnet: chosen.Source.Magnet, Tags: []string{Tag}} - hash := chosen.InfoHash - if add.Magnet == "" { - if s.Grabber.Fetch == nil { - out.Error = "This release is a .torrent link, and nothing is set up to fetch it." - return out - } - body, err := s.Grabber.Fetch.Download(ctx, chosen.Source) - if magnet, ok := indexer.AsMagnet(err); ok { - add.Magnet, err = magnet, nil - } - if err != nil { - out.Error = indexer.FirstLine(err.Error()) - return out - } - if add.Magnet == "" { - add.Torrent = body - if meta, err := release.ParseTorrent(body); err == nil { - if hash == "" { - hash = meta.InfoHash - } - if refused := s.judgeFiles(ctx, want, chosen, hash, meta.Files, force); refused { - out.Refused = true - return out - } - } - } - } - if hash == "" && add.Magnet != "" { - hash = indexer.MagnetHash(add.Magnet) - } - add.SavePath = landingFor(s.Grabber.Landing, hash, chosen.Name) - - err := s.Grabber.Client.AddTorrent(ctx, add) - if errors.Is(err, downloader.ErrDuplicate) && s.heldElsewhere(ctx, hash) { - why := "Already in the download client outside Minstrel's category, where Minstrel cannot follow it (" + - strings.TrimPrefix(indexer.FirstLine(err.Error()), downloader.ErrDuplicate.Error()+": ") + ")" - if force { - out.Error = why + "." - return out - } - set(chosen, Blocked, Hard, CodeBlocked, why+".") - if s.Memory != nil && hash != "" { - _ = s.Memory.Block(ctx, dbq.BlockReleaseParams{ - InfoHash: hash, Name: chosen.Name, Reason: BlockGone, Detail: why + ".", WantID: want.ID, - ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(GoneBlock), Valid: true}, - }) - } - out.Refused = true - return out - } - if err != nil && !errors.Is(err, downloader.ErrDuplicate) { - if errors.Is(err, downloader.ErrUnconfigured) { - out.Unconfigured, out.Missing = true, MissingClient - } else { - out.Error = indexer.FirstLine(err.Error()) - } - return out - } - out.Added, out.SavePath = true, add.SavePath - if s.Memory == nil { - return out - } - - var replaced pgtype.UUID - why := "" - if contest != nil && contest.Replaced { - out.Contest = contest - replaced, why = contest.Rival.ID, "Replaced by "+chosen.Name+": "+contest.Reason+"." - } - g, err := s.Memory.Grabbed(ctx, dbq.InsertGrabParams{ - WantID: want.ID, InfoHash: hash, Name: chosen.Name, Key: Key(*chosen), Indexer: chosen.Indexer, - Source: chosen.Source.Source, Client: s.Grabber.Code, SavePath: add.SavePath, - Quality: string(chosen.Tier), Origin: origin.By, Forced: force, GrabbedBy: origin.User, - }, replaced, why) - if err != nil { - out.Error = "The download started, but could not be recorded: " + indexer.FirstLine(err.Error()) - return out - } - out.Grab = g - // Removed only after the new download was added and recorded, so a - // failure never leaves the want with nothing running. - if replaced.Valid && contest.Rival.InfoHash != "" { - if err := s.Grabber.Client.Delete(ctx, true, contest.Rival.InfoHash); err != nil { - contest.Reason += ". The download it replaced could not be removed from the client: " + indexer.FirstLine(err.Error()) - } - } - return out -} - -// heldElsewhere reports whether a release the client says it already holds is -// one it does not list for Minstrel: held under another category. Recorded -// as a grab, it would read as gone half an hour later and be taken again, -// every pass. A client that -// cannot answer now is given the benefit of the doubt, as the add was. -func (s *Service) heldElsewhere(ctx context.Context, hash string) bool { - if hash == "" { - return false - } - listed, err := s.Grabber.Client.Torrents(ctx, indexer.NormalizeHash(hash)) - return err == nil && len(listed) == 0 -} - -// judgeFiles judges a chosen release again on its .torrent's file list, and -// sets it aside when the files say it is not the album, so no later search -// offers it again. force still takes it. -func (s *Service) judgeFiles(ctx context.Context, want Want, chosen *Candidate, hash string, files []release.File, force bool) bool { - chosen.Files = files - if chosen.FilesCount == 0 { - chosen.FilesCount = len(files) - } - veto, reason, _ := release.JudgeFiles(want.Want, files) - if veto == "" || force { - return false - } - set(chosen, Rejected, Hard, veto, reason) - if s.Memory != nil && hash != "" { - _ = s.Memory.Block(ctx, dbq.BlockReleaseParams{ - InfoHash: hash, Name: chosen.Name, Reason: BlockFiles, Detail: reason, WantID: want.ID, - }) - } - return true -} - -var wantLocks sync.Map // want id → *sync.Mutex - -// lockWant settles two grabs for one want one after the other. The -// one-live-grab index is the backstop for anything outside this process. -func lockWant(id pgtype.UUID) func() { - if !id.Valid { - return func() {} - } - m, _ := wantLocks.LoadOrStore(id.Bytes, &sync.Mutex{}) - mu := m.(*sync.Mutex) - mu.Lock() - return mu.Unlock -} - -// contest settles a grab against the download running for its want: a -// person's grab beats the schedule's; between two of a kind the better -// candidate wins; a tie, a download nearly done, or one that cannot be -// removed stays. Nil when nothing is running. -func (s *Service) contest(ctx context.Context, want Want, chosen *Candidate, all []Candidate, origin Origin) *Contest { - if s.Memory == nil || !want.ID.Valid { - return nil - } - running, ok, err := s.Memory.LiveGrab(ctx, want.ID) - if err != nil || !ok { - return nil - } - c := &Contest{Rival: running} - if running.InfoHash != "" && running.InfoHash == chosen.InfoHash { - c.Kept, c.Reason = true, "That release is already downloading for this album." - return c - } - switch { - case origin.By == OriginOperator && running.Origin == OriginSchedule: - c.Reason = "you chose it over the one the schedule started" - case origin.By == OriginSchedule && running.Origin == OriginOperator: - c.Kept, c.Reason = true, "A download you started for this album is already running." - return c - default: - var theirs *Candidate - for i := range all { - if (running.InfoHash != "" && all[i].InfoHash == running.InfoHash) || Key(all[i]) == running.Key { - theirs = &all[i] - break - } - } - if theirs == nil || !better(*chosen, *theirs) { - c.Kept, c.Reason = true, "A download for this album is already running, and this release is no better." - return c - } - c.Reason = "it ranks above the one that was running" - } - if running.InfoHash == "" { - c.Kept, c.Reason = true, "A download for this album is already running, and it cannot be identified to replace it." - return c - } - if ts, err := s.Grabber.Client.Torrents(ctx, running.InfoHash); err == nil && len(ts) > 0 && ts[0].Progress >= nearlyDone { - c.Kept, c.Reason = true, "A download for this album is already running and nearly done." - return c - } - c.Replaced = true - return c -} - -// landingFor is the folder a download lands in: one per torrent, named by -// its infohash, so two grabs never unpack into the same place. -func landingFor(root, hash, name string) string { - dir := hash - if dir == "" { - dir = slug(name) - } - if dir == "" { - dir = "unnamed" - } - return path.Join(root, dir) -} - -// slug keeps a folder name to characters every filesystem in the chain -// takes. -func slug(s string) string { - var b strings.Builder - for _, r := range strings.ToLower(strings.TrimSpace(s)) { - if b.Len() >= 80 { - break - } - switch { - case r >= 'a' && r <= 'z', r >= '0' && r <= '9': - b.WriteRune(r) - case r == '-', r == '_', r == ' ', r == '.': - b.WriteRune('-') - } - } - return strings.Trim(b.String(), "-") -} diff --git a/internal/acquire/memory.go b/internal/acquire/memory.go deleted file mode 100644 index 8e553e9f..00000000 --- a/internal/acquire/memory.go +++ /dev/null @@ -1,199 +0,0 @@ -package acquire - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -// Block reasons, matching release_blocks_reason_check. -const ( - BlockOperator = "operator" - BlockFiles = "files" - // BlockImport: the import found its files were not the album. - BlockImport = "import" - // BlockStalled: given up on because it would not finish; held - // back until the block's expires_at. - BlockStalled = "stalled" - // BlockGone: its download client would not let Minstrel follow it, held - // outside Minstrel's category or leaving the client twice; held - // back for GoneBlock. - BlockGone = "gone" -) - -// GoneBlock is how long a release its client lost track of is held back: -// long enough that a release which keeps vanishing is tried once a day rather -// than on every pass, short enough that it is taken once the client lets go. -const GoneBlock = 24 * time.Hour - -// Grab origins, matching grabs_origin_check. -const ( - OriginSchedule = "schedule" - OriginOperator = "operator" -) - -// Memory is what searches and grabs leave behind: every candidate of a -// want's last search, the grabs, and the releases set aside. -type Memory struct { - pool *pgxpool.Pool -} - -// NewMemory returns a Memory over pool. -func NewMemory(pool *pgxpool.Pool) *Memory { return &Memory{pool: pool} } - -// Keep replaces a want's candidates with this search's, in order. -func (m *Memory) Keep(ctx context.Context, wantID pgtype.UUID, cands []Candidate) error { - return pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error { - q := dbq.New(tx) - if err := q.DeleteWantCandidates(ctx, wantID); err != nil { - return err - } - for i, c := range cands { - reasons, err := json.Marshal(c.Reasons) - if err != nil { - return err - } - if c.Reasons == nil { - reasons = []byte("[]") - } - folded := c.FoldedFrom - if folded == nil { - folded = []string{} - } - if err := q.InsertWantCandidate(ctx, dbq.InsertWantCandidateParams{ - WantID: wantID, Key: Key(c), Name: c.Name, InfoHash: c.InfoHash, Indexer: c.Indexer, - Source: c.Source.Source, SizeBytes: c.SizeBytes, Seeders: int32(c.Seeders), - FilesCount: int32(c.FilesCount), Format: release.Describe(c.Release), Quality: string(c.Tier), - Year: int32(c.Year), Verdict: string(c.Verdict), Reason: c.Reason, Reasons: reasons, - FoldedFrom: folded, Rank: int32(i), - }); err != nil { - return err - } - } - return nil - }) -} - -// blocked is every release set aside, by infohash, with the sentence a -// candidate shows. A failed read blocks nothing: offering a release set -// aside costs one grab a person can undo, while blocking everything on a -// database blip would hide every result. -func (m *Memory) blocked(ctx context.Context) map[string]string { - if m == nil { - return nil - } - rows, err := dbq.New(m.pool).ListReleaseBlocks(ctx) - if err != nil { - return nil - } - out := make(map[string]string, len(rows)) - for _, r := range rows { - out[indexer.NormalizeHash(r.InfoHash)] = BlockSentence(r.Reason, r.Detail) - } - return out -} - -// BlockSentence is what a blocked candidate says. -func BlockSentence(reason, detail string) string { - switch reason { - case BlockFiles: - if detail != "" { - return "Set aside for what its files hold: " + detail - } - return "Set aside for what its files hold." - case BlockImport: - if detail != "" { - return "Refused on import: " + detail - } - return "Refused on import: its files were not the album." - case BlockGone: - if detail != "" { - return "Held back for now: " + detail - } - return "Held back for now: its download client lost track of it." - case BlockStalled: - if detail != "" { - return "Given up on for now: " + detail - } - return "Given up on for now: it would not finish." - } - return "You set this release aside." -} - -// Block sets a release aside and marks every kept candidate of it blocked. -func (m *Memory) Block(ctx context.Context, p dbq.BlockReleaseParams) error { - p.InfoHash = indexer.NormalizeHash(p.InfoHash) - if p.InfoHash == "" { - return errors.New("a release without an infohash cannot be set aside") - } - return pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error { - q := dbq.New(tx) - if err := q.BlockRelease(ctx, p); err != nil { - return err - } - return q.MarkCandidatesBlocked(ctx, dbq.MarkCandidatesBlockedParams{ - InfoHash: p.InfoHash, Reason: BlockSentence(p.Reason, p.Detail), - }) - }) -} - -// Unblock lets a release be taken again. Its kept candidates wait for a -// person until the next search judges them afresh. -func (m *Memory) Unblock(ctx context.Context, hash string) (bool, error) { - hash = indexer.NormalizeHash(hash) - var n int64 - err := pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error { - q := dbq.New(tx) - var err error - if n, err = q.UnblockRelease(ctx, hash); err != nil { - return err - } - return q.MarkCandidatesUnblocked(ctx, dbq.MarkCandidatesUnblockedParams{ - InfoHash: hash, Reason: "Allowed again. The next search judges it afresh.", - }) - }) - return n > 0, err -} - -// LiveGrab is the download running for a want, if there is one. -func (m *Memory) LiveGrab(ctx context.Context, wantID pgtype.UUID) (dbq.Grab, bool, error) { - g, err := dbq.New(m.pool).GetLiveGrab(ctx, wantID) - if errors.Is(err, pgx.ErrNoRows) { - return g, false, nil - } - if err != nil { - return g, false, err - } - return g, true, nil -} - -// Grabbed records a download started, ending the grab it replaced first so -// the one-live-grab index holds. -func (m *Memory) Grabbed(ctx context.Context, p dbq.InsertGrabParams, replaced pgtype.UUID, why string) (dbq.Grab, error) { - var g dbq.Grab - err := pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error { - q := dbq.New(tx) - if replaced.Valid { - if err := q.EndGrab(ctx, dbq.EndGrabParams{ID: replaced, EndReason: "superseded", EndDetail: why}); err != nil { - return err - } - } - var err error - g, err = q.InsertGrab(ctx, p) - return err - }) - if err != nil { - return g, fmt.Errorf("record grab: %w", err) - } - return g, nil -} diff --git a/internal/acquire/pace.go b/internal/acquire/pace.go deleted file mode 100644 index fb2352e3..00000000 --- a/internal/acquire/pace.go +++ /dev/null @@ -1,145 +0,0 @@ -package acquire - -import ( - "context" - "sync" - "time" - - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -// SearchPace is the one Pacer every search shares. Process-wide because a -// Fanout is built fresh for each search; a Pacer per Fanout would start empty -// and pace nothing. -var SearchPace = &Pacer{} - -// holdWithoutRetryAfter is how long a source that answered 429 without saying -// for how long is left alone: one schedule tick. -const holdWithoutRetryAfter = 10 * time.Minute - -// Pacer spaces the searches sent to each source by its searches_per_hour: a -// spacing, not a burst bucket, because Prowlarr answers 429 to a few requests -// in quick succession. Every search spends, the schedule's and a -// person's alike; only the schedule waits. -type Pacer struct { - // Now and Sleep are the clock, replaceable in tests. - Now func() time.Time - Sleep func(context.Context, time.Duration) error - - mu sync.Mutex - next map[string]time.Time -} - -func (p *Pacer) now() time.Time { - if p.Now != nil { - return p.Now() - } - return time.Now() -} - -func (p *Pacer) sleep(ctx context.Context, d time.Duration) error { - if p.Sleep != nil { - return p.Sleep(ctx, d) - } - t := time.NewTimer(d) - defer t.Stop() - select { - case <-t.C: - return nil - case <-ctx.Done(): - return ctx.Err() - } -} - -// gap is the spacing a source's number asks for; zero is unpaced. -func gap(perHour int) time.Duration { - if perHour <= 0 { - return 0 - } - return time.Hour / time.Duration(perHour) -} - -// readyAt is when every source may next be asked. -func (p *Pacer) readyAt(sources []Source) time.Time { - p.mu.Lock() - defer p.mu.Unlock() - var at time.Time - for _, s := range sources { - if s.Search == nil { - continue - } - if n := p.next[s.Code]; n.After(at) { - at = n - } - } - return at -} - -// Wait holds until every source may be asked, and answers false, without -// waiting, when that is after the deadline or ctx ends first. All of them, -// not any: a search while one is held back would be narrowed, and the want -// recorded as looked for. -func (p *Pacer) Wait(ctx context.Context, sources []Source, deadline time.Time) bool { - if p == nil { - return true - } - at := p.readyAt(sources) - if !deadline.IsZero() && at.After(deadline) { - return false - } - if d := at.Sub(p.now()); d > 0 { - return p.sleep(ctx, d) == nil - } - return ctx.Err() == nil -} - -// spend takes one search's slot from a source. -func (p *Pacer) spend(s Source) { - g := gap(s.PerHour) - if p == nil || g == 0 { - return - } - p.mu.Lock() - defer p.mu.Unlock() - if p.next == nil { - p.next = map[string]time.Time{} - } - at := p.next[s.Code] - if t := p.now(); at.Before(t) { - at = t - } - p.next[s.Code] = at.Add(g) -} - -// hold leaves a source alone after it answered 429, for as long as it asked, -// whatever its searches_per_hour says. -func (p *Pacer) hold(code string, rl *indexer.RateLimited) { - if p == nil { - return - } - d := rl.RetryAfter - if d <= 0 { - d = holdWithoutRetryAfter - } - p.mu.Lock() - defer p.mu.Unlock() - if p.next == nil { - p.next = map[string]time.Time{} - } - if until := p.now().Add(d); until.After(p.next[code]) { - p.next[code] = until - } -} - -// Ready holds until every source this service searches may be asked again, -// and answers false when that is past the deadline. The schedule calls it -// before each want; a person's search never does. -func (s *Service) Ready(ctx context.Context, deadline time.Time) bool { - if s == nil { - return ctx.Err() == nil - } - if f, ok := s.Search.(*Fanout); ok && f != nil { - return f.Pace.Wait(ctx, f.Sources, deadline) - } - return ctx.Err() == nil -} diff --git a/internal/acquire/search.go b/internal/acquire/search.go deleted file mode 100644 index 73960b3a..00000000 --- a/internal/acquire/search.go +++ /dev/null @@ -1,408 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "sort" - "strings" - - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -// One search for one want, and what could be done about each result. -// internal/release -// says whether a name is the album and what quality it is; this package -// asks in the right order and says why in words a person can act on. - -// Verdict is what can be done about one result. -type Verdict string - -const ( - // Grab: the album, in a quality the profile takes. - Grab Verdict = "grab" - // Review: maybe the album; a person decides. - Review Verdict = "review" - // Refused: the album, in a quality the profile does not take. The only - // verdict that names a setting. - Refused Verdict = "refused" - // Rejected: not the album. - Rejected Verdict = "rejected" - // Blocked: a release set aside, by a person or by its files. - Blocked Verdict = "blocked" -) - -// order sorts verdicts: what can be taken first, what was given up on last. -var order = map[Verdict]int{Grab: 0, Review: 1, Refused: 2, Rejected: 3, Blocked: 4} - -// Reason kinds: a hard reason is a fact about the bytes, a soft one about the -// moment or a setting. -const ( - Hard = "hard" - Soft = "soft" -) - -// Reason codes beyond internal/release's vetoes. -const ( - CodeBlocked = "blocked" - CodeProfile = "profile" - CodeNoSeeders = "no_seeders" - CodeDoubt = "doubt" - // CodeNotBetter: the album, but no better than the copy the library - // holds, for a want that is an upgrade. - CodeNotBetter = "not_better" -) - -// Reason is one thing a verdict rests on. -type Reason struct { - Kind string `json:"kind"` - Code string `json:"code"` - Text string `json:"text"` -} - -// Want is the album searched for: its wants row and how the catalogue -// describes it. -type Want struct { - ID pgtype.UUID - release.Want - // Floor is the tier of the copy the library holds, for an album wanted - // for a better one: a release must rank above it. "" for an - // album not held, and for a video rip, which any clean copy beats. - Floor release.Tier - // Held says the floor in words: "MP3, about 192 kbps". - Held string -} - -// Candidate is one result with everything decided about it. -type Candidate struct { - release.Release - // Source is the indexer's own result. It never leaves the server: its - // DownloadURL can carry the indexer's key. - Source indexer.Result - InfoHash string - Indexer string - SizeBytes int64 - Seeders int - SwarmKnown bool - Category int - FilesCount int - // Files is the torrent's file list once its .torrent has been read. - Files []release.File - FoldedFrom []string - - Tier release.Tier - YearAgrees bool - Verdict Verdict - Reason string - Reasons []Reason -} - -// Key is how a candidate is named across a search and a grab: its infohash, -// or its name when the source gave none. -func Key(c Candidate) string { - if c.InfoHash != "" { - return c.InfoHash - } - return c.Name -} - -// Result is one search. -type Result struct { - Query string - // Unconfigured: no search source is set up. - Unconfigured bool - // Error is a search that failed outright. - Error string - // Narrowed names sources that did not answer on a search that otherwise - // did. - Narrowed []Narrowing - Considered int - Folded int - // Looked is how many .torrent files were read for their file lists. - Looked int - Candidates []Candidate - // KeepError: the candidates could not be stored. - KeepError string -} - -// Grabbable is what may be taken, best first. -func (r Result) Grabbable() []Candidate { - var out []Candidate - for _, c := range r.Candidates { - if c.Verdict == Grab { - out = append(out, c) - } - } - return out -} - -// ForAPerson says whether anything found is worth a person's look: a -// release that may be the album, whatever its quality. -func (r Result) ForAPerson() bool { - for _, c := range r.Candidates { - if c.Verdict == Grab || c.Verdict == Review || c.Verdict == Refused { - return true - } - } - return false -} - -// Service searches and grabs. -type Service struct { - // Search is nil when no source is configured. - Search Searcher - // Grabber is nil when no download client is configured. - Grabber *Downloader - Profile release.Profile - // Memory stores candidates, grabs and blocks. Nil keeps nothing. - Memory *Memory -} - -// Query is the text sent to the indexers: the artist and the title, without -// a trailing bracketed part the release names usually leave off. -func Query(w release.Want) string { - title := w.Title - if i := strings.IndexAny(title, "(["); i > 0 { - title = title[:i] - } - return strings.Join(strings.Fields(strings.TrimSpace(w.Artist)+" "+strings.TrimSpace(title)), " ") -} - -// For searches for one want and judges everything that comes back. It never -// returns an error: a search that could not be made is a Result saying so. -func (s *Service) For(ctx context.Context, want Want) Result { - r := Result{Query: Query(want.Want)} - if s == nil || s.Search == nil { - r.Unconfigured = true - return r - } - found, err := s.Search.Search(ctx, indexer.Query{Text: r.Query, Categories: indexer.MusicCategories}) - // A partial search arrives as results and an error together. - if narrowed, answered := narrowings(err); narrowed != nil && answered { - r.Narrowed, err = narrowed, nil - } - switch { - case errors.Is(err, indexer.ErrUnconfigured): - r.Unconfigured = true - return r - case err != nil: - r.Error = indexer.FirstLine(err.Error()) - return r - } - r.Considered = len(found) - cands, folded := fold(found) - r.Folded = folded - - blocked := s.Memory.blocked(ctx) - for i := range cands { - decide(&cands[i], want, s.Profile, blocked) - } - sortCandidates(cands) - for _, i := range s.peek(ctx, cands) { - decide(&cands[i], want, s.Profile, blocked) - r.Looked++ - } - sortCandidates(cands) - r.Candidates = cands - if s.Memory != nil && want.ID.Valid { - if err := s.Memory.Keep(ctx, want.ID, cands); err != nil { - r.KeepError = indexer.FirstLine(err.Error()) - } - } - return r -} - -// decide works out one candidate's verdict, in order: given up on, then -// whether it is the album, then whether the profile takes its quality, then -// whether anything leaves it to a person. A quality refusal said about the -// wrong album would be noise, so identity comes first. -func decide(c *Candidate, want Want, profile release.Profile, blocked map[string]string) { - w := want.Want - c.Verdict, c.Reason, c.Reasons = "", "", nil - if why, ok := blocked[c.InfoHash]; ok && c.InfoHash != "" { - set(c, Blocked, Hard, CodeBlocked, why) - return - } - m := release.Judge(w, c.Release) - c.YearAgrees = m.YearAgrees - if m.Veto != "" { - set(c, Rejected, Hard, m.Veto, m.Reason) - return - } - doubt := m.Doubt - if len(c.Files) > 0 { - if in := release.Inspect(c.Files); in.Format != "" { - c.Format = in.Format - } - veto, reason, fileDoubt := release.JudgeFiles(w, c.Files) - if veto != "" { - set(c, Rejected, Hard, veto, reason) - return - } - if doubt == "" { - doubt = fileDoubt - } - } - c.Tier = release.TierOf(c.Release, c.Category) - if !profile.Allows(c.Tier) { - set(c, Refused, Soft, CodeProfile, "Your quality settings don’t take "+strings.ToLower(release.Label(c.Tier))+".") - return - } - if want.Floor != "" && release.Rank(c.Tier) <= release.Rank(want.Floor) { - held := want.Held - if held == "" { - held = strings.ToLower(release.Label(want.Floor)) - } - set(c, Refused, Soft, CodeNotBetter, "No better than the copy you have ("+held+").") - return - } - if doubt != "" { - set(c, Review, Soft, CodeDoubt, doubt) - return - } - if c.Seeders == 0 { - set(c, Review, Soft, CodeNoSeeders, "Nobody is sharing it right now.") - return - } - c.Verdict = Grab - c.Reason = "The album, " + strings.ToLower(release.Label(c.Tier)) + "." - if d := release.Describe(c.Release); d != "" { - c.Reason = "The album, " + d + "." - } -} - -func set(c *Candidate, v Verdict, kind, code, text string) { - c.Verdict, c.Reason = v, text - c.Reasons = append(c.Reasons, Reason{Kind: kind, Code: code, Text: text}) -} - -// sortCandidates puts the best first, stably so the same search proposes the -// same grab twice. -func sortCandidates(cands []Candidate) { - sort.SliceStable(cands, func(a, b int) bool { return better(cands[a], cands[b]) }) -} - -// better says whether x ranks above y: verdict, then quality, then how many -// share it, then whether its year agrees. -func better(x, y Candidate) bool { - if order[x.Verdict] != order[y.Verdict] { - return order[x.Verdict] < order[y.Verdict] - } - if rx, ry := release.Rank(x.Tier), release.Rank(y.Tier); rx != ry { - return rx > ry - } - if x.Seeders != y.Seeders { - return x.Seeders > y.Seeders - } - return x.YearAgrees && !y.YearAgrees -} - -// fold merges results that are the same torrent, by infohash. Prowlarr -// aggregates, so one release arrives once per tracker that lists it. A -// result without a hash is never folded: an absent hash is not a shared one. -func fold(found []indexer.Result) ([]Candidate, int) { - out := make([]Candidate, 0, len(found)) - at := make(map[string]int, len(found)) - folded := 0 - for _, f := range found { - if strings.TrimSpace(f.Title) == "" { - continue - } - hash := indexer.NormalizeHash(f.InfoHash) - if hash == "" && f.Magnet != "" { - hash = indexer.MagnetHash(f.Magnet) - } - if hash != "" { - if i, seen := at[hash]; seen { - folded++ - if f.Indexer != "" { - out[i].FoldedFrom = append(out[i].FoldedFrom, f.Indexer) - } - // A measured swarm beats a reported one; among like, the - // highest count. - switch { - case f.SwarmKnown && !out[i].SwarmKnown: - out[i].Seeders, out[i].SwarmKnown = f.Seeders, true - case f.SwarmKnown == out[i].SwarmKnown && f.Seeders > out[i].Seeders: - out[i].Seeders = f.Seeders - } - if f.FilesCount > 0 && out[i].FilesCount == 0 { - out[i].FilesCount = f.FilesCount - } - continue - } - at[hash] = len(out) - } - out = append(out, Candidate{ - Release: release.Parse(f.Title), Source: f, InfoHash: hash, Indexer: f.Indexer, - SizeBytes: f.SizeBytes, Seeders: f.Seeders, SwarmKnown: f.SwarmKnown, - Category: f.Category, FilesCount: f.FilesCount, - }) - } - return out, folded -} - -// maxPeeks is how many .torrent files one search reads. Few: each goes -// through Prowlarr to a tracker, and Prowlarr answers 429 to a burst. -const maxPeeks = 3 - -// peek reads the .torrent of candidates that are the album but whose name -// states no format, so their files can say what they are; it returns which -// now carry a file list. A failed fetch leaves the candidate as it was. -func (s *Service) peek(ctx context.Context, cands []Candidate) []int { - f, ok := s.Search.(Fetcher) - if !ok { - return nil - } - var looked []int - for i := range cands { - if len(looked) >= maxPeeks || ctx.Err() != nil { - break - } - c := &cands[i] - if c.Tier != release.TierUnknown || (c.Verdict != Grab && c.Verdict != Refused) || - c.Files != nil || c.Source.DownloadURL == "" || c.Source.Magnet != "" { - continue - } - body, err := f.Download(ctx, c.Source) - if err != nil { - continue - } - meta, err := release.ParseTorrent(body) - if err != nil { - continue - } - c.Files = meta.Files - if c.InfoHash == "" { - c.InfoHash = meta.InfoHash - } - if c.FilesCount == 0 { - c.FilesCount = len(meta.Files) - } - looked = append(looked, i) - } - return looked -} - -// pick finds a candidate by key: the infohash first, the exact name for a -// result that has none. -func pick(cands []Candidate, key string) *Candidate { - key = strings.TrimSpace(key) - if key == "" { - return nil - } - hash := indexer.NormalizeHash(key) - for i := range cands { - if cands[i].InfoHash != "" && cands[i].InfoHash == hash { - return &cands[i] - } - } - for i := range cands { - if cands[i].InfoHash == "" && cands[i].Name == key { - return &cands[i] - } - } - return nil -} diff --git a/internal/acquire/search_test.go b/internal/acquire/search_test.go deleted file mode 100644 index 63022d0e..00000000 --- a/internal/acquire/search_test.go +++ /dev/null @@ -1,291 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "fmt" - "strings" - "testing" - "time" - - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -type fakeSearch struct { - results []indexer.Result - err error - asked []indexer.Query -} - -func (f *fakeSearch) Search(_ context.Context, q indexer.Query) ([]indexer.Result, error) { - f.asked = append(f.asked, q) - return f.results, f.err -} - -var ram = Want{Want: release.Want{ - Artist: "Daft Punk", Title: "Random Access Memories", Year: 2013, PrimaryType: "Album", - MinTracks: 13, MaxTracks: 15, -}} - -var anyQuality = release.NewProfile([]string{ - "lossless_hires", "lossless", "lossy_high", "lossy_standard", "lossy_low", "lossy_poor", "lossy_trash", -}) - -func result(title, hash string, seeders int) indexer.Result { - return indexer.Result{Title: title, InfoHash: hash, Seeders: seeders, Indexer: "Knaben", Source: "prowlarr", - Magnet: "magnet:?xt=urn:btih:" + hash} -} - -func TestFor_JudgesSortsAndFolds(t *testing.T) { - search := &fakeSearch{results: []indexer.Result{ - result("Daft Punk - Random Access Memories (2013) [MP3 320]", "aaaa", 40), - result("Daft Punk Random Access Memories (Drumless Edition 2023) [Flac 24-88]", "bbbb", 90), - result("Daft Punk - Random Access Memories (2013) [FLAC]", "cccc", 12), - result("Daft Punk - Random Access Memories (2013) [FLAC]", "CCCC", 30), // the same torrent from another tracker - result("Daft Punk - Discovery (2001) [FLAC]", "dddd", 50), - }} - s := &Service{Search: search, Profile: anyQuality} - r := s.For(context.Background(), ram) - - if len(search.asked) != 1 || search.asked[0].Text != "Daft Punk Random Access Memories" { - t.Fatalf("asked %+v", search.asked) - } - if r.Considered != 5 || r.Folded != 1 || len(r.Candidates) != 4 { - t.Fatalf("considered %d folded %d candidates %d", r.Considered, r.Folded, len(r.Candidates)) - } - // Lossless before high-quality lossy among what can be taken; the - // folded copy keeps the higher seeder count. - first, second := r.Candidates[0], r.Candidates[1] - if first.InfoHash != "cccc" || first.Verdict != Grab || first.Seeders != 30 || first.Tier != release.TierLossless { - t.Errorf("first = %s %s %d %s", first.Name, first.Verdict, first.Seeders, first.Tier) - } - if second.InfoHash != "aaaa" || second.Verdict != Grab { - t.Errorf("second = %s %s", second.Name, second.Verdict) - } - for _, c := range r.Candidates[2:] { - if c.Verdict != Rejected || len(c.Reasons) != 1 || c.Reasons[0].Kind != Hard { - t.Errorf("%s: %s %+v", c.Name, c.Verdict, c.Reasons) - } - } - if len(r.Grabbable()) != 2 || !r.ForAPerson() { - t.Errorf("grabbable %d", len(r.Grabbable())) - } -} - -func TestFor_ProfileSeedersAndDoubt(t *testing.T) { - search := &fakeSearch{results: []indexer.Result{ - result("Daft Punk - Random Access Memories [MP3 128]", "aaaa", 5), - result("Daft Punk - Random Access Memories [FLAC]", "bbbb", 0), - result("Daft Punk - Random Access Memories", "cccc", 9), - }} - s := &Service{Search: search, Profile: release.NewProfile([]string{"lossless", "lossy_high"})} - r := s.For(context.Background(), ram) - verdicts := map[string]Verdict{} - for _, c := range r.Candidates { - verdicts[c.InfoHash] = c.Verdict - } - if verdicts["aaaa"] != Refused || verdicts["bbbb"] != Review || verdicts["cccc"] != Refused { - t.Errorf("verdicts = %v", verdicts) - } - if len(r.Grabbable()) != 0 || !r.ForAPerson() { - t.Error("nothing grabbable, but something for a person") - } -} - -func TestFor_BlockedReleasesAreSetAside(t *testing.T) { - c := Candidate{Release: release.Parse("Daft Punk - Random Access Memories [FLAC]"), InfoHash: "aaaa", Seeders: 3} - decide(&c, ram, anyQuality, map[string]string{"aaaa": "You set this release aside."}) - if c.Verdict != Blocked || c.Reason != "You set this release aside." { - t.Errorf("verdict %s %q", c.Verdict, c.Reason) - } -} - -func TestFor_UnconfiguredAndFailedSearches(t *testing.T) { - if r := (&Service{}).For(context.Background(), ram); !r.Unconfigured { - t.Error("no source is unconfigured") - } - r := (&Service{Search: &fakeSearch{err: indexer.ErrUnconfigured}}).For(context.Background(), ram) - if !r.Unconfigured { - t.Error("ErrUnconfigured is unconfigured") - } - r = (&Service{Search: &fakeSearch{err: errors.New("dial tcp: refused")}}).For(context.Background(), ram) - if r.Error == "" { - t.Error("a failed search says so") - } -} - -func TestFanout_ANarrowedSearchKeepsWhatAnswered(t *testing.T) { - up := &fakeSearch{results: []indexer.Result{result("Daft Punk - Random Access Memories [FLAC]", "aaaa", 3)}} - down := &fakeSearch{err: indexer.ErrUnreachable} - f := &Fanout{Sources: []Source{{Code: "prowlarr", Label: "Prowlarr", Search: up}, {Code: "torznab", Label: "Feed", Search: down}}} - r := (&Service{Search: f, Profile: anyQuality}).For(context.Background(), ram) - if r.Error != "" || len(r.Candidates) != 1 || len(r.Narrowed) != 1 || r.Narrowed[0].Source != "torznab" { - t.Errorf("narrowed search: error %q, %d candidates, narrowed %+v", r.Error, len(r.Candidates), r.Narrowed) - } - f.Sources = f.Sources[1:] - if r := (&Service{Search: f}).For(context.Background(), ram); r.Error == "" { - t.Error("every source down is a failed search") - } -} - -func TestPacer_SpacesSearchesAndHoldsAfterA429(t *testing.T) { - now := time.Unix(0, 0) - var slept time.Duration - p := &Pacer{Now: func() time.Time { return now }, Sleep: func(_ context.Context, d time.Duration) error { slept += d; return nil }} - src := []Source{{Code: "prowlarr", PerHour: 120, Search: &fakeSearch{}}} - p.spend(src[0]) - if !p.Wait(context.Background(), src, now.Add(time.Hour)) || slept != 30*time.Second { - t.Errorf("slept %s, want 30s", slept) - } - if p.Wait(context.Background(), src, now.Add(time.Second)) { - t.Error("waited past the deadline") - } - p.hold("prowlarr", &indexer.RateLimited{RetryAfter: 5 * time.Minute}) - if at := p.readyAt(src); at.Sub(now) != 5*time.Minute { - t.Errorf("held until %s", at.Sub(now)) - } -} - -type fakeClient struct { - downloader.Driver - added []downloader.Add - addErr error - deleted []string - progress float64 - // elsewhere: the client holds it but does not list it for Minstrel. - elsewhere bool -} - -func (c *fakeClient) AddTorrent(_ context.Context, a downloader.Add) error { - c.added = append(c.added, a) - return c.addErr -} - -func (c *fakeClient) Torrents(_ context.Context, hashes ...string) ([]downloader.Torrent, error) { - if c.elsewhere { - return nil, nil - } - return []downloader.Torrent{{Hash: hashes[0], Progress: c.progress}}, nil -} - -func (c *fakeClient) Delete(_ context.Context, _ bool, hashes ...string) error { - c.deleted = append(c.deleted, hashes...) - return nil -} - -func TestGrab_AddsAMagnetToItsOwnFolder(t *testing.T) { - client := &fakeClient{} - s := &Service{Search: &fakeSearch{results: []indexer.Result{ - result("Daft Punk - Random Access Memories (2013) [FLAC]", "ABCD", 8), - }}, Profile: anyQuality, Grabber: &Downloader{Client: client, Code: "qbittorrent", Landing: "/downloads"}} - r := s.For(context.Background(), ram) - took := s.Grab(context.Background(), ram, &r.Candidates[0], r.Candidates, false, Origin{By: OriginSchedule}) - if !took.Added || took.SavePath != "/downloads/abcd" { - t.Fatalf("took %+v", took) - } - if len(client.added) != 1 || !strings.Contains(strings.ToLower(client.added[0].Magnet), "abcd") || client.added[0].Tags[0] != Tag { - t.Errorf("added %+v", client.added) - } -} - -func TestGrab_RefusesWhatTheVerdictWouldNotTake(t *testing.T) { - client := &fakeClient{} - s := &Service{Grabber: &Downloader{Client: client, Landing: "/downloads"}} - review := Candidate{Verdict: Review, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}} - if took := s.Grab(context.Background(), ram, &review, nil, false, Origin{By: OriginSchedule}); !took.Refused { - t.Error("a review was taken unforced") - } - if took := s.Grab(context.Background(), ram, &review, nil, true, Origin{By: OriginOperator}); !took.Added { - t.Errorf("a forced review was not taken: %+v", took) - } - blocked := Candidate{Verdict: Blocked, InfoHash: "bbbb"} - if took := s.Grab(context.Background(), ram, &blocked, nil, true, Origin{By: OriginOperator}); !took.Refused { - t.Error("forcing took a release set aside") - } - if took := (&Service{}).Grab(context.Background(), ram, &review, nil, true, Origin{}); !took.Unconfigured || took.Missing != MissingClient { - t.Errorf("no client: %+v", took) - } -} - -func TestGrab_AClientThatAlreadyHasItCounts(t *testing.T) { - client := &fakeClient{addErr: downloader.ErrDuplicate} - s := &Service{Grabber: &Downloader{Client: client, Landing: "/downloads"}} - c := Candidate{Verdict: Grab, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}} - if took := s.Grab(context.Background(), ram, &c, nil, false, Origin{By: OriginSchedule}); !took.Added { - t.Errorf("a duplicate: %+v", took) - } -} - -// A duplicate the client does not list for Minstrel sits under another -// category, where it would read as gone half an hour later. It is set -// aside rather than taken; forced, it is refused with the client's reason. -func TestGrab_ADuplicateHeldOutsideMinstrelIsNotTaken(t *testing.T) { - client := &fakeClient{addErr: fmt.Errorf("%w: already downloading Ohio Players (lidarr)", downloader.ErrDuplicate), elsewhere: true} - s := &Service{Grabber: &Downloader{Client: client, Landing: "/downloads"}} - c := Candidate{Verdict: Grab, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}} - took := s.Grab(context.Background(), ram, &c, nil, false, Origin{By: OriginSchedule}) - if took.Added || !took.Refused { - t.Fatalf("took %+v", took) - } - if c.Verdict != Blocked || !strings.Contains(c.Reason, "(already downloading Ohio Players (lidarr))") { - t.Errorf("candidate %s: %q", c.Verdict, c.Reason) - } - - forced := Candidate{Verdict: Grab, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}} - took = s.Grab(context.Background(), ram, &forced, nil, true, Origin{By: OriginOperator}) - if took.Added || !strings.Contains(took.Error, "outside Minstrel's category") { - t.Errorf("forced: %+v", took) - } -} - -func TestBetter_QualityThenSeedersThenYear(t *testing.T) { - flac := Candidate{Verdict: Grab, Tier: release.TierLossless, Seeders: 2} - mp3 := Candidate{Verdict: Grab, Tier: release.TierLossyHigh, Seeders: 90} - if !better(flac, mp3) || better(mp3, flac) { - t.Error("quality first among grabs") - } - busy := Candidate{Verdict: Grab, Tier: release.TierLossless, Seeders: 20} - if !better(busy, flac) { - t.Error("then seeders") - } - dated := Candidate{Verdict: Grab, Tier: release.TierLossless, Seeders: 2, YearAgrees: true} - if !better(dated, flac) { - t.Error("then the year") - } - if better(Candidate{Verdict: Review}, flac) || !better(flac, Candidate{Verdict: Review}) { - t.Error("a grab ranks above a review") - } -} - -func TestLandingFor_OneFolderPerTorrent(t *testing.T) { - if got := landingFor("/downloads", "abcd", "x"); got != "/downloads/abcd" { - t.Error(got) - } - if got := landingFor("/downloads", "", "Daft Punk: R.A.M. [FLAC]"); got != "/downloads/daft-punk-r-a-m--flac" { - t.Error(got) - } -} - -func TestDecide_AnUpgradeTakesOnlyABetterCopy(t *testing.T) { - up := ram - up.Floor, up.Held = release.TierLossyLow, "MP3, about 192 kbps" - same := Candidate{Release: release.Parse("Daft Punk - Random Access Memories [MP3 192]"), InfoHash: "aaaa", Seeders: 3} - decide(&same, up, anyQuality, nil) - if same.Verdict != Refused || same.Reasons[0].Code != CodeNotBetter || - same.Reason != "No better than the copy you have (MP3, about 192 kbps)." { - t.Errorf("same quality: %s %q", same.Verdict, same.Reason) - } - flac := Candidate{Release: release.Parse("Daft Punk - Random Access Memories [FLAC]"), InfoHash: "bbbb", Seeders: 3} - decide(&flac, up, anyQuality, nil) - if flac.Verdict != Grab { - t.Errorf("a FLAC over a 192 MP3: %s %q", flac.Verdict, flac.Reason) - } - // A video rip has no floor: any clean copy is better. - rip := ram - decide(&same, rip, anyQuality, nil) - if same.Verdict != Grab { - t.Errorf("no floor: %s %q", same.Verdict, same.Reason) - } -} diff --git a/internal/acquire/settings.go b/internal/acquire/settings.go deleted file mode 100644 index e71284a3..00000000 --- a/internal/acquire/settings.go +++ /dev/null @@ -1,185 +0,0 @@ -// Package acquire turns the configured indexers and download clients into -// working clients. -// -// ONE BUILDER PER KIND. SourceFor makes a search source from a row and -// DownloadClient makes a download client, path mapping included. The grab, -// the importer, the stall watchdog and the settings page's Test all build -// through them, so a Test that passes vouches for the path real traffic takes. -// Clients are rebuilt from the row on every use, so a changed address or a new -// key takes effect on the next call. -package acquire - -import ( - "context" - "errors" - "fmt" - "time" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/exchange" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" - "git.fabledsword.com/bvandeusen/minstrel/internal/prowlarr" -) - -// Kinds: which list a row appears in. -const ( - KindSearch = "search" - KindDownload = "download" -) - -// Jobs a row can do. An exchange row does each its switch allows; every -// other row does the one its kind names. -const ( - JobSearch = "search" - JobDownload = "download" - JobEnrichment = "enrichment" -) - -// Protocols: which client a row builds. -const ( - ProtocolProwlarr = "prowlarr" - ProtocolTorznab = "torznab" - ProtocolQBittorrent = "qbittorrent" - ProtocolExchange = "exchange" -) - -// DefaultCategory files everything Minstrel adds to a download client. -const DefaultCategory = "minstrel" - -// addable is what a new row of a protocol starts as. -type addable struct { - kind string - label string - category string - timeoutMs int32 - perHour int32 -} - -// catalogue is every protocol an admin can add. Exchange starts unpaced -// (it searches its own database); the others at 120 searches an hour, which -// keeps a Prowlarr's indexers under the rate most trackers allow. -var catalogue = map[string]addable{ - ProtocolProwlarr: {kind: KindSearch, label: "Prowlarr", timeoutMs: 60000, perHour: 120}, - ProtocolTorznab: {kind: KindSearch, label: "Torznab feed", timeoutMs: 30000, perHour: 120}, - ProtocolQBittorrent: {kind: KindDownload, label: "qBittorrent", category: DefaultCategory, timeoutMs: 15000, perHour: 0}, - ProtocolExchange: {kind: KindDownload, label: "FabledExchange", category: DefaultCategory, timeoutMs: 30000, perHour: 0}, -} - -// Addable says whether protocol is one an admin can add. -func Addable(protocol string) bool { - _, ok := catalogue[protocol] - return ok -} - -// Searches says whether a row is a search source. -func Searches(row dbq.AcquisitionService) bool { - if row.Protocol == ProtocolExchange { - return row.ServesSearch - } - return row.Kind == KindSearch -} - -// Fetches says whether a row is a download client. -func Fetches(row dbq.AcquisitionService) bool { - if row.Protocol == ProtocolExchange { - return row.ServesDownloads - } - return row.Kind == KindDownload -} - -// Searcher is a search source. -type Searcher interface { - Search(ctx context.Context, q indexer.Query) ([]indexer.Result, error) -} - -// Fetcher fetches a result's .torrent through the source that offered it. -type Fetcher interface { - Download(ctx context.Context, r indexer.Result) ([]byte, error) -} - -// Source is one configured search source. -type Source struct { - Code string - Label string - // PerHour is the most searches the schedule sends it an hour; 0 = unpaced. - PerHour int - Search Searcher - // Fetch is nil for a source whose results are all magnets. - Fetch Fetcher -} - -// SourceFor builds the search source a row describes. -func SourceFor(row dbq.AcquisitionService) Source { - src := Source{Code: row.Code, Label: row.Label, PerHour: int(row.SearchesPerHour)} - timeout := msDuration(row.TimeoutMs) - switch row.Protocol { - case ProtocolProwlarr: - c := &prowlarr.Client{Config: prowlarr.Config{ - Code: row.Code, BaseURL: row.BaseUrl, APIKey: row.ApiKey, Timeout: timeout, - }} - src.Search, src.Fetch = c, c - case ProtocolExchange: - src.Search = ExchangeFor(row) - default: - c := &indexer.Torznab{Config: indexer.TorznabConfig{ - Code: row.Code, FeedURL: row.BaseUrl, APIKey: row.ApiKey, Timeout: timeout, - }} - src.Search, src.Fetch = c, c - } - return src -} - -// ExchangeFor builds the search and enrichment client for an exchange row. -func ExchangeFor(row dbq.AcquisitionService) *exchange.Client { - return &exchange.Client{ - Code: row.Code, - Config: exchange.Config{ - BaseURL: row.BaseUrl, APIKey: row.ApiKey, Timeout: msDuration(row.TimeoutMs), - }, - } -} - -// DownloadClient builds the download client a row describes, wrapped in its -// path mapping. -func DownloadClient(row dbq.AcquisitionService) (downloader.Driver, error) { - d, err := downloader.For(row.Protocol, downloader.Config{ - BaseURL: row.BaseUrl, Username: row.Username, Password: row.Password, - APIKey: row.ApiKey, Category: row.Category, Timeout: msDuration(row.TimeoutMs), - }) - if err != nil { - return nil, err - } - return downloader.Mapped(d, downloader.PathMap{Local: row.LocalPath, Remote: row.RemotePath}), nil -} - -// DownloadClientFor builds the download client a grab went to, by the code -// of its acquisition_services row. -func DownloadClientFor(ctx context.Context, pool *pgxpool.Pool, code string) (downloader.Driver, error) { - row, err := dbq.New(pool).GetAcquisitionService(ctx, code) - if err != nil { - if errors.Is(err, pgx.ErrNoRows) { - return nil, fmt.Errorf("the download client %q is no longer set up", code) - } - return nil, err - } - return DownloadClient(row) -} - -// Sources builds every enabled search source. -func Sources(ctx context.Context, pool *pgxpool.Pool) ([]Source, error) { - rows, err := dbq.New(pool).ListUsableAcquisitionServices(ctx, JobSearch) - if err != nil { - return nil, err - } - out := make([]Source, len(rows)) - for i, r := range rows { - out[i] = SourceFor(r) - } - return out, nil -} - -func msDuration(ms int32) time.Duration { return time.Duration(ms) * time.Millisecond } diff --git a/internal/acquire/store.go b/internal/acquire/store.go deleted file mode 100644 index 0245be01..00000000 --- a/internal/acquire/store.go +++ /dev/null @@ -1,191 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "fmt" - "net/url" - "strings" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" -) - -// ErrNotFound is a code with no row. -var ErrNotFound = errors.New("no such service") - -// ErrTooMany is a twenty-first row of one protocol. -var ErrTooMany = errors.New("there are already twenty of these") - -// InvalidError is a setting an admin has to change, in words for the -// settings card. -type InvalidError struct { - Field string - Message string -} - -func (e *InvalidError) Error() string { return e.Message } - -func invalid(field, msg string) error { return &InvalidError{Field: field, Message: msg} } - -// maxPerProtocol bounds the codes tried for a new row. Nobody runs twenty -// Prowlarrs; the bound keeps a loop over a full table finite. -const maxPerProtocol = 20 - -// Store reads and writes acquisition_services. -type Store struct { - pool *pgxpool.Pool -} - -// NewStore returns a Store over pool. -func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} } - -// List returns every row without its secrets. -func (s *Store) List(ctx context.Context) ([]dbq.ListAcquisitionServicesRow, error) { - return dbq.New(s.pool).ListAcquisitionServices(ctx) -} - -// Get returns one row, secrets included: for building a client only. -func (s *Store) Get(ctx context.Context, code string) (dbq.AcquisitionService, error) { - row, err := dbq.New(s.pool).GetAcquisitionService(ctx, code) - if errors.Is(err, pgx.ErrNoRows) { - return row, ErrNotFound - } - return row, err -} - -// Create adds a row of protocol, switched off and with no address. Its code -// is the protocol for the first, then protocol-2, protocol-3. -func (s *Store) Create(ctx context.Context, protocol string) (dbq.AcquisitionService, error) { - a, ok := catalogue[protocol] - if !ok { - return dbq.AcquisitionService{}, invalid("protocol", "One of prowlarr, torznab, qbittorrent, exchange.") - } - q := dbq.New(s.pool) - for n := 1; n <= maxPerProtocol; n++ { - code, label := protocol, a.label - if n > 1 { - code, label = fmt.Sprintf("%s-%d", protocol, n), fmt.Sprintf("%s %d", a.label, n) - } - row, err := q.CreateAcquisitionService(ctx, dbq.CreateAcquisitionServiceParams{ - Code: code, Kind: a.kind, Protocol: protocol, Label: label, - Category: a.category, TimeoutMs: a.timeoutMs, SearchesPerHour: a.perHour, - }) - if errors.Is(err, pgx.ErrNoRows) { - continue - } - return row, err - } - return dbq.AcquisitionService{}, ErrTooMany -} - -// Update is everything on the settings form except the credentials. -type Update struct { - Label string - Enabled bool - BaseURL string - Username string - Category string - TimeoutMs int32 - ServesSearch bool - ServesDownloads bool - ServesEnrichment bool - LocalPath string - RemotePath string - SearchesPerHour int32 -} - -// Save validates u and writes it to code's row. -func (s *Store) Save(ctx context.Context, code string, u Update) (dbq.AcquisitionService, error) { - u.Label = strings.TrimSpace(u.Label) - u.BaseURL = strings.TrimSpace(u.BaseURL) - u.Username = strings.TrimSpace(u.Username) - u.Category = strings.TrimSpace(u.Category) - u.LocalPath = strings.TrimSpace(u.LocalPath) - u.RemotePath = strings.TrimSpace(u.RemotePath) - if err := u.validate(); err != nil { - return dbq.AcquisitionService{}, err - } - row, err := dbq.New(s.pool).UpdateAcquisitionService(ctx, dbq.UpdateAcquisitionServiceParams{ - Code: code, Label: u.Label, Enabled: u.Enabled, BaseUrl: u.BaseURL, - Username: u.Username, Category: u.Category, TimeoutMs: u.TimeoutMs, - ServesSearch: u.ServesSearch, ServesDownloads: u.ServesDownloads, - ServesEnrichment: u.ServesEnrichment, LocalPath: u.LocalPath, - RemotePath: u.RemotePath, SearchesPerHour: u.SearchesPerHour, - }) - if errors.Is(err, pgx.ErrNoRows) { - return row, ErrNotFound - } - return row, err -} - -// validate mirrors the table's CHECKs, so a bad value is named in the card's -// own terms before Postgres refuses it. -func (u Update) validate() error { - if u.Label == "" { - return invalid("label", "Name: give it a name.") - } - if u.Enabled && u.BaseURL == "" { - return invalid("base_url", "Address: give the address before switching this on.") - } - if u.BaseURL != "" { - parsed, err := url.Parse(u.BaseURL) - if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" { - return invalid("base_url", "Address: start with http:// or https://.") - } - } - if u.TimeoutMs < 1000 || u.TimeoutMs > 300000 { - return invalid("timeout_ms", "Give up after: between 1000 and 300000 milliseconds.") - } - if !strings.HasPrefix(u.LocalPath, "/") { - return invalid("local_path", "Downloads folder as Minstrel sees it: a full path, starting with /.") - } - if u.RemotePath != "" && !strings.HasPrefix(u.RemotePath, "/") { - return invalid("remote_path", "Downloads folder as the client sees it: a full path starting with /, or empty when it is the same path.") - } - if u.SearchesPerHour < 0 || u.SearchesPerHour > 3600 { - return invalid("searches_per_hour", "Searches per hour: between 0 and 3600. 0 means no limit.") - } - return nil -} - -// Delete removes code's row. -func (s *Store) Delete(ctx context.Context, code string) error { - n, err := dbq.New(s.pool).DeleteAcquisitionService(ctx, code) - if err != nil { - return err - } - if n == 0 { - return ErrNotFound - } - return nil -} - -// SetAPIKey stores a key, trimmed; empty clears it. -func (s *Store) SetAPIKey(ctx context.Context, code, key string) error { - n, err := dbq.New(s.pool).SetAcquisitionServiceAPIKey(ctx, dbq.SetAcquisitionServiceAPIKeyParams{ - Code: code, ApiKey: strings.TrimSpace(key), - }) - return affected(n, err) -} - -// SetPassword stores a password as typed (spaces are part of a password); -// empty clears it. -func (s *Store) SetPassword(ctx context.Context, code, password string) error { - n, err := dbq.New(s.pool).SetAcquisitionServicePassword(ctx, dbq.SetAcquisitionServicePasswordParams{ - Code: code, Password: password, - }) - return affected(n, err) -} - -func affected(n int64, err error) error { - if err != nil { - return err - } - if n == 0 { - return ErrNotFound - } - return nil -} diff --git a/internal/acquire/store_test.go b/internal/acquire/store_test.go deleted file mode 100644 index 37c369da..00000000 --- a/internal/acquire/store_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "io" - "log/slog" - "os" - "testing" - - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" -) - -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - -func TestStore_AddsConfiguresAndRemoves_Integration(t *testing.T) { - ctx := context.Background() - s := NewStore(newPool(t)) - - first, err := s.Create(ctx, ProtocolExchange) - if err != nil { - t.Fatalf("create: %v", err) - } - second, err := s.Create(ctx, ProtocolExchange) - if err != nil { - t.Fatalf("create a second: %v", err) - } - if first.Code != "exchange" || second.Code != "exchange-2" || second.Label != "FabledExchange 2" { - t.Errorf("codes = %q, %q (%q); want exchange, exchange-2", first.Code, second.Code, second.Label) - } - // A new exchange is off, does every job, files under minstrel and is - // unpaced. - if first.Enabled || first.Kind != KindDownload || !first.ServesSearch || !first.ServesDownloads || - !first.ServesEnrichment || first.Category != DefaultCategory || first.SearchesPerHour != 0 || first.LocalPath != "/downloads" { - t.Errorf("a new exchange = %+v", first) - } - if _, err := s.Create(ctx, "transmission"); !errors.As(err, new(*InvalidError)) { - t.Errorf("an unknown protocol: err = %v", err) - } - - u := Update{ - Label: "Exchange", Enabled: true, BaseURL: "http://exchange:8080", Category: "minstrel", - TimeoutMs: 20000, ServesSearch: true, LocalPath: "/downloads", RemotePath: "/data/torrents", - } - saved, err := s.Save(ctx, first.Code, u) - if err != nil { - t.Fatalf("save: %v", err) - } - if !saved.Enabled || saved.ServesDownloads || saved.RemotePath != "/data/torrents" { - t.Errorf("saved = %+v", saved) - } - if _, err := s.Save(ctx, "nope", u); !errors.Is(err, ErrNotFound) { - t.Errorf("saving a missing row: err = %v", err) - } - - // Secrets are write-only: the list says whether one is set, never what. - if err := s.SetAPIKey(ctx, first.Code, " key "); err != nil { - t.Fatalf("set key: %v", err) - } - full, err := s.Get(ctx, first.Code) - if err != nil || full.ApiKey != "key" { - t.Errorf("stored key = %q (err %v), want it trimmed", full.ApiKey, err) - } - rows, err := s.List(ctx) - if err != nil || len(rows) != 2 { - t.Fatalf("list: %d rows, err %v", len(rows), err) - } - for _, r := range rows { - if r.Code == first.Code && !r.HasApiKey { - t.Error("the list should say a key is set") - } - } - - // Only the exchange with search switched on is a search source. - srcs, err := Sources(ctx, s.pool) - if err != nil || len(srcs) != 1 || srcs[0].Code != first.Code { - t.Errorf("sources = %+v, err %v; want only the enabled exchange", srcs, err) - } - - if err := s.Delete(ctx, second.Code); err != nil { - t.Fatalf("delete: %v", err) - } - if err := s.Delete(ctx, second.Code); !errors.Is(err, ErrNotFound) { - t.Errorf("deleting twice: err = %v", err) - } -} diff --git a/internal/acquire/test.go b/internal/acquire/test.go deleted file mode 100644 index 9ec6d07b..00000000 --- a/internal/acquire/test.go +++ /dev/null @@ -1,134 +0,0 @@ -package acquire - -import ( - "context" - "errors" - "fmt" - "os" - "strings" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/exchange" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -// TestResult is what the settings card says after Test. -type TestResult struct { - OK bool `json:"ok"` - Detail string `json:"detail"` -} - -// testQuery is a search every music indexer should answer. -const testQuery = "Radiohead" - -// Test reaches the service a row describes, through the same builders real -// traffic uses. It runs whether or not the row is switched on: paste the -// address, test it, then switch it on. -func Test(ctx context.Context, row dbq.AcquisitionService) TestResult { - if strings.TrimSpace(row.BaseUrl) == "" { - return TestResult{Detail: "No address is set, so there is nothing to reach yet."} - } - if row.Protocol == ProtocolExchange { - return testExchange(ctx, row) - } - if row.Kind == KindSearch { - return testSearch(ctx, row) - } - return testDownload(ctx, row) -} - -// testExchange runs each job the row has switched on and reports them all. -func testExchange(ctx context.Context, row dbq.AcquisitionService) TestResult { - var parts []string - ok := true - run := func(name string, on bool, test func() TestResult) { - if !on { - return - } - r := test() - ok = ok && r.OK - parts = append(parts, name+": "+r.Detail) - } - run("Downloads", row.ServesDownloads, func() TestResult { return testDownload(ctx, row) }) - run("Search", row.ServesSearch, func() TestResult { return testSearch(ctx, row) }) - run("Release details", row.ServesEnrichment, func() TestResult { return testEnrichment(ctx, row) }) - if len(parts) == 0 { - return TestResult{Detail: "Every job of this FabledExchange is switched off, so there is nothing to test."} - } - return TestResult{OK: ok, Detail: strings.Join(parts, " ")} -} - -// testSearch runs a real search. -func testSearch(ctx context.Context, row dbq.AcquisitionService) TestResult { - src := SourceFor(row) - results, err := src.Search.Search(ctx, indexer.Query{Text: testQuery, Categories: indexer.MusicCategories}) - switch { - case errors.Is(err, indexer.ErrUnconfigured): - return TestResult{Detail: "Add this service's address, and the API key it shows on its own settings page."} - case errors.Is(err, indexer.ErrAuth): - return TestResult{Detail: indexer.FirstLine(err.Error()) + ". Check it on the service's own settings page."} - case err != nil: - return TestResult{Detail: indexer.FirstLine(err.Error())} - case len(results) == 0: - return TestResult{OK: true, Detail: "Connected, but a test search for music found nothing. Check that it has an indexer with music categories."} - } - return TestResult{OK: true, Detail: fmt.Sprintf("Connected. %d results for a test search.", len(results))} -} - -// testDownload lists the client's torrents, which proves the session and not -// only the login, then checks the downloads folder from Minstrel's side. -func testDownload(ctx context.Context, row dbq.AcquisitionService) TestResult { - c, err := DownloadClient(row) - if err != nil { - return TestResult{Detail: err.Error()} - } - ts, err := c.Torrents(ctx) - if err != nil { - return TestResult{Detail: indexer.FirstLine(err.Error())} - } - detail := fmt.Sprintf("Connected. %d torrents.", len(ts)) - if row.Category != "" { - detail = fmt.Sprintf("Connected. %d torrents in the %q category.", len(ts), row.Category) - } - if up, err := c.Connected(ctx); err == nil && !up { - detail += " The client reports it is not connected to any peers, so downloads will stall." - } - if problem := landingProblem(row.LocalPath); problem != "" { - return TestResult{Detail: detail + " " + problem} - } - return TestResult{OK: true, Detail: detail} -} - -// landingProblem checks Minstrel can see and write the downloads folder: it -// moves finished downloads out of it. Only the local path can be checked; -// the client's own name for it cannot be seen from here. -func landingProblem(dir string) string { - info, err := os.Stat(dir) - switch { - case err != nil: - return fmt.Sprintf("But Minstrel cannot see its downloads folder at %s. Mount the download client's downloads folder there, or change where Minstrel looks for it.", dir) - case !info.IsDir(): - return fmt.Sprintf("But %s is a file, not the downloads folder.", dir) - } - probe, err := os.CreateTemp(dir, ".minstrel-probe-*") - if err != nil { - return fmt.Sprintf("But Minstrel cannot write to %s, so it could not move a finished download out of it. Check the mount is not read-only and Minstrel's user can write there.", dir) - } - name := probe.Name() - _ = probe.Close() - _ = os.Remove(name) - return "" -} - -// testEnrichment asks about a hash no torrent has. A JSON "not crawled" is a -// healthy answer; a 404 from something that is not Exchange is not. -func testEnrichment(ctx context.Context, row dbq.AcquisitionService) TestResult { - _, err := ExchangeFor(row).Torrent(ctx, strings.Repeat("0", 40)) - switch { - case err == nil, errors.Is(err, exchange.ErrUnknown): - return TestResult{OK: true, Detail: "Connected. The index answered."} - case errors.Is(err, exchange.ErrUnconfigured): - return TestResult{Detail: "No address is set, so there is nothing to reach yet."} - } - return TestResult{Detail: indexer.FirstLine(err.Error())} -} diff --git a/internal/api/access_test.go b/internal/api/access_test.go new file mode 100644 index 00000000..d8b6dbb1 --- /dev/null +++ b/internal/api/access_test.go @@ -0,0 +1,232 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/config" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/eventbus" + "github.com/Fabled-Sword/minstrel/internal/playevents" +) + +// publicRoutes are the API routes a request without a session may reach. +// Every other route answers 401 to it. The stream routes take a session or +// a signed token and check it themselves. +var publicRoutes = map[string]bool{ + "POST /api/auth/login": true, + "POST /api/auth/register": true, + "GET /api/auth/setup-status": true, + "POST /api/auth/restore": true, + "POST /api/auth/forgot-password": true, + "POST /api/auth/reset-password": true, + "GET /api/tracks/{id}/stream": true, + "GET /api/tracks/{id}/stream.{ext}": true, + "GET /api/tracks/{id}/leveled.flac": true, +} + +// mountedAPI is the production router: every route Mount registers, behind +// the middleware it registers them with. +func mountedAPI(t *testing.T) (chi.Router, *handlers) { + t.Helper() + h, _ := testHandlers(t) + r := chi.NewRouter() + w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), + 30*time.Minute, 0.5, 30000) + Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil) + return r, h +} + +// mountedRoute is one registered method and pattern, with a request path +// that fills each {param} in. +type mountedRoute struct{ method, pattern, path string } + +func mountedRoutes(t *testing.T, r chi.Router) []mountedRoute { + t.Helper() + var out []mountedRoute + err := chi.Walk(r, func(method, pattern string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { + path := pattern + for strings.Contains(path, "{") { + open := strings.Index(path, "{") + end := strings.Index(path[open:], "}") + path = path[:open] + "00000000-0000-0000-0000-000000000001" + path[open+end+1:] + } + out = append(out, mountedRoute{method, pattern, strings.TrimSuffix(path, "/*")}) + return nil + }) + if err != nil { + t.Fatalf("walk routes: %v", err) + } + if len(out) < 50 { + t.Fatalf("walked %d routes; Mount registers far more, so the walk is not seeing them", len(out)) + } + return out +} + +// sessionCookie signs user in the way the web app does. +func sessionCookie(t *testing.T, pool *pgxpool.Pool, user dbq.User) *http.Cookie { + t.Helper() + token, err := auth.MintSessionToken() + if err != nil { + t.Fatalf("mint session: %v", err) + } + if _, err := dbq.New(pool).InsertSession(context.Background(), dbq.InsertSessionParams{ + UserID: user.ID, TokenHash: auth.HashSessionToken(token), UserAgent: "test-agent", Ip: "192.0.2.1", + }); err != nil { + t.Fatalf("insert session: %v", err) + } + return &http.Cookie{Name: auth.SessionCookieName, Value: token} +} + +// reachedHandler stands for a request that got past the access checks into a +// handler, which then panicked on the walk's bare wiring. +const reachedHandler = -1 + +// serveGuarded serves one request and returns its status, or reachedHandler +// when a handler panicked. Without the recover, one route mounted outside its +// group would take down the whole test binary and hide every other failure. +func serveGuarded(r http.Handler, req *http.Request) (code int) { + defer func() { + if recover() != nil { + code = reachedHandler + } + }() + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w.Code +} + +func describeCode(code int) string { + if code == reachedHandler { + return "from inside its handler (it ran, and panicked)" + } + return strconv.Itoa(code) +} + +// Every API route but the public ones answers 401 without a session, and +// every admin route answers 403 to a signed-in user who is not an admin. +// The routes come from the production router, so a route registered outside +// its group fails here. +func TestMountedRoutes_RequireASessionAndAdminRoutesAnAdmin(t *testing.T) { + r, h := mountedAPI(t) + listener := seedUser(t, h.pool, "listener", "pw", false) + cookie := sessionCookie(t, h.pool, listener) + + var admin int + public := map[string]bool{} + for _, rt := range mountedRoutes(t, r) { + key := rt.method + " " + rt.pattern + if publicRoutes[key] { + public[key] = true + continue + } + if code := serveGuarded(r, httptest.NewRequest(rt.method, rt.path, nil)); code != http.StatusUnauthorized { + t.Errorf("%s answered %s without a session, want 401", key, describeCode(code)) + } + if !strings.HasPrefix(rt.pattern, "/api/admin/") { + continue + } + admin++ + req := httptest.NewRequest(rt.method, rt.path, nil) + req.AddCookie(cookie) + if code := serveGuarded(r, req); code != http.StatusForbidden { + t.Errorf("%s answered %s to a non-admin, want 403", key, describeCode(code)) + } + } + if admin < 50 { + t.Errorf("only %d admin routes walked; the admin group is not being reached", admin) + } + for key := range publicRoutes { + if !public[key] { + t.Errorf("public route %s is not registered", key) + } + } +} + +// An id that is not a UUID answers 400, and one that names nothing answers +// 404, on every route that looks a record up by id. The error message names +// what was not found where the clients show it. +func TestMountedRoutes_AMalformedIDIs400AndAnUnknownOneIs404(t *testing.T) { + r, h := mountedAPI(t) + listener := seedUser(t, h.pool, "listener", "pw", false) + cookie := sessionCookie(t, h.pool, listener) + const unknown = "00000000-0000-0000-0000-000000000099" + + for _, tc := range []struct { + method, path string // path holds %s where the id goes + wantMessage string // on the 404, when the clients show it + }{ + {http.MethodGet, "/api/tracks/%s", ""}, + {http.MethodGet, "/api/albums/%s", ""}, + {http.MethodGet, "/api/artists/%s", ""}, + {http.MethodGet, "/api/artists/%s/tracks", ""}, + {http.MethodGet, "/api/albums/%s/cover", "album not found"}, + {http.MethodGet, "/api/tracks/%s/stream", "track not found"}, + {http.MethodGet, "/api/playlists/%s", ""}, + {http.MethodPost, "/api/likes/tracks/%s", ""}, + {http.MethodGet, "/api/radio?seed_track=%s", ""}, + } { + for _, id := range []string{"not-a-uuid", unknown} { + req := httptest.NewRequest(tc.method, fmt.Sprintf(tc.path, id), nil) + req.AddCookie(cookie) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + want := http.StatusBadRequest + if id == unknown { + want = http.StatusNotFound + } + if w.Code != want { + t.Errorf("%s %s answered %d, want %d", tc.method, fmt.Sprintf(tc.path, id), w.Code, want) + continue + } + if id == unknown && tc.wantMessage != "" { + var body apierror.Body + _ = json.Unmarshal(w.Body.Bytes(), &body) + if body.Error.Message != tc.wantMessage { + t.Errorf("%s %s message = %q, want %q", tc.method, tc.path, body.Error.Message, tc.wantMessage) + } + } + } + } +} + +// The routes the web app and the phone call are registered: a missing one +// answers 404 rather than reaching the session check. +func TestMountedRoutes_TheClientsRoutesAreRegistered(t *testing.T) { + r, _ := mountedAPI(t) + for _, p := range []string{ + "/api/artists", + "/api/artists/00000000-0000-0000-0000-000000000001", + "/api/albums/00000000-0000-0000-0000-000000000001", + "/api/albums/00000000-0000-0000-0000-000000000001/cover", + "/api/tracks/00000000-0000-0000-0000-000000000001", + "/api/search?q=x", + "/api/library/genres", + "/api/library/years", + "/api/admin/library/missing", + "/api/admin/library/fingerprints", + "/api/admin/library/fingerprint-settings", + "/api/admin/library/duplicates", + } { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, p, nil)) + if w.Code != http.StatusUnauthorized { + t.Errorf("GET %s answered %d, want 401 (404 means the route is not registered)", p, w.Code) + } + } +} diff --git a/internal/api/admin_acoustid.go b/internal/api/admin_acoustid.go index 69c88f17..0628a7c3 100644 --- a/internal/api/admin_acoustid.go +++ b/internal/api/admin_acoustid.go @@ -6,9 +6,9 @@ import ( "net/http" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // AcoustID recording-id lookup, admin side. diff --git a/internal/api/admin_acquisition.go b/internal/api/admin_acquisition.go deleted file mode 100644 index f6144e61..00000000 --- a/internal/api/admin_acquisition.go +++ /dev/null @@ -1,210 +0,0 @@ -package api - -import ( - "encoding/json" - "errors" - "io" - "net/http" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" -) - -// Indexers and download clients, admin side. Rows an admin -// adds and configures; nothing is seeded. Secrets are write-only: no response -// carries one, only whether it is set. - -// acquisitionBodyLimit caps a settings body. The largest is a full form of -// short strings. -const acquisitionBodyLimit = 64 << 10 - -type acquisitionServiceResp struct { - Code string `json:"code"` - Kind string `json:"kind"` - Protocol string `json:"protocol"` - Label string `json:"label"` - Enabled bool `json:"enabled"` - BaseURL string `json:"base_url"` - HasAPIKey bool `json:"has_api_key"` - HasPassword bool `json:"has_password"` - Username string `json:"username"` - Category string `json:"category"` - TimeoutMs int32 `json:"timeout_ms"` - ServesSearch bool `json:"serves_search"` - ServesDownloads bool `json:"serves_downloads"` - ServesEnrichment bool `json:"serves_enrichment"` - LocalPath string `json:"local_path"` - RemotePath string `json:"remote_path"` - SearchesPerHour int32 `json:"searches_per_hour"` - // Usable is switched on and addressed: the state the jobs read. - Usable bool `json:"usable"` -} - -func acquisitionRespOf(r dbq.AcquisitionService) acquisitionServiceResp { - return acquisitionServiceResp{ - Code: r.Code, Kind: r.Kind, Protocol: r.Protocol, Label: r.Label, - Enabled: r.Enabled, BaseURL: r.BaseUrl, - HasAPIKey: r.ApiKey != "", HasPassword: r.Password != "", - Username: r.Username, Category: r.Category, TimeoutMs: r.TimeoutMs, - ServesSearch: r.ServesSearch, ServesDownloads: r.ServesDownloads, - ServesEnrichment: r.ServesEnrichment, - LocalPath: r.LocalPath, RemotePath: r.RemotePath, - SearchesPerHour: r.SearchesPerHour, - Usable: r.Enabled && r.BaseUrl != "", - } -} - -// handleListAcquisitionServices implements GET /api/admin/acquisition/services. -func (h *handlers) handleListAcquisitionServices(w http.ResponseWriter, r *http.Request) { - rows, err := h.acquisition.List(r.Context()) - if err != nil { - writeErrWithLog(w, h.logger, "admin: list acquisition services", apierror.Internal(err)) - return - } - out := make([]acquisitionServiceResp, len(rows)) - for i, row := range rows { - out[i] = acquisitionRespOf(dbq.AcquisitionService{ - Code: row.Code, Kind: row.Kind, Protocol: row.Protocol, Label: row.Label, - Enabled: row.Enabled, BaseUrl: row.BaseUrl, Username: row.Username, - Category: row.Category, TimeoutMs: row.TimeoutMs, - ServesSearch: row.ServesSearch, ServesDownloads: row.ServesDownloads, - ServesEnrichment: row.ServesEnrichment, LocalPath: row.LocalPath, - RemotePath: row.RemotePath, SearchesPerHour: row.SearchesPerHour, - }) - out[i].HasAPIKey, out[i].HasPassword = row.HasApiKey, row.HasPassword - } - writeJSON(w, http.StatusOK, map[string]any{"services": out}) -} - -// handleCreateAcquisitionService implements POST -// /api/admin/acquisition/services with {"protocol": -// "prowlarr"|"torznab"|"qbittorrent"|"exchange"}. The row starts switched off, -// with no address. -func (h *handlers) handleCreateAcquisitionService(w http.ResponseWriter, r *http.Request) { - var body struct { - Protocol string `json:"protocol"` - } - if !decodeAcquisitionBody(w, r, &body) { - return - } - row, err := h.acquisition.Create(r.Context(), body.Protocol) - if err != nil { - h.writeAcquisitionErr(w, "admin: create acquisition service", err) - return - } - writeJSON(w, http.StatusCreated, acquisitionRespOf(row)) -} - -type updateAcquisitionBody struct { - Label string `json:"label"` - Enabled bool `json:"enabled"` - BaseURL string `json:"base_url"` - Username string `json:"username"` - Category string `json:"category"` - TimeoutMs int32 `json:"timeout_ms"` - ServesSearch bool `json:"serves_search"` - ServesDownloads bool `json:"serves_downloads"` - ServesEnrichment bool `json:"serves_enrichment"` - LocalPath string `json:"local_path"` - RemotePath string `json:"remote_path"` - SearchesPerHour int32 `json:"searches_per_hour"` -} - -// handleUpdateAcquisitionService implements PUT -// /api/admin/acquisition/services/{code}: the whole form except credentials. -func (h *handlers) handleUpdateAcquisitionService(w http.ResponseWriter, r *http.Request) { - var body updateAcquisitionBody - if !decodeAcquisitionBody(w, r, &body) { - return - } - row, err := h.acquisition.Save(r.Context(), chi.URLParam(r, "code"), acquire.Update(body)) - if err != nil { - h.writeAcquisitionErr(w, "admin: update acquisition service", err) - return - } - writeJSON(w, http.StatusOK, acquisitionRespOf(row)) -} - -// handleDeleteAcquisitionService implements DELETE -// /api/admin/acquisition/services/{code}. -func (h *handlers) handleDeleteAcquisitionService(w http.ResponseWriter, r *http.Request) { - if err := h.acquisition.Delete(r.Context(), chi.URLParam(r, "code")); err != nil { - h.writeAcquisitionErr(w, "admin: delete acquisition service", err) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// handleTestAcquisitionService implements POST -// /api/admin/acquisition/services/{code}/test. POST because it reaches -// another machine, which a prefetch must not trigger. Always 200 with -// {ok, detail}: a failed connection is the answer, not an error. -func (h *handlers) handleTestAcquisitionService(w http.ResponseWriter, r *http.Request) { - row, err := h.acquisition.Get(r.Context(), chi.URLParam(r, "code")) - if err != nil { - h.writeAcquisitionErr(w, "admin: test acquisition service", err) - return - } - writeJSON(w, http.StatusOK, acquire.Test(r.Context(), row)) -} - -// handleSetAcquisitionSecret implements PUT and DELETE on -// /api/admin/acquisition/services/{code}/api-key and .../password. PUT takes -// {"value": "..."}; DELETE clears it. 204 with no body either way: echoing -// anything here is how a secret ends up in a response. -func (h *handlers) handleSetAcquisitionSecret(field string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - value := "" - if r.Method == http.MethodPut { - var body struct { - Value string `json:"value"` - } - if !decodeAcquisitionBody(w, r, &body) { - return - } - if body.Value == "" { - writeErr(w, apierror.BadRequest("invalid_setting", "Paste a value, or use Remove to clear the one that is set.")) - return - } - value = body.Value - } - code := chi.URLParam(r, "code") - var err error - if field == "password" { - err = h.acquisition.SetPassword(r.Context(), code, value) - } else { - err = h.acquisition.SetAPIKey(r.Context(), code, value) - } - if err != nil { - h.writeAcquisitionErr(w, "admin: set acquisition "+field, err) - return - } - w.WriteHeader(http.StatusNoContent) - } -} - -func decodeAcquisitionBody(w http.ResponseWriter, r *http.Request, into any) bool { - err := json.NewDecoder(http.MaxBytesReader(w, r.Body, acquisitionBodyLimit)).Decode(into) - if err != nil && !errors.Is(err, io.EOF) { - writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON")) - return false - } - return true -} - -func (h *handlers) writeAcquisitionErr(w http.ResponseWriter, msg string, err error) { - var invalid *acquire.InvalidError - switch { - case errors.As(err, &invalid): - writeErr(w, apierror.BadRequest("invalid_setting", invalid.Message)) - case errors.Is(err, acquire.ErrNotFound): - writeErr(w, apierror.NotFound("service")) - case errors.Is(err, acquire.ErrTooMany): - writeErr(w, apierror.Conflict("too_many_services", "There are already twenty of these. Remove one you no longer use first.")) - default: - writeErrWithLog(w, h.logger, msg, apierror.Internal(err)) - } -} diff --git a/internal/api/admin_backups.go b/internal/api/admin_backups.go new file mode 100644 index 00000000..21cd906d --- /dev/null +++ b/internal/api/admin_backups.go @@ -0,0 +1,94 @@ +package api + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/backup" +) + +// GET /api/admin/backups — the backup's verdict, settings and recent runs. +func (h *handlers) handleGetBackups(w http.ResponseWriter, r *http.Request) { + st, err := h.backups.Status(r.Context()) + if err != nil { + writeErrWithLog(w, h.logger, "admin backups: status", apierror.Internal(err)) + return + } + writeJSON(w, http.StatusOK, st) +} + +func decodeBackupUpdate(w http.ResponseWriter, r *http.Request) (backup.Update, bool) { + var u backup.Update + if err := json.NewDecoder(r.Body).Decode(&u); err != nil { + writeErr(w, apierror.BadRequest("invalid_body", "")) + return u, false + } + return u, true +} + +// fieldErr writes a setting that can't be kept as a 400 whose message says +// which setting and why, and reports whether err was one. +func fieldErr(w http.ResponseWriter, err error) bool { + var fe *backup.FieldError + if !errors.As(err, &fe) { + return false + } + writeErr(w, apierror.BadRequest("invalid_backup_setting", fe.Message)) + return true +} + +// PUT /api/admin/backups — save the settings. An empty secret_key keeps the +// stored one. Returns the new status. +func (h *handlers) handleUpdateBackups(w http.ResponseWriter, r *http.Request) { + u, ok := decodeBackupUpdate(w, r) + if !ok { + return + } + if err := h.backups.Save(r.Context(), u); err != nil { + if !fieldErr(w, err) { + writeErrWithLog(w, h.logger, "admin backups: save", apierror.Internal(err)) + } + return + } + h.handleGetBackups(w, r) +} + +// POST /api/admin/backups/test — check the destination in the body without +// saving it, by listing the backups already there. Nothing is written. +func (h *handlers) handleTestBackups(w http.ResponseWriter, r *http.Request) { + u, ok := decodeBackupUpdate(w, r) + if !ok { + return + } + res, err := h.backups.Test(r.Context(), u) + if err != nil { + if fieldErr(w, err) { + return + } + msg := strings.TrimPrefix(err.Error(), "backup: ") + writeErr(w, &apierror.Error{Status: http.StatusBadGateway, Code: "destination_failed", Message: msg}) + return + } + writeJSON(w, http.StatusOK, res) +} + +// POST /api/admin/backups/run — start a backup now. 202 once it has started; +// 409 while one runs or before the destination is set up. +func (h *handlers) handleRunBackup(w http.ResponseWriter, r *http.Request) { + err := h.backups.Start(r.Context(), backup.TriggerManual) + switch { + case err == nil: + w.WriteHeader(http.StatusAccepted) + case errors.Is(err, backup.ErrRunning): + writeErr(w, apierror.Conflict("backup_running", "A backup is already running.")) + case errors.Is(err, backup.ErrNotReady): + writeErr(w, apierror.Conflict("backup_not_ready", "Set up where backups go first.")) + case errors.Is(err, backup.ErrClosed): + writeErr(w, apierror.Conflict("shutting_down", "The server is shutting down.")) + default: + writeErrWithLog(w, h.logger, "admin backups: start", apierror.Internal(err)) + } +} diff --git a/internal/api/admin_cover_sources.go b/internal/api/admin_cover_sources.go index 924eca90..a8183b0f 100644 --- a/internal/api/admin_cover_sources.go +++ b/internal/api/admin_cover_sources.go @@ -1,159 +1,23 @@ package api import ( - "encoding/json" - "errors" "net/http" - "time" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" ) -// coverProviderResp is the wire shape for one provider in the -// GET /api/admin/cover-sources list. Mirrors coverart.ProviderInfo -// but uses snake_case JSON tags. -type coverProviderResp struct { - ID string `json:"id"` - DisplayName string `json:"display_name"` - RequiresAPIKey bool `json:"requires_api_key"` - Supports []string `json:"supports"` - Enabled bool `json:"enabled"` - APIKeySet bool `json:"api_key_set"` - DisplayOrder int32 `json:"display_order"` - Testable bool `json:"testable"` -} - -type coverProvidersListResp struct { - Providers []coverProviderResp `json:"providers"` - SourcesVersion int32 `json:"sources_version"` -} +// The cover-sources admin card: the shared provider-source handlers +// (admin_provider_sources.go) over the cover settings. // handleListCoverSources implements GET /api/admin/cover-sources. func (h *handlers) handleListCoverSources(w http.ResponseWriter, _ *http.Request) { - infos := h.coverSettings.ListProviderInfo() - out := coverProvidersListResp{ - Providers: make([]coverProviderResp, 0, len(infos)), - SourcesVersion: h.coverSettings.CurrentVersion(), - } - for _, info := range infos { - supports := info.Supports - if supports == nil { - supports = []string{} - } - out.Providers = append(out.Providers, coverProviderResp{ - ID: info.ID, - DisplayName: info.DisplayName, - RequiresAPIKey: info.RequiresAPIKey, - Supports: supports, - Enabled: info.Enabled, - APIKeySet: info.APIKeySet, - DisplayOrder: info.DisplayOrder, - Testable: info.Testable, - }) - } - writeJSON(w, http.StatusOK, out) + listProviderSources(w, h.coverSettings.Service) } -// updateCoverSourceReq is the PATCH body. nil pointers mean -// "leave unchanged"; non-nil means "set to this value (which may be -// empty string for api_key clearing)". -type updateCoverSourceReq struct { - Enabled *bool `json:"enabled,omitempty"` - APIKey *string `json:"api_key,omitempty"` -} - -type updateCoverSourceResp struct { - coverProviderResp - VersionBumped bool `json:"version_bumped"` -} - -// handleUpdateCoverSource implements PATCH -// /api/admin/cover-sources/{provider_id}. +// handleUpdateCoverSource implements PATCH /api/admin/cover-sources/{provider_id}. func (h *handlers) handleUpdateCoverSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - var body updateCoverSourceReq - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - writeErr(w, apierror.BadRequest("bad_body", "invalid JSON")) - return - } - - bumped, err := h.coverSettings.UpdateProvider(r.Context(), id, coverart.ProviderUpdatePatch{ - Enabled: body.Enabled, - APIKey: body.APIKey, - }) - if err != nil { - if errors.Is(err, coverart.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - h.logger.Error("admin: update cover source", "id", id, "err", err) - writeErr(w, apierror.InternalMsg("update failed", err)) - return - } - - // Re-fetch the provider info to return. - infos := h.coverSettings.ListProviderInfo() - var found coverProviderResp - for _, info := range infos { - if info.ID == id { - supports := info.Supports - if supports == nil { - supports = []string{} - } - found = coverProviderResp{ - ID: info.ID, - DisplayName: info.DisplayName, - RequiresAPIKey: info.RequiresAPIKey, - Supports: supports, - Enabled: info.Enabled, - APIKeySet: info.APIKeySet, - DisplayOrder: info.DisplayOrder, - Testable: info.Testable, - } - break - } - } - writeJSON(w, http.StatusOK, updateCoverSourceResp{ - coverProviderResp: found, - VersionBumped: bumped, - }) + h.updateProviderSource(w, r, h.coverSettings.Service) } -type testCoverSourceResp struct { - OK bool `json:"ok"` - DurationMs int64 `json:"duration_ms,omitempty"` - Error string `json:"error,omitempty"` -} - -// handleTestCoverSource implements POST -// /api/admin/cover-sources/{provider_id}/test. +// handleTestCoverSource implements POST /api/admin/cover-sources/{provider_id}/test. func (h *handlers) handleTestCoverSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - start := time.Now() - err := h.coverSettings.TestProvider(r.Context(), id) - duration := time.Since(start).Milliseconds() - - if err == nil { - writeJSON(w, http.StatusOK, testCoverSourceResp{OK: true, DurationMs: duration}) - return - } - - if errors.Is(err, coverart.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - - // Not testable, or test failed — both surface as ok=false. - // 200 status because the operation completed; the test result is - // data, not an error. - writeJSON(w, http.StatusOK, testCoverSourceResp{ - OK: false, - DurationMs: duration, - Error: err.Error(), - }) + testProviderSource(w, r, h.coverSettings.Service) } diff --git a/internal/api/admin_cover_sources_test.go b/internal/api/admin_cover_sources_test.go index 0da0d4f9..70d7d2ec 100644 --- a/internal/api/admin_cover_sources_test.go +++ b/internal/api/admin_cover_sources_test.go @@ -6,13 +6,12 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/coverart" ) // apiTestAlbumProvider is a minimal AlbumCoverProvider for use in api @@ -31,14 +30,6 @@ func (p *apiTestAlbumProvider) FetchAlbumCover(_ context.Context, _ coverart.Alb return []byte("img"), nil } -// apiTestTestableProvider is an AlbumCoverProvider that also implements -// TestableProvider (so the test connection button exercises the success path). -type apiTestTestableProvider struct { - apiTestAlbumProvider -} - -func (p *apiTestTestableProvider) TestConnection(_ context.Context) error { return nil } - func newAdminCoverSourcesRouter(h *handlers) chi.Router { r := chi.NewRouter() r.Route("/api/admin", func(admin chi.Router) { @@ -67,9 +58,6 @@ func testHandlersWithCoverSettings(t *testing.T) (*handlers, *coverart.SettingsS } func TestAdminListCoverSources_ReturnsRegisteredProviders(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -86,7 +74,7 @@ func TestAdminListCoverSources_ReturnsRegisteredProviders(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp coverProvidersListResp + var resp providerSourcesListResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -120,9 +108,6 @@ func TestAdminListCoverSources_ReturnsRegisteredProviders(t *testing.T) { } func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -132,7 +117,7 @@ func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { admin := seedUser(t, h.pool, "csflip", "pw", true) disabled := false - body, _ := json.Marshal(updateCoverSourceReq{Enabled: &disabled}) + body, _ := json.Marshal(updateProviderSourceReq{Enabled: &disabled}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/cover-sources/flip-prov", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -142,7 +127,7 @@ func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp updateCoverSourceResp + var resp updateProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -151,10 +136,7 @@ func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { } } -func TestAdminUpdateCoverSource_KeyOnlyDoesNotBump(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } +func TestAdminUpdateCoverSource_ReplacingAKeyDoesNotBump(t *testing.T) { coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -163,33 +145,36 @@ func TestAdminUpdateCoverSource_KeyOnlyDoesNotBump(t *testing.T) { h, _ := testHandlersWithCoverSettings(t) admin := seedUser(t, h.pool, "cskey", "pw", true) - newKey := "newkey" - body, _ := json.Marshal(updateCoverSourceReq{APIKey: &newKey}) - req := httptest.NewRequest(http.MethodPatch, "/api/admin/cover-sources/key-prov", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - req = withUser(req, admin) - rec := httptest.NewRecorder() - newAdminCoverSourcesRouter(h).ServeHTTP(rec, req) + // The first key on an enabled source moves the version (it searched + // without one until now); replacing that key with another doesn't. + for i, step := range []struct { + key string + wantBumped bool + }{{"firstkey", true}, {"newkey", false}} { + body, _ := json.Marshal(updateProviderSourceReq{APIKey: &step.key}) + req := httptest.NewRequest(http.MethodPatch, "/api/admin/cover-sources/key-prov", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req = withUser(req, admin) + rec := httptest.NewRecorder() + newAdminCoverSourcesRouter(h).ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - var resp updateCoverSourceResp - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.VersionBumped { - t.Error("version_bumped = true, want false for key-only change") - } - if !resp.APIKeySet { - t.Error("api_key_set = false, want true after setting key") + if rec.Code != http.StatusOK { + t.Fatalf("step %d: status = %d, want 200; body=%s", i, rec.Code, rec.Body.String()) + } + var resp updateProviderSourceResp + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if resp.VersionBumped != step.wantBumped { + t.Errorf("key %q: version_bumped = %v, want %v", step.key, resp.VersionBumped, step.wantBumped) + } + if !resp.APIKeySet { + t.Error("api_key_set = false, want true after setting key") + } } } func TestAdminUpdateCoverSource_UnknownProvider404(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -197,7 +182,7 @@ func TestAdminUpdateCoverSource_UnknownProvider404(t *testing.T) { h, _ := testHandlersWithCoverSettings(t) admin := seedUser(t, h.pool, "cs404", "pw", true) - body, _ := json.Marshal(updateCoverSourceReq{}) + body, _ := json.Marshal(updateProviderSourceReq{}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/cover-sources/missing", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -209,32 +194,7 @@ func TestAdminUpdateCoverSource_UnknownProvider404(t *testing.T) { } } -func TestAdminTestCoverSource_NonAdminReturns403(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - coverart.ResetRegistryForTests() - t.Cleanup(coverart.ResetRegistryForTests) - - coverart.Register(&apiTestTestableProvider{apiTestAlbumProvider{id: "testable-prov", display: "Testable"}}) - - h, _ := testHandlersWithCoverSettings(t) - nonAdmin := seedUser(t, h.pool, "csnoadmin", "pw", false) - - req := httptest.NewRequest(http.MethodPost, "/api/admin/cover-sources/testable-prov/test", nil) - req = withUser(req, nonAdmin) - rec := httptest.NewRecorder() - newAdminCoverSourcesRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String()) - } -} - func TestAdminTestCoverSource_NotTestableReturnsOkFalse(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -252,7 +212,7 @@ func TestAdminTestCoverSource_NotTestableReturnsOkFalse(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp testCoverSourceResp + var resp testProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } diff --git a/internal/api/admin_coverage.go b/internal/api/admin_coverage.go index 851d32c7..06ea6d5f 100644 --- a/internal/api/admin_coverage.go +++ b/internal/api/admin_coverage.go @@ -4,9 +4,9 @@ import ( "context" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // coverageRollupResp is the wire shape for GET /api/admin/library/coverage. diff --git a/internal/api/admin_coverage_test.go b/internal/api/admin_coverage_test.go index 4a42c647..6e8ff794 100644 --- a/internal/api/admin_coverage_test.go +++ b/internal/api/admin_coverage_test.go @@ -5,12 +5,11 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/auth" ) // newAdminCoverageRouter builds a test chi router exposing only the @@ -25,9 +24,6 @@ func newAdminCoverageRouter(h *handlers) chi.Router { } func TestAdminLibraryCoverage_EmptyLibraryReturnsZeros(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "covgauge1", "pw", true) @@ -49,9 +45,6 @@ func TestAdminLibraryCoverage_EmptyLibraryReturnsZeros(t *testing.T) { } func TestAdminLibraryCoverage_MixedRowsReturnCorrectBuckets(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "covgauge2", "pw", true) @@ -138,20 +131,3 @@ func TestAdminLibraryCoverage_MixedRowsReturnCorrectBuckets(t *testing.T) { resp.WithArt, resp.Pending, resp.Settled, resp.Total) } } - -func TestAdminLibraryCoverage_NonAdminReturns403(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - user := seedUser(t, pool, "covgauge3", "pw", false) - - req := httptest.NewRequest(http.MethodGet, "/api/admin/library/coverage", nil) - req = withUser(req, user) - rec := httptest.NewRecorder() - newAdminCoverageRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String()) - } -} diff --git a/internal/api/admin_coverart_research.go b/internal/api/admin_coverart_research.go index c945880b..ef086c20 100644 --- a/internal/api/admin_coverart_research.go +++ b/internal/api/admin_coverart_research.go @@ -3,7 +3,7 @@ package api import ( "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/apierror" ) // handleResearchMissingArt bumps the cover-art version unconditionally diff --git a/internal/api/admin_coverart_research_test.go b/internal/api/admin_coverart_research_test.go index a44050f2..c6306028 100644 --- a/internal/api/admin_coverart_research_test.go +++ b/internal/api/admin_coverart_research_test.go @@ -4,13 +4,12 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/coverart" ) func newResearchRouter(h *handlers) chi.Router { @@ -23,9 +22,6 @@ func newResearchRouter(h *handlers) chi.Router { } func TestAdminResearchMissingArt_BumpsAndReturnsVersion(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -50,25 +46,3 @@ func TestAdminResearchMissingArt_BumpsAndReturnsVersion(t *testing.T) { t.Errorf("response missing 'version' field; got %v", resp) } } - -func TestAdminResearchMissingArt_NonAdmin_403(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - coverart.ResetRegistryForTests() - t.Cleanup(coverart.ResetRegistryForTests) - - coverart.Register(&apiTestAlbumProvider{id: "research-prov2", display: "Research Provider 2"}) - - h, _ := testHandlersWithCoverSettings(t) - user := seedUser(t, h.pool, "researchnonadmin", "pw", false) - - req := httptest.NewRequest(http.MethodPost, "/api/admin/cover-sources/research", nil) - req = withUser(req, user) - rec := httptest.NewRecorder() - newResearchRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Errorf("status = %d, want 403", rec.Code) - } -} diff --git a/internal/api/admin_covers.go b/internal/api/admin_covers.go index b9856f23..39c24cd3 100644 --- a/internal/api/admin_covers.go +++ b/internal/api/admin_covers.go @@ -8,9 +8,10 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) type adminCoverRefetchResp struct { @@ -58,11 +59,10 @@ type adminBulkRefetchResp struct { // sources run at disk speed). The count is unknowable synchronously, so the // response just acknowledges the drain started. func (h *handlers) handleAdminBulkRefetchCovers(w http.ResponseWriter, _ *http.Request) { - go func() { - bgCtx := context.Background() - if _, err := h.coverart.EnrichRetryMissing(bgCtx, -1); err != nil { + go periodic.Safe(context.Background(), h.logger, "bulk cover refetch", func(ctx context.Context) { + if _, err := h.coverart.EnrichRetryMissing(ctx, -1); err != nil { h.logger.Warn("admin: bulk cover refetch failed", "err", err) } - }() + }) writeJSON(w, http.StatusOK, adminBulkRefetchResp{Started: true}) } diff --git a/internal/api/admin_covers_test.go b/internal/api/admin_covers_test.go index 7f574ce7..4fdde6f5 100644 --- a/internal/api/admin_covers_test.go +++ b/internal/api/admin_covers_test.go @@ -6,14 +6,13 @@ import ( "log/slog" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // newAdminCoversRouter builds a test chi router with the two cover admin @@ -51,31 +50,12 @@ func testHandlersWithCovers(t *testing.T) (*handlers, *coverart.Enricher) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - enricher := coverart.NewEnricher(pool, slog.Default(), settings) + enricher := coverart.NewEnricher(pool, slog.Default(), settings, t.TempDir()) h.coverart = enricher return h, enricher } -func TestAdminAlbumRefetchCover_NonAdminReturns403(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, _ := testHandlersWithCovers(t) - user := seedUser(t, h.pool, "alice", "pw", false) - artist := seedArtist(t, h.pool, "TestArtist") - album := seedAlbum(t, h.pool, artist.ID, "TestAlbum", 0) - - w := doAdminCoversReq(t, h, http.MethodPost, - "/api/admin/albums/"+uuidToString(album.ID)+"/cover/refetch", user) - if w.Code != http.StatusForbidden { - t.Errorf("status = %d, want 403; body=%s", w.Code, w.Body.String()) - } -} - func TestAdminAlbumRefetchCover_AdminOK(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlersWithCovers(t) admin := seedUser(t, h.pool, "rootuser", "pw", true) artist := seedArtist(t, h.pool, "TestArtist") @@ -97,9 +77,6 @@ func TestAdminAlbumRefetchCover_AdminOK(t *testing.T) { } func TestAdminBulkRefetchCovers_AdminStartsRefetch(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlersWithCovers(t) admin := seedUser(t, h.pool, "rootuser2", "pw", true) artist := seedArtist(t, h.pool, "TestArtist") @@ -118,16 +95,3 @@ func TestAdminBulkRefetchCovers_AdminStartsRefetch(t *testing.T) { t.Errorf("started = false, want true (bulk refetch should acknowledge)") } } - -func TestAdminBulkRefetchCovers_NonAdminReturns403(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, _ := testHandlersWithCovers(t) - user := seedUser(t, h.pool, "alicebulk", "pw", false) - - w := doAdminCoversReq(t, h, http.MethodPost, "/api/admin/covers/refetch-missing", user) - if w.Code != http.StatusForbidden { - t.Errorf("status = %d, want 403; body=%s", w.Code, w.Body.String()) - } -} diff --git a/internal/api/admin_duplicates.go b/internal/api/admin_duplicates.go index 970478f6..014245fe 100644 --- a/internal/api/admin_duplicates.go +++ b/internal/api/admin_duplicates.go @@ -11,9 +11,10 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // duplicateMemberView is one copy in a proposed duplicate group. LikeCount and @@ -107,7 +108,7 @@ type adminDuplicatesResponse struct { func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) { limit, offset, err := parsePaging(r.URL.Query()) if err != nil { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") + writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset")) return } view := r.URL.Query().Get("view") @@ -115,7 +116,7 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) view = duplicateViewReview } if view != duplicateViewReview && view != duplicateViewCrossRelease { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_view") + writeErr(w, apierror.BadRequest("invalid_view", "unknown view")) return } ctx := r.Context() @@ -128,20 +129,20 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) sweep = duplicateSweepViewOf(last) case !errors.Is(err, pgx.ErrNoRows): h.logger.Error("admin: latest duplicate sweep", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } cov, err := h.fingerprintCoverage(ctx) if err != nil { h.logger.Error("admin: fingerprint coverage", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } counts, err := duplicateCounts(ctx, q) if err != nil { h.logger.Error("admin: count duplicate groups", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } total := counts.Review @@ -153,7 +154,7 @@ func (h *handlers) handleListDuplicates(w http.ResponseWriter, r *http.Request) }) if err != nil { h.logger.Error("admin: list duplicate groups", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } @@ -209,14 +210,14 @@ type resolvedActivityResponse struct { func (h *handlers) handleListResolvedDuplicates(w http.ResponseWriter, r *http.Request) { limit, offset, err := parsePaging(r.URL.Query()) if err != nil { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") + writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset")) return } q := dbq.New(h.pool) total, err := q.CountAuditLogByActions(r.Context(), dbq.CountAuditLogByActionsParams{Actions: resolvedActions, SystemOnly: true}) if err != nil { h.logger.Error("admin: count resolved duplicates", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } rows, err := q.ListAuditLogByActions(r.Context(), dbq.ListAuditLogByActionsParams{ @@ -224,7 +225,7 @@ func (h *handlers) handleListResolvedDuplicates(w http.ResponseWriter, r *http.R }) if err != nil { h.logger.Error("admin: list resolved duplicates", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } items := make([]resolvedActivityView, 0, len(rows)) @@ -299,7 +300,7 @@ func foldDuplicateGroups(rows []dbq.ListPendingDuplicateGroupMembersRow) []dupli }) candidates[n] = append(candidates[n], library.SurvivorCandidate{ TrackID: trackID, FileFormat: row.FileFormat, FileSize: row.FileSize, AddedAt: row.AddedAt.Time, - TagFit: library.TagFitScore(row.TrackNumber != nil, row.PositionClash, row.FilePath, row.HasMbid), + TagFit: library.TagFitScore(row.TrackNumber != nil, row.PositionClash, row.FilePath, row.AlbumTitle, row.HasMbid), }) } for i := range groups { @@ -320,11 +321,11 @@ func (h *handlers) handleRunDuplicateSweep(w http.ResponseWriter, _ *http.Reques ) if err != nil { h.logger.Error("admin: start duplicate sweep", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } if !started { - writeAdminJSONErr(w, http.StatusConflict, "sweep_in_progress") + writeErr(w, apierror.Conflict("sweep_in_progress", "a duplicate sweep is already running")) return } writeJSON(w, http.StatusAccepted, map[string]bool{"started": true}) @@ -339,17 +340,17 @@ func (h *handlers) handleRunDuplicateSweep(w http.ResponseWriter, _ *http.Reques func (h *handlers) handleDismissDuplicateGroup(w http.ResponseWriter, r *http.Request) { id, ok := parseUUID(chi.URLParam(r, "id")) if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } n, err := h.dismissDuplicateGroup(r.Context(), id) if err != nil { h.logger.Error("admin: dismiss duplicate group", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } if n == 0 { - writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending") + writeErr(w, apierror.New(http.StatusNotFound, "duplicate_group_not_pending", "that duplicate group is no longer waiting for a decision")) return } writeJSON(w, http.StatusOK, map[string]string{"status": "dismissed"}) @@ -407,18 +408,18 @@ func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Requ } groupID, ok := parseUUID(chi.URLParam(r, "id")) if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } var body mergeDuplicateRequest if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") + writeErr(w, apierror.BadRequest("invalid_body", "invalid request body")) return } var survivorID pgtype.UUID // invalid: keep the proposal if body.SurvivorTrackID != "" { if survivorID, ok = parseUUID(body.SurvivorTrackID); !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } } @@ -432,12 +433,12 @@ func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Requ } switch { case errors.Is(err, library.ErrDuplicateGroupNotPending): - writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending") + writeErr(w, apierror.New(http.StatusNotFound, "duplicate_group_not_pending", "that duplicate group is no longer waiting for a decision")) case errors.Is(err, library.ErrSurvivorNotInGroup): - writeAdminJSONErr(w, http.StatusBadRequest, "survivor_not_in_group") + writeErr(w, apierror.BadRequest("survivor_not_in_group", "the copy to keep is not in this group")) default: h.logger.Error("admin: merge duplicate group", "group_id", uuidToString(groupID), "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) } return } @@ -452,28 +453,26 @@ func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Requ writeJSON(w, http.StatusOK, resp) } -// refetchDuplicateRequest is an admin's answer for one recording filling +// wrongSlotRequest is an admin's answer for one recording filling // several of an album's slots. keep_track_id is the copy whose title the // recording is; empty means they cannot say, and every copy goes. -type refetchDuplicateRequest struct { +type wrongSlotRequest struct { KeepTrackID string `json:"keep_track_id"` } -// refetchDuplicateResponse reports what went. Blocked names the releases set -// aside; empty when the album came from before Minstrel downloaded anything. -type refetchDuplicateResponse struct { +// wrongSlotResponse reports what went. +type wrongSlotResponse struct { KeptTrackID *string `json:"kept_track_id"` RemovedPaths []string `json:"removed_paths"` - Blocked []string `json:"blocked"` } -// handleRefetchDuplicateGroup implements POST -// /api/admin/library/duplicates/{id}/refetch: settle a group of one +// handleRemoveWrongSlotFiles implements POST +// /api/admin/library/duplicates/{id}/remove-files: settle a group of one // recording in several slots of an album the way the resolver would, with an // admin's answer. The copies in slots that are not the recording's are -// removed and marked missing, the release they came from is set aside, and the -// album is wanted again. Merge is the wrong action there: it keeps one title -// whether or not it is the audio's, and fetches nothing. +// removed and marked missing, so the slot shows as missing until a good copy +// arrives in the library. Merge is the wrong action there: it keeps one title +// whether or not it is the audio's. // // Errors: // - 409 library_not_writable / 500 file_delete_failed when a file could not be @@ -481,25 +480,25 @@ type refetchDuplicateResponse struct { // - 404 duplicate_group_not_pending when the group was already resolved // - 400 not_wrong_slot when the group is not one recording in several slots // - 400 survivor_not_in_group, invalid_id, invalid_body -func (h *handlers) handleRefetchDuplicateGroup(w http.ResponseWriter, r *http.Request) { +func (h *handlers) handleRemoveWrongSlotFiles(w http.ResponseWriter, r *http.Request) { admin, ok := requireUser(w, r) if !ok { return } groupID, ok := parseUUID(chi.URLParam(r, "id")) if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } - var body refetchDuplicateRequest + var body wrongSlotRequest if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") + writeErr(w, apierror.BadRequest("invalid_body", "invalid request body")) return } var keepID pgtype.UUID // invalid: every copy goes if body.KeepTrackID != "" { if keepID, ok = parseUUID(body.KeepTrackID); !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } } @@ -513,22 +512,19 @@ func (h *handlers) handleRefetchDuplicateGroup(w http.ResponseWriter, r *http.Re } switch { case errors.Is(err, library.ErrDuplicateGroupNotPending): - writeAdminJSONErr(w, http.StatusNotFound, "duplicate_group_not_pending") + writeErr(w, apierror.New(http.StatusNotFound, "duplicate_group_not_pending", "that duplicate group is no longer waiting for a decision")) case errors.Is(err, library.ErrNotWrongSlot): - writeAdminJSONErr(w, http.StatusBadRequest, "not_wrong_slot") + writeErr(w, apierror.BadRequest("not_wrong_slot", "this group is not a wrong-slot match")) case errors.Is(err, library.ErrSurvivorNotInGroup): - writeAdminJSONErr(w, http.StatusBadRequest, "survivor_not_in_group") + writeErr(w, apierror.BadRequest("survivor_not_in_group", "the copy to keep is not in this group")) default: - h.logger.Error("admin: refetch duplicate group", "group_id", uuidToString(groupID), "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + h.logger.Error("admin: remove wrong-slot files", "group_id", uuidToString(groupID), "err", err) + writeErr(w, apierror.Internal(err)) } return } - resp := refetchDuplicateResponse{RemovedPaths: make([]string, 0, len(res.Removed)), Blocked: res.Blocked} - if resp.Blocked == nil { - resp.Blocked = []string{} - } + resp := wrongSlotResponse{RemovedPaths: make([]string, 0, len(res.Removed))} if res.Kept != nil { id := uuidToString(res.Kept.TrackID) resp.KeptTrackID = &id diff --git a/internal/api/admin_duplicates_test.go b/internal/api/admin_duplicates_test.go index ba869714..f4a882af 100644 --- a/internal/api/admin_duplicates_test.go +++ b/internal/api/admin_duplicates_test.go @@ -6,7 +6,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func dupUUID(b byte) pgtype.UUID { @@ -28,14 +28,14 @@ func TestFoldDuplicateGroups(t *testing.T) { rows := []dbq.ListPendingDuplicateGroupMembersRow{ // Group 1: identical audio, sizes tie, the older copy should be kept. {GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(10), - Title: "WWW", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(newer), PlayCount: 3}, + Title: "XYZ", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(newer), PlayCount: 3}, {GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(11), - Title: "WWW", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(older), LikeCount: 1}, + Title: "XYZ", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(older), LikeCount: 1}, // Group 2: the same recording, FLAC against MP3. {GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(20), - Title: "Lovesick", FileFormat: "mp3", FileSize: 9_000_000, DurationMs: 198_000, AddedAt: dupTS(older)}, + Title: "Homesick", FileFormat: "mp3", FileSize: 9_000_000, DurationMs: 198_000, AddedAt: dupTS(older)}, {GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(21), - Title: "Lovesick", FileFormat: "flac", FileSize: 30_000_000, DurationMs: 198_000, AddedAt: dupTS(newer)}, + Title: "Homesick", FileFormat: "flac", FileSize: 30_000_000, DurationMs: 198_000, AddedAt: dupTS(newer)}, } got := foldDuplicateGroups(rows) diff --git a/internal/api/admin_fingerprint_settings.go b/internal/api/admin_fingerprint_settings.go index cf27c54e..f6c0dabb 100644 --- a/internal/api/admin_fingerprint_settings.go +++ b/internal/api/admin_fingerprint_settings.go @@ -5,8 +5,8 @@ import ( "errors" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/library" ) // fingerprintSettingsBody is the wire shape for GET and PUT @@ -67,7 +67,7 @@ func (h *handlers) handleUpdateFingerprintSettings(w http.ResponseWriter, r *htt AutoResolve: autoResolve, }) if err != nil { - // Validation mirrors migration 0061's CHECKs and names the field. + // Validation mirrors fingerprint_settings's CHECKs and names the field. if errors.Is(err, library.ErrFingerprintSettingOutOfRange) { writeErr(w, apierror.BadRequest("invalid_setting", err.Error())) return diff --git a/internal/api/admin_fingerprint_settings_test.go b/internal/api/admin_fingerprint_settings_test.go index 0dfaedf3..4af674f4 100644 --- a/internal/api/admin_fingerprint_settings_test.go +++ b/internal/api/admin_fingerprint_settings_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/library" ) func TestGetFingerprintSettings_ServesDefaultsWithoutAService(t *testing.T) { diff --git a/internal/api/admin_import.go b/internal/api/admin_import.go deleted file mode 100644 index 207283ef..00000000 --- a/internal/api/admin_import.go +++ /dev/null @@ -1,285 +0,0 @@ -package api - -import ( - "encoding/json" - "errors" - "net/http" - - "github.com/jackc/pgx/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/importer" - "git.fabledsword.com/bvandeusen/minstrel/internal/lifecycle" -) - -// Downloads and their imports: the Wanted view's Activity tab, -// a person's "import anyway", "refuse" and "retry", and the Blocked tab. - -// downloadView is one grab and what its import made of it. -type downloadView struct { - ID string `json:"id"` - WantID *string `json:"want_id"` - WantTitle string `json:"want_title"` - WantArtist string `json:"want_artist"` - Name string `json:"name"` - Indexer string `json:"indexer"` - Client string `json:"client"` - Quality string `json:"quality"` - Origin string `json:"origin"` - GrabbedAt string `json:"grabbed_at"` - EndedAt *string `json:"ended_at"` - EndReason string `json:"end_reason"` - Progress float32 `json:"progress"` - ImportState string `json:"import_state"` - ImportReason string `json:"import_reason"` - ImportedAt *string `json:"imported_at"` - ImportedFiles int32 `json:"imported_files"` - Destination string `json:"destination"` - Edition string `json:"edition,omitempty"` - Evidence *importer.Evidence `json:"evidence,omitempty"` - Files []string `json:"files"` - Skipped int `json:"skipped"` - RehomedFrom string `json:"rehomed_from,omitempty"` - // EndDetail says why an ended download ended. - EndDetail string `json:"end_detail"` - // Seeding: imported and still sharing; Ratio its share ratio as last - // read; SeedReleasedAt when it was removed once it had shared enough. - Seeding bool `json:"seeding"` - Ratio float32 `json:"ratio"` - SeedReleasedAt *string `json:"seed_released_at"` - // Condition is what is wrong with it now, if anything. - Condition *conditionView `json:"condition"` -} - -// conditionView is an open row of the intervention ledger: what was seen, -// since when, and how many times it was retried. -type conditionView struct { - Trigger string `json:"trigger"` - Detail string `json:"detail"` - Retries int32 `json:"retries"` - Since string `json:"since"` -} - -func downloadFrom(g dbq.ListGrabsRow) downloadView { - v := downloadView{ - ID: uuidToString(g.ID), Name: g.Name, Indexer: g.Indexer, Client: g.Client, Quality: g.Quality, - Origin: g.Origin, GrabbedAt: formatTimestamp(g.GrabbedAt), EndReason: g.EndReason, - Progress: g.Progress, ImportState: g.ImportState, ImportReason: g.ImportReason, - ImportedFiles: g.ImportedFiles, Destination: g.Destination, Files: []string{}, - EndDetail: g.EndDetail, Seeding: g.Seeding, Ratio: g.Ratio, - } - if g.SeedReleasedAt.Valid { - at := formatTimestamp(g.SeedReleasedAt) - v.SeedReleasedAt = &at - } - if g.Condition != nil { - v.Condition = &conditionView{Trigger: *g.Condition, Detail: deref(g.ConditionDetail), - Since: formatTimestamp(g.ConditionSince)} - if g.ConditionRetries != nil { - v.Condition.Retries = *g.ConditionRetries - } - } - if g.WantID.Valid { - id := uuidToString(g.WantID) - v.WantID = &id - } - if g.WantTitle != nil { - v.WantTitle = *g.WantTitle - } - if g.WantArtist != nil { - v.WantArtist = *g.WantArtist - } - if g.EndedAt.Valid { - at := formatTimestamp(g.EndedAt) - v.EndedAt = &at - } - if g.ImportedAt.Valid { - at := formatTimestamp(g.ImportedAt) - v.ImportedAt = &at - } - var det importer.Detail - if len(g.ImportDetail) > 0 && json.Unmarshal(g.ImportDetail, &det) == nil && det.Verdict.Outcome != "" { - ev := det.Verdict.Evidence - v.Evidence, v.Edition, v.Skipped, v.RehomedFrom = &ev, det.Edition, det.Skipped, det.RehomedFrom - if det.Files != nil { - v.Files = det.Files - } - } - return v -} - -type downloadsPage struct { - Items []downloadView `json:"items"` - Limit int `json:"limit"` - Offset int `json:"offset"` - // ClientsDown are the download clients not answering now. - ClientsDown []clientDownView `json:"clients_down"` -} - -type clientDownView struct { - Client string `json:"client"` - Detail string `json:"detail"` - Since string `json:"since"` -} - -// handleListDownloads implements GET /api/admin/downloads?offset=: running -// downloads first, then the rest newest first. -func (h *handlers) handleListDownloads(w http.ResponseWriter, r *http.Request) { - limit, offset, err := parsePaging(r.URL.Query()) - if err != nil { - writeErr(w, apierror.BadRequest("invalid_paging", "limit and offset must be numbers")) - return - } - rows, err := dbq.New(h.pool).ListGrabs(r.Context(), dbq.ListGrabsParams{MaxRows: int32(limit), Skip: int32(offset)}) - if err != nil { - writeErrWithLog(w, h.logger, "admin downloads: list", apierror.Internal(err)) - return - } - down, err := dbq.New(h.pool).ListClientsDown(r.Context()) - if err != nil { - writeErrWithLog(w, h.logger, "admin downloads: clients down", apierror.Internal(err)) - return - } - out := downloadsPage{Items: make([]downloadView, 0, len(rows)), Limit: limit, Offset: offset, - ClientsDown: make([]clientDownView, 0, len(down))} - for _, g := range rows { - out.Items = append(out.Items, downloadFrom(g)) - } - for _, c := range down { - out.ClientsDown = append(out.ClientsDown, clientDownView{Client: c.Client, Detail: c.Detail, - Since: formatTimestamp(c.FirstSeen)}) - } - writeJSON(w, http.StatusOK, out) -} - -// handleAbandonDownload implements POST /api/admin/downloads/{id}/abandon: a -// running download is given up, its release set aside, the download removed -// and the album searched again. -func (h *handlers) handleAbandonDownload(w http.ResponseWriter, r *http.Request) { - admin, ok := requireUser(w, r) - if !ok { - return - } - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - if _, err := h.lifecycle.Abandon(r.Context(), id, admin.ID); err != nil { - switch { - case errors.Is(err, pgx.ErrNoRows), errors.Is(err, lifecycle.ErrNotAbandonable): - writeErr(w, apierror.Conflict("not_running", "that download is no longer running")) - default: - writeErrWithLog(w, h.logger, "admin downloads: abandon", apierror.Internal(err)) - } - return - } - w.WriteHeader(http.StatusNoContent) -} - -// handleImportAnyway implements POST /api/admin/downloads/{id}/import: a -// download the check held for a person (or one that failed) is imported on -// the next pass whatever the check says. -func (h *handlers) handleImportAnyway(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - if _, err := dbq.New(h.pool).ForceGrabImport(r.Context(), id); err != nil { - h.writeImportErr(w, "import anyway", err) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// handleRetryImport implements POST /api/admin/downloads/{id}/retry. -func (h *handlers) handleRetryImport(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - if _, err := dbq.New(h.pool).RetryGrabImport(r.Context(), id); err != nil { - h.writeImportErr(w, "retry", err) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// handleRefuseDownload implements POST /api/admin/downloads/{id}/refuse: the -// release is blocked, the download removed and the album searched again. -func (h *handlers) handleRefuseDownload(w http.ResponseWriter, r *http.Request) { - admin, ok := requireUser(w, r) - if !ok { - return - } - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - if _, err := h.importer.Refuse(r.Context(), id, admin.ID); err != nil { - h.writeImportErr(w, "refuse", err) - return - } - w.WriteHeader(http.StatusNoContent) -} - -func (h *handlers) writeImportErr(w http.ResponseWriter, what string, err error) { - switch { - case errors.Is(err, pgx.ErrNoRows), errors.Is(err, importer.ErrNotDecidable): - writeErr(w, apierror.Conflict("not_decidable", "that download is not waiting on a decision")) - default: - writeErrWithLog(w, h.logger, "admin downloads: "+what, apierror.Internal(err)) - } -} - -type releaseBlockView struct { - InfoHash string `json:"info_hash"` - Name string `json:"name"` - Reason string `json:"reason"` - Detail string `json:"detail"` - BlockedAt string `json:"blocked_at"` - // ExpiresAt is when a release given up on may be taken again; null is - // for good. - ExpiresAt *string `json:"expires_at"` - WantTitle string `json:"want_title"` - WantArtist string `json:"want_artist"` -} - -type releaseBlocksPage struct { - Items []releaseBlockView `json:"items"` - Limit int `json:"limit"` - Offset int `json:"offset"` -} - -// handleListReleaseBlocks implements GET /api/admin/release-blocks?offset=: -// every release set aside, by a person or by a check, newest first. -func (h *handlers) handleListReleaseBlocks(w http.ResponseWriter, r *http.Request) { - limit, offset, err := parsePaging(r.URL.Query()) - if err != nil { - writeErr(w, apierror.BadRequest("invalid_paging", "limit and offset must be numbers")) - return - } - rows, err := dbq.New(h.pool).ListReleaseBlocksPage(r.Context(), dbq.ListReleaseBlocksPageParams{ - MaxRows: int32(limit), Skip: int32(offset)}) - if err != nil { - writeErrWithLog(w, h.logger, "admin release blocks: list", apierror.Internal(err)) - return - } - out := releaseBlocksPage{Items: make([]releaseBlockView, 0, len(rows)), Limit: limit, Offset: offset} - for _, b := range rows { - v := releaseBlockView{InfoHash: b.InfoHash, Name: b.Name, Reason: b.Reason, Detail: b.Detail, - BlockedAt: formatTimestamp(b.BlockedAt)} - if b.ExpiresAt.Valid { - at := formatTimestamp(b.ExpiresAt) - v.ExpiresAt = &at - } - if b.WantTitle != nil { - v.WantTitle = *b.WantTitle - } - if b.WantArtist != nil { - v.WantArtist = *b.WantArtist - } - out.Items = append(out.Items, v) - } - writeJSON(w, http.StatusOK, out) -} diff --git a/internal/api/admin_invites.go b/internal/api/admin_invites.go index 63da745c..cffa70f7 100644 --- a/internal/api/admin_invites.go +++ b/internal/api/admin_invites.go @@ -12,9 +12,9 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // inviteTTL is the lifetime of a freshly-minted invite. 24 hours diff --git a/internal/api/admin_invites_test.go b/internal/api/admin_invites_test.go index 6723a770..89057c8b 100644 --- a/internal/api/admin_invites_test.go +++ b/internal/api/admin_invites_test.go @@ -5,12 +5,11 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/auth" ) func newAdminInvitesRouter(h *handlers) chi.Router { @@ -25,9 +24,6 @@ func newAdminInvitesRouter(h *handlers) chi.Router { } func TestAdminInvites_CreateListDelete(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "invadmin", "pw", true) @@ -93,19 +89,3 @@ func TestAdminInvites_CreateListDelete(t *testing.T) { t.Errorf("invite still exists after delete (count=%d)", count) } } - -func TestAdminInvites_NonAdmin_403(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - user := seedUser(t, pool, "invnonadmin", "pw", false) - - req := httptest.NewRequest(http.MethodPost, "/api/admin/invites", nil) - req = withUser(req, user) - rec := httptest.NewRecorder() - newAdminInvitesRouter(h).ServeHTTP(rec, req) - if rec.Code != http.StatusForbidden { - t.Errorf("status = %d, want 403", rec.Code) - } -} diff --git a/internal/api/admin_library_folders.go b/internal/api/admin_library_folders.go index 0c2a4745..c6b56c38 100644 --- a/internal/api/admin_library_folders.go +++ b/internal/api/admin_library_folders.go @@ -6,9 +6,9 @@ import ( "net/http" "os" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // The library's folders: where the scan, the watcher and the import diff --git a/internal/api/admin_library_missing.go b/internal/api/admin_library_missing.go index 30a3a4a8..19605238 100644 --- a/internal/api/admin_library_missing.go +++ b/internal/api/admin_library_missing.go @@ -1,44 +1,50 @@ package api import ( + "encoding/csv" + "encoding/json" + "errors" "net/http" - "time" + "strconv" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/tracks" ) -// missingTrackView is one track whose file the scan could not find. +// missingTrackView is one track waiting for a file: removed by an admin from +// a Collection queue, or gone from disk. // // The text fields come from the tracks row, not from the filesystem, which is // the point: the recording is still a known thing with a title, an artist and // a play history — only its bytes are absent. LastPlayedAt is nullable because // plenty of missing files were never played, and that is exactly the signal an -// operator wants when deciding whether to bother re-acquiring one. +// operator wants when deciding whether a lost file is worth replacing. +// +// RemovedFor is the queue the file was removed from ("report", "duplicate", +// "suspect"), or null when the scan found it gone; RemovedBy is the admin who +// removed it, null for the duplicate resolver. The MBIDs let an export be +// matched exactly by whatever finds the good copy. type missingTrackView struct { - TrackID string `json:"track_id"` - Title string `json:"title"` - ArtistID string `json:"artist_id"` - ArtistName string `json:"artist_name"` - AlbumID string `json:"album_id"` - AlbumTitle string `json:"album_title"` - FilePath string `json:"file_path"` - DurationSec int32 `json:"duration_sec"` - MissingSince string `json:"missing_since"` - LastPlayedAt *string `json:"last_played_at"` -} - -// reacquisitionStateView is what the wanted list says about one album: when -// it was wanted back, and when the library -// held it again. A missing album with no want yet is still inside the grace -// window, or MusicBrainz cannot name it. Want is that want as the wanted list -// sends it, so the Missing page can show its search and download and act on -// it. -type reacquisitionStateView struct { - WantedAt *string `json:"wanted_at"` - HeldAt *string `json:"held_at"` - Want *wantView `json:"want"` + TrackID string `json:"track_id"` + Title string `json:"title"` + ArtistID string `json:"artist_id"` + ArtistName string `json:"artist_name"` + AlbumID string `json:"album_id"` + AlbumTitle string `json:"album_title"` + FilePath string `json:"file_path"` + DurationSec int32 `json:"duration_sec"` + DiscNumber *int32 `json:"disc_number"` + TrackNumber *int32 `json:"track_number"` + RecordingMBID *string `json:"recording_mbid"` + ReleaseGroupMBID *string `json:"release_group_mbid"` + RemovedFor *string `json:"removed_for"` + RemovedBy *string `json:"removed_by"` + MissingSince string `json:"missing_since"` + LastPlayedAt *string `json:"last_played_at"` } // missingGroupView is a directory's worth of missing tracks. @@ -52,10 +58,6 @@ type missingGroupView struct { Directory string `json:"directory"` MissingSince string `json:"missing_since"` Tracks []missingTrackView `json:"tracks"` - // Nil when nothing has been attempted for this group's album — the - // common case for a folder that just went missing, and distinct from - // an attempts:0 record, which cannot occur. - Reacquisition *reacquisitionStateView `json:"reacquisition"` } // adminMissingResponse is the paged envelope. Total counts TRACKS, not @@ -68,16 +70,15 @@ type adminMissingResponse struct { Groups []missingGroupView `json:"groups"` } -// handleListMissingTracks implements GET /api/admin/library/missing. -// -// Read-only by design. Nothing on this surface deletes a track: a missing file -// keeps its row, its history and its likes because it may come back, and if it -// comes back renamed the scanner adopts it. The surface exists so an admin -// can SEE what the library has lost and act on it deliberately. +// handleListMissingTracks implements GET /api/admin/library/missing: the +// tracks waiting for a file. A waiting track keeps its row, its history and +// its likes because a file may come back, and a good copy that lands in the +// library is adopted or folded into it. Forgetting one is a separate, +// deliberate call (handleForgetMissingTracks). func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Request) { limit, offset, err := parsePaging(r.URL.Query()) if err != nil { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") + writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset")) return } @@ -85,7 +86,7 @@ func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Reques total, err := q.CountMissingTracks(r.Context()) if err != nil { h.logger.Error("admin: count missing tracks", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{ @@ -94,12 +95,11 @@ func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Reques }) if err != nil { h.logger.Error("admin: list missing tracks", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } groups := groupMissingByDirectory(rows) - h.attachReacquisitionState(r, q, rows, groups) out := adminMissingResponse{ Total: total, @@ -122,15 +122,21 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView groups := make([]missingGroupView, 0, 8) for _, row := range rows { t := missingTrackView{ - TrackID: uuidToString(row.ID), - Title: row.Title, - ArtistID: uuidToString(row.ArtistID), - ArtistName: row.ArtistName, - AlbumID: uuidToString(row.AlbumID), - AlbumTitle: row.AlbumTitle, - FilePath: row.FilePath, - DurationSec: row.DurationMs / 1000, - MissingSince: formatTimestamp(row.MissingSince), + TrackID: uuidToString(row.ID), + Title: row.Title, + ArtistID: uuidToString(row.ArtistID), + ArtistName: row.ArtistName, + AlbumID: uuidToString(row.AlbumID), + AlbumTitle: row.AlbumTitle, + FilePath: row.FilePath, + DurationSec: row.DurationMs / 1000, + DiscNumber: row.DiscNumber, + TrackNumber: row.TrackNumber, + RecordingMBID: row.Mbid, + ReleaseGroupMBID: row.ReleaseGroupMbid, + RemovedFor: row.RemovedReason, + RemovedBy: row.RemovedByName, + MissingSince: formatTimestamp(row.MissingSince), } if row.LastPlayedAt.Valid { s := formatTimestamp(row.LastPlayedAt) @@ -155,108 +161,115 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView return groups } -// attachReacquisitionState decorates each group with its album's want. -// -// Best-effort: this is context on a list whose primary job is showing what is -// missing, so a failure here leaves the groups bare rather than failing the -// page. One batched query for the whole page, not one per group. -// -// A group is keyed by directory while a want is keyed by album, and those -// line up in practice (an album's files live in one folder) but are not -// guaranteed to — a directory holding two albums takes the first album's -// state, which is the same album its first track belongs to. -func (h *handlers) attachReacquisitionState( - r *http.Request, - q *dbq.Queries, - rows []dbq.ListMissingTracksRow, - groups []missingGroupView, -) { - if len(groups) == 0 { - return - } - // Directory -> the album its first row belongs to, matching the order - // groupMissingByDirectory folded them in. - dirAlbum := make(map[string]pgtype.UUID, len(groups)) - ids := make([]pgtype.UUID, 0, len(groups)) - // The latest loss in each folder: a want held before it is the album - // as it was before its files went, not the library holding it again. - dirLost := make(map[string]time.Time, len(groups)) - for _, row := range rows { - if row.MissingSince.Valid && row.MissingSince.Time.After(dirLost[row.Directory]) { - dirLost[row.Directory] = row.MissingSince.Time - } - if _, seen := dirAlbum[row.Directory]; seen { - continue - } - dirAlbum[row.Directory] = row.AlbumID - ids = append(ids, row.AlbumID) - } +// forgetMissingRequest is the body of POST /api/admin/library/missing/forget: +// the waiting tracks to forget, one track or a whole folder's. +type forgetMissingRequest struct { + TrackIDs []string `json:"track_ids"` +} - wants, err := q.GetWantsForAlbums(r.Context(), ids) - if err != nil { - h.logger.Warn("admin missing: want lookup failed", "err", err) +// forgetMissingRequestLimit caps the body: a folder of a few hundred ids is +// a few tens of KB. +const forgetMissingRequestLimit = 1 << 20 + +// handleForgetMissingTracks implements POST +// /api/admin/library/missing/forget: the tracks go for good, with their +// likes, plays and playlist places, and an album or artist they leave empty +// goes too. It is all or nothing. +// +// Errors: 400 invalid_body / invalid_id; 404 track_not_found when an id is +// unknown; 409 track_has_file when one has its file again, since forgetting +// it would throw away music the library holds. +func (h *handlers) handleForgetMissingTracks(w http.ResponseWriter, r *http.Request) { + admin, ok := requireUser(w, r) + if !ok { return } - // Newest want first, so the first seen per album is its current one. - byAlbum := make(map[string]dbq.GetWantsForAlbumsRow, len(wants)) - for _, w := range wants { - if _, seen := byAlbum[uuidToString(w.AlbumID)]; !seen { - byAlbum[uuidToString(w.AlbumID)] = w - } + var body forgetMissingRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, forgetMissingRequestLimit)).Decode(&body); err != nil || len(body.TrackIDs) == 0 { + writeErr(w, apierror.BadRequest("invalid_body", "invalid request body")) + return } - full := h.wantViewsByID(r, q, byAlbum) - for i := range groups { - albumID, ok := dirAlbum[groups[i].Directory] + ids := make([]pgtype.UUID, 0, len(body.TrackIDs)) + for _, raw := range body.TrackIDs { + id, ok := parseUUID(raw) if !ok { - continue + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) + return } - w, ok := byAlbum[uuidToString(albumID)] - if !ok { - continue + ids = append(ids, id) + } + gone, err := h.tracks.ForgetTracks(r.Context(), ids, admin.ID) + switch { + case errors.Is(err, tracks.ErrNotFound): + writeErr(w, apierror.NotFound("track")) + return + case errors.Is(err, library.ErrTrackPresent): + writeErr(w, apierror.Conflict("track_has_file", "the track's file is still on disk")) + return + case err != nil: + h.logger.Error("admin: forget missing tracks", "err", err) + writeErr(w, apierror.Internal(err)) + return + } + writeJSON(w, http.StatusOK, map[string]int{"forgotten": len(gone)}) +} + +// missingCSVHeader is the export's columns. They name the song for whatever +// finds the good copy: the MBIDs match it exactly where the tags carried +// them, and the names do the rest. +var missingCSVHeader = []string{ + "artist", "album", "disc", "track", "title", + "recording_mbid", "release_group_mbid", "why", "since", +} + +// handleExportMissingTracks implements GET /api/admin/library/missing.csv: +// every track waiting for a file, in the list's folder order, as a CSV to +// hand to whatever finds music. "why" is the queue the file was removed from, +// or "missing" when the scan found it gone. +func (h *handlers) handleExportMissingTracks(w http.ResponseWriter, r *http.Request) { + q := dbq.New(h.pool) + total, err := q.CountMissingTracks(r.Context()) + if err != nil { + h.logger.Error("admin: count missing tracks", "err", err) + writeErr(w, apierror.Internal(err)) + return + } + rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{PageLimit: int32(total), PageOffset: 0}) + if err != nil { + h.logger.Error("admin: list missing tracks", "err", err) + writeErr(w, apierror.Internal(err)) + return + } + w.Header().Set("Content-Type", "text/csv; charset=utf-8") + w.Header().Set("Content-Disposition", `attachment; filename="needs-a-file.csv"`) + out := csv.NewWriter(w) + _ = out.Write(missingCSVHeader) + for _, row := range rows { + why := "missing" + if row.RemovedReason != nil { + why = *row.RemovedReason } - // Held before its files went (every library album is on the list, - // held): not wanted back yet, which the sweep does once - // the grace window has passed. - if w.FulfilledAt.Valid && !w.FulfilledAt.Time.After(dirLost[groups[i].Directory]) { - continue - } - view := &reacquisitionStateView{} - wantedAt := formatTimestamp(w.WantedAt) - view.WantedAt = &wantedAt - if w.FulfilledAt.Valid { - heldAt := formatTimestamp(w.FulfilledAt) - view.HeldAt = &heldAt - } - if v, ok := full[uuidToString(w.WantID)]; ok { - view.Want = &v - } - groups[i].Reacquisition = view + _ = out.Write([]string{ + row.ArtistName, row.AlbumTitle, optInt(row.DiscNumber), optInt(row.TrackNumber), row.Title, + optString(row.Mbid), optString(row.ReleaseGroupMbid), why, formatTimestamp(row.MissingSince), + }) + } + out.Flush() + if err := out.Error(); err != nil { + h.logger.Warn("admin: write missing-tracks csv", "err", err) } } -// wantViewsByID reads each album's current want in full, keyed by want id. -// Best-effort like the state it decorates: a failure leaves the groups with -// their dates and no want. -func (h *handlers) wantViewsByID( - r *http.Request, - q *dbq.Queries, - byAlbum map[string]dbq.GetWantsForAlbumsRow, -) map[string]wantView { - ids := make([]pgtype.UUID, 0, len(byAlbum)) - for _, w := range byAlbum { - ids = append(ids, w.WantID) +func optInt(v *int32) string { + if v == nil { + return "" } - out := make(map[string]wantView, len(ids)) - if len(ids) == 0 { - return out + return strconv.Itoa(int(*v)) +} + +func optString(v *string) string { + if v == nil { + return "" } - rows, err := q.ListWants(r.Context(), dbq.ListWantsParams{State: "all", WantIds: ids, MaxRows: int32(len(ids))}) - if err != nil { - h.logger.Warn("admin missing: want detail lookup failed", "err", err) - return out - } - for _, row := range rows { - out[uuidToString(row.ID)] = wantViewOf(row) - } - return out + return *v } diff --git a/internal/api/admin_library_missing_db_test.go b/internal/api/admin_library_missing_db_test.go new file mode 100644 index 00000000..f79439ea --- /dev/null +++ b/internal/api/admin_library_missing_db_test.go @@ -0,0 +1,108 @@ +package api + +import ( + "bytes" + "context" + "encoding/csv" + "net/http" + "net/http/httptest" + "testing" +) + +// The export names every waiting track and why it waits, with an empty cell +// for an MBID or a position the tags never carried. +func TestHandleExportMissingTracks_Integration(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + admin := seedUser(t, pool, "export-admin", "pw", true) + artist := seedArtist(t, pool, "Fields of Ontario") + album := seedAlbum(t, pool, artist.ID, "Geomantic", 2002) + gone := seedTrack(t, pool, album.ID, artist.ID, "Music Is Maps", 0, 300_000) + removed := seedTrack(t, pool, album.ID, artist.ID, "Dusk Chorus", 2, 240_000) + seedTrack(t, pool, album.ID, artist.ID, "Julia and Cane", 3, 200_000) + ctx := context.Background() + if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, gone.ID); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now(), removed_reason = 'report', removed_by = $2, + mbid = 'rec-dawn', mbid_source = 'tag' WHERE id = $1`, removed.ID, admin.ID); err != nil { + t.Fatal(err) + } + + req := withUser(httptest.NewRequest(http.MethodGet, "/api/admin/library/missing.csv", nil), admin) + w := httptest.NewRecorder() + h.handleExportMissingTracks(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status %d: %s", w.Code, w.Body.String()) + } + rows, err := csv.NewReader(bytes.NewReader(w.Body.Bytes())).ReadAll() + if err != nil { + t.Fatalf("parse csv: %v", err) + } + if len(rows) != 3 { + t.Fatalf("rows = %v, want a header and the two waiting tracks", rows) + } + byTitle := map[string][]string{} + for _, r := range rows[1:] { + byTitle[r[4]] = r + } + if r := byTitle["Music Is Maps"]; r == nil || r[3] != "" || r[5] != "" || r[7] != "missing" { + t.Errorf("untagged missing row = %v, want no track number, no mbid, why missing", r) + } + if r := byTitle["Dusk Chorus"]; r == nil || r[3] != "2" || r[5] != "rec-dawn" || r[7] != "report" { + t.Errorf("removed row = %v, want track 2, its mbid, why report", r) + } +} + +// Forget deletes waiting tracks, all or nothing: a track that has its file +// is refused, and nothing in that request goes. +func TestHandleForgetMissingTracks_Integration(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + admin := seedUser(t, pool, "forget-admin", "pw", true) + artist := seedArtist(t, pool, "Autoglyph") + album := seedAlbum(t, pool, artist.ID, "Ochre", 1994) + waiting := seedTrack(t, pool, album.ID, artist.ID, "Foil", 1, 300_000) + present := seedTrack(t, pool, album.ID, artist.ID, "Montreal", 2, 300_000) + ctx := context.Background() + if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, waiting.ID); err != nil { + t.Fatal(err) + } + forget := func(ids ...string) int { + body := `{"track_ids":[` + for i, id := range ids { + if i > 0 { + body += "," + } + body += `"` + id + `"` + } + body += `]}` + req := withUser(httptest.NewRequest(http.MethodPost, "/api/admin/library/missing/forget", bytes.NewBufferString(body)), admin) + w := httptest.NewRecorder() + h.handleForgetMissingTracks(w, req) + return w.Code + } + exists := func(id string) bool { + var n int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM tracks WHERE id = $1`, id).Scan(&n); err != nil { + t.Fatal(err) + } + return n == 1 + } + + if code := forget(uuidToString(waiting.ID), uuidToString(present.ID)); code != http.StatusConflict { + t.Fatalf("forgetting a track with its file: status %d, want 409", code) + } + if !exists(uuidToString(waiting.ID)) || !exists(uuidToString(present.ID)) { + t.Fatalf("a refused forget removed a track") + } + if code := forget(uuidToString(waiting.ID)); code != http.StatusOK { + t.Fatalf("forgetting the waiting track: status %d, want 200", code) + } + if exists(uuidToString(waiting.ID)) { + t.Errorf("the forgotten track is still there") + } + if !exists(uuidToString(present.ID)) { + t.Errorf("the album's other track went too") + } +} diff --git a/internal/api/admin_library_missing_test.go b/internal/api/admin_library_missing_test.go index 9d28a8b5..5e579520 100644 --- a/internal/api/admin_library_missing_test.go +++ b/internal/api/admin_library_missing_test.go @@ -6,7 +6,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // missingRow builds a ListMissingTracksRow with just the fields the grouping @@ -29,9 +29,9 @@ func TestGroupMissingByDirectory(t *testing.T) { t.Run("consecutive rows in one directory collapse to one group", func(t *testing.T) { groups := groupMissingByDirectory([]dbq.ListMissingTracksRow{ - missingRow("/music/Linkin Park/Minutes to Midnight", "Given Up", base), - missingRow("/music/Linkin Park/Minutes to Midnight", "Leave Out All the Rest", base), - missingRow("/music/Linkin Park/Minutes to Midnight", "Bleed It Out", base), + missingRow("/music/Lincoln Yard/Minutes to Noon", "Paper Wings", base), + missingRow("/music/Lincoln Yard/Minutes to Noon", "Leave the Lights On", base), + missingRow("/music/Lincoln Yard/Minutes to Noon", "Ring It Out", base), }) if len(groups) != 1 { @@ -40,7 +40,7 @@ func TestGroupMissingByDirectory(t *testing.T) { if got := len(groups[0].Tracks); got != 3 { t.Errorf("want 3 tracks in the group, got %d", got) } - if groups[0].Directory != "/music/Linkin Park/Minutes to Midnight" { + if groups[0].Directory != "/music/Lincoln Yard/Minutes to Noon" { t.Errorf("unexpected directory %q", groups[0].Directory) } }) diff --git a/internal/api/admin_library_missing_wants_test.go b/internal/api/admin_library_missing_wants_test.go deleted file mode 100644 index 6710580d..00000000 --- a/internal/api/admin_library_missing_wants_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/jackc/pgx/v5/pgtype" -) - -// seedMissingWant marks a track's file missing for two days and puts its -// album on the wanted list, held at heldDaysAgo (0 for an open want) and -// last searched with nothing found. -func seedMissingWant(t *testing.T, h *handlers, trackID, albumID pgtype.UUID, group string, heldDaysAgo int) string { - t.Helper() - ctx := context.Background() - if _, err := h.pool.Exec(ctx, - `UPDATE tracks SET missing_since = now() - interval '2 days' WHERE id = $1`, trackID); err != nil { - t.Fatalf("mark missing: %v", err) - } - if _, err := h.pool.Exec(ctx, `DELETE FROM wants WHERE release_group_mbid = $1`, group); err != nil { - t.Fatalf("clear want: %v", err) - } - var id pgtype.UUID - if err := h.pool.QueryRow(ctx, - `INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id, - wanted_at, fulfilled_at, searched_at, search_outcome) - VALUES ($1, 'artist-'||$1, 'Artist', 'Album '||$1, 'library', $2, - now() - interval '30 days', - CASE WHEN $3::int > 0 THEN now() - make_interval(days => $3::int) END, - now() - interval '1 hour', 'nothing') - RETURNING id`, group, albumID, heldDaysAgo).Scan(&id); err != nil { - t.Fatalf("insert want: %v", err) - } - return uuidToString(id) -} - -// A folder's album that was held before its files went is not wanted back -// yet (every library album is on the list, held); an open want comes with -// its search, so the Missing page can show it and act on it. -func TestListMissingTracks_WantState(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - admin := seedUser(t, pool, "admin", "pw", true) - - heldTrack, _ := seedTrackOnDisk(t, h, "missheld") - openTrack, _ := seedTrackOnDisk(t, h, "missopen") - seedMissingWant(t, h, heldTrack.ID, heldTrack.AlbumID, "rg-missing-held", 10) - openID := seedMissingWant(t, h, openTrack.ID, openTrack.AlbumID, "rg-missing-open", 0) - - req := withUser(httptest.NewRequest(http.MethodGet, "/api/admin/library/missing", nil), admin) - w := httptest.NewRecorder() - h.handleListMissingTracks(w, req) - if w.Code != http.StatusOK { - t.Fatalf("status %d: %s", w.Code, w.Body.String()) - } - var resp adminMissingResponse - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if len(resp.Groups) != 2 { - t.Fatalf("groups = %d, want 2", len(resp.Groups)) - } - byTitle := map[string]missingGroupView{} - for _, g := range resp.Groups { - byTitle[g.Tracks[0].Title] = g - } - - if r := byTitle["AdmQ Track missheld"].Reacquisition; r != nil { - t.Errorf("held before the loss: reacquisition = %+v, want none", r) - } - r := byTitle["AdmQ Track missopen"].Reacquisition - if r == nil || r.WantedAt == nil || r.HeldAt != nil { - t.Fatalf("open want: reacquisition = %+v, want wanted and not held", r) - } - if r.Want == nil || r.Want.ID != openID { - t.Fatalf("open want: want = %+v, want id %s", r.Want, openID) - } - if r.Want.Search == nil || r.Want.Search.Outcome != "nothing" { - t.Errorf("open want: search = %+v, want outcome nothing", r.Want.Search) - } -} diff --git a/internal/api/admin_lookups.go b/internal/api/admin_lookups.go new file mode 100644 index 00000000..d66c897f --- /dev/null +++ b/internal/api/admin_lookups.go @@ -0,0 +1,48 @@ +package api + +import ( + "encoding/json" + "net/http" + + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/lookups" +) + +// lookupSettingsBody is the wire shape for GET and PUT +// /api/admin/lookup-settings: the switches for the outside lookups no +// metadata source covers. +type lookupSettingsBody struct { + ListenBrainzSimilarity bool `json:"listenbrainz_similarity"` + MusicBrainzTrackLists bool `json:"musicbrainz_track_lists"` +} + +func lookupSettingsBodyOf(s lookups.Settings) lookupSettingsBody { + return lookupSettingsBody{ + ListenBrainzSimilarity: s.ListenBrainzSimilarity, + MusicBrainzTrackLists: s.MusicBrainzTrackLists, + } +} + +// handleGetLookupSettings implements GET /api/admin/lookup-settings. +func (h *handlers) handleGetLookupSettings(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, lookupSettingsBodyOf(h.lookupSettings.Get())) +} + +// handleUpdateLookupSettings implements PUT /api/admin/lookup-settings. A +// whole-row write: a switch the body leaves out is saved as off. +func (h *handlers) handleUpdateLookupSettings(w http.ResponseWriter, r *http.Request) { + var req lookupSettingsBody + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON")) + return + } + saved, err := h.lookupSettings.Set(r.Context(), lookups.Settings{ + ListenBrainzSimilarity: req.ListenBrainzSimilarity, + MusicBrainzTrackLists: req.MusicBrainzTrackLists, + }) + if err != nil { + writeErrWithLog(w, h.logger, "admin lookup settings: update failed", apierror.Internal(err)) + return + } + writeJSON(w, http.StatusOK, lookupSettingsBodyOf(saved)) +} diff --git a/internal/api/admin_loudness.go b/internal/api/admin_loudness.go index 2e022651..18bc2a1e 100644 --- a/internal/api/admin_loudness.go +++ b/internal/api/admin_loudness.go @@ -5,8 +5,8 @@ import ( "errors" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/library" ) // loudnessCoverageResp is the wire shape for GET /api/admin/library/loudness. diff --git a/internal/api/admin_network.go b/internal/api/admin_network.go index b37d73d3..ad22b165 100644 --- a/internal/api/admin_network.go +++ b/internal/api/admin_network.go @@ -5,9 +5,9 @@ import ( "errors" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/netsettings" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/netsettings" ) type networkSettingsResp struct { diff --git a/internal/api/admin_notification_email.go b/internal/api/admin_notification_email.go index 3e750e5e..b2ddca20 100644 --- a/internal/api/admin_notification_email.go +++ b/internal/api/admin_notification_email.go @@ -5,9 +5,9 @@ import ( "errors" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) // notificationEmailBody is the wire shape for GET and PUT diff --git a/internal/api/admin_provider_sources.go b/internal/api/admin_provider_sources.go new file mode 100644 index 00000000..02825b00 --- /dev/null +++ b/internal/api/admin_provider_sources.go @@ -0,0 +1,132 @@ +package api + +import ( + "encoding/json" + "errors" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/providers" +) + +// The admin cards for outside sources, Cover sources and Tag sources, run +// on these. Each family's handlers pass their own providers.Service, so the +// two cards answer in one shape and share no rows. + +// providerSourceResp is one provider in a sources list. +type providerSourceResp struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + RequiresAPIKey bool `json:"requires_api_key"` + Supports []string `json:"supports"` + Enabled bool `json:"enabled"` + APIKeySet bool `json:"api_key_set"` + DisplayOrder int32 `json:"display_order"` + Testable bool `json:"testable"` +} + +func providerSourceRespFrom(info providers.Info) providerSourceResp { + supports := info.Supports + if supports == nil { + supports = []string{} + } + return providerSourceResp{ + ID: info.ID, + DisplayName: info.DisplayName, + RequiresAPIKey: info.RequiresAPIKey, + Supports: supports, + Enabled: info.Enabled, + APIKeySet: info.APIKeySet, + DisplayOrder: info.DisplayOrder, + Testable: info.Testable, + } +} + +type providerSourcesListResp struct { + Providers []providerSourceResp `json:"providers"` + SourcesVersion int32 `json:"sources_version"` +} + +// updateProviderSourceReq is the PATCH body. A nil field is left as it +// is; an empty api_key clears the key. +type updateProviderSourceReq struct { + Enabled *bool `json:"enabled,omitempty"` + APIKey *string `json:"api_key,omitempty"` +} + +type updateProviderSourceResp struct { + providerSourceResp + VersionBumped bool `json:"version_bumped"` +} + +// testProviderSourceResp is a Test-button result. It answers 200 whether +// or not the test passed: the result is data, not an error. +type testProviderSourceResp struct { + OK bool `json:"ok"` + DurationMs int64 `json:"duration_ms,omitempty"` + Error string `json:"error,omitempty"` +} + +var errNoSuchProvider = apierror.New(http.StatusNotFound, "not_found", "no such provider") + +// listProviderSources answers GET /api/admin/{family}-sources. +func listProviderSources(w http.ResponseWriter, svc *providers.Service) { + infos := svc.ListProviderInfo() + out := providerSourcesListResp{ + Providers: make([]providerSourceResp, 0, len(infos)), + SourcesVersion: svc.CurrentVersion(), + } + for _, info := range infos { + out.Providers = append(out.Providers, providerSourceRespFrom(info)) + } + writeJSON(w, http.StatusOK, out) +} + +// updateProviderSource answers PATCH /api/admin/{family}-sources/{provider_id} +// with the provider as it now stands. +func (h *handlers) updateProviderSource(w http.ResponseWriter, r *http.Request, svc *providers.Service) { + id := chi.URLParam(r, "provider_id") + var body updateProviderSourceReq + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeErr(w, apierror.BadRequest("bad_body", "invalid JSON")) + return + } + bumped, err := svc.UpdateProvider(r.Context(), id, providers.UpdatePatch{Enabled: body.Enabled, APIKey: body.APIKey}) + if err != nil { + if errors.Is(err, providers.ErrProviderNotFound) { + writeErr(w, errNoSuchProvider) + return + } + h.logger.Error("admin: update provider source", "id", id, "err", err) + writeErr(w, apierror.InternalMsg("update failed", err)) + return + } + var found providerSourceResp + for _, info := range svc.ListProviderInfo() { + if info.ID == id { + found = providerSourceRespFrom(info) + break + } + } + writeJSON(w, http.StatusOK, updateProviderSourceResp{providerSourceResp: found, VersionBumped: bumped}) +} + +// testProviderSource answers POST /api/admin/{family}-sources/{provider_id}/test. +func testProviderSource(w http.ResponseWriter, r *http.Request, svc *providers.Service) { + id := chi.URLParam(r, "provider_id") + start := time.Now() + err := svc.TestProvider(r.Context(), id) + duration := time.Since(start).Milliseconds() + switch { + case err == nil: + writeJSON(w, http.StatusOK, testProviderSourceResp{OK: true, DurationMs: duration}) + case errors.Is(err, providers.ErrProviderNotFound): + writeErr(w, errNoSuchProvider) + default: + // Not testable, or the test failed. + writeJSON(w, http.StatusOK, testProviderSourceResp{OK: false, DurationMs: duration, Error: err.Error()}) + } +} diff --git a/internal/api/admin_quarantine.go b/internal/api/admin_quarantine.go index 07ab3202..7c07b61d 100644 --- a/internal/api/admin_quarantine.go +++ b/internal/api/admin_quarantine.go @@ -8,9 +8,10 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/quarantine" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/quarantine" ) // adminQueueRowView is a single aggregated row in the admin queue response. @@ -48,7 +49,7 @@ func (h *handlers) handleListAdminQuarantine(w http.ResponseWriter, r *http.Requ rows, err := h.quarantine.ListAdminQueue(r.Context()) if err != nil { h.logger.Error("admin: list quarantine", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } out := make([]adminQueueRowView, 0, len(rows)) @@ -90,22 +91,22 @@ type actionResultView struct { func (h *handlers) handleResolveQuarantine(w http.ResponseWriter, r *http.Request) { admin, ok := auth.UserFromContext(r.Context()) if !ok { - writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") + writeErr(w, apierror.ErrUnauthorized) return } id, ok := parseUUID(chi.URLParam(r, "track_id")) if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } action, err := h.quarantine.Resolve(r.Context(), id, admin.ID) if err != nil { if errors.Is(err, quarantine.ErrTrackNotFound) { - writeAdminJSONErr(w, http.StatusNotFound, "track_not_found") + writeErr(w, apierror.NotFound("track")) return } h.logger.Error("admin: resolve quarantine", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } // Broadcast: affects every user who'd flagged this track. @@ -121,18 +122,17 @@ func (h *handlers) handleResolveQuarantine(w http.ResponseWriter, r *http.Reques func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Request) { admin, ok := auth.UserFromContext(r.Context()) if !ok { - writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") + writeErr(w, apierror.ErrUnauthorized) return } id, ok := parseUUID(chi.URLParam(r, "track_id")) if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } action, err := h.quarantine.DeleteFile(r.Context(), id, admin.ID) if err != nil { - // Written in the enveloped shape, not writeAdminJSONErr's bare code: - // the message is the part that tells an admin which directory and uid. + // The message is the part that tells an admin which directory and uid. if apiErr, ok := fileRemoveAPIError(err); ok { logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id)) writeErr(w, apiErr) @@ -140,10 +140,10 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req } switch { case errors.Is(err, quarantine.ErrTrackNotFound): - writeAdminJSONErr(w, http.StatusNotFound, "track_not_found") + writeErr(w, apierror.NotFound("track")) default: h.logger.Error("admin: delete file", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "file_delete_failed") + writeErr(w, apierror.New(http.StatusInternalServerError, "file_delete_failed", "the file could not be deleted")) } return } @@ -156,6 +156,48 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req }) } +// handleRemoveQuarantineFile implements POST +// /api/admin/quarantine/{track_id}/remove-file: the reported file goes and the +// track stays, missing, until a good copy lands in the library. Its reports +// and open playback errors are settled with it. +// +// Errors: 404 track_not_found; 409 library_not_writable / 500 +// file_delete_failed when the file could not be removed. +func (h *handlers) handleRemoveQuarantineFile(w http.ResponseWriter, r *http.Request) { + admin, ok := auth.UserFromContext(r.Context()) + if !ok { + writeErr(w, apierror.ErrUnauthorized) + return + } + id, ok := parseUUID(chi.URLParam(r, "track_id")) + if !ok { + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) + return + } + action, err := h.quarantine.RemoveFile(r.Context(), id, admin.ID) + if err != nil { + if apiErr, ok := fileRemoveAPIError(err); ok { + logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id)) + writeErr(w, apiErr) + return + } + switch { + case errors.Is(err, quarantine.ErrTrackNotFound): + writeErr(w, apierror.NotFound("track")) + default: + h.logger.Error("admin: remove reported file", "err", err) + writeErr(w, apierror.New(http.StatusInternalServerError, "file_delete_failed", "the file could not be deleted")) + } + return + } + // Broadcast: every listener's report on it is cleared. + h.publishQuarantineEvent("quarantine.resolved", pgtype.UUID{}, id, true) + writeJSON(w, http.StatusOK, actionResultView{ + ActionID: uuidToString(action.ID), + AffectedUsers: action.AffectedUsers, + }) +} + // actionLogView is the row shape returned by GET /api/admin/quarantine/actions. type actionLogView struct { ID string `json:"id"` @@ -187,7 +229,7 @@ func (h *handlers) handleListQuarantineActions(w http.ResponseWriter, r *http.Re rows, err := dbq.New(h.pool).ListQuarantineActions(r.Context(), limit) if err != nil { h.logger.Error("admin: list actions", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } out := make([]actionLogView, 0, len(rows)) diff --git a/internal/api/admin_quarantine_test.go b/internal/api/admin_quarantine_test.go index e412adfd..c2cef512 100644 --- a/internal/api/admin_quarantine_test.go +++ b/internal/api/admin_quarantine_test.go @@ -13,8 +13,8 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // newAdminQuarantineRouter builds a test chi router with the five admin @@ -96,7 +96,6 @@ func seedTrackOnDisk(t *testing.T, h *handlers, unique string) (dbq.Track, strin func TestListAdminQuarantine_AggregatedShape(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - resetRequests(t, h) alice := seedUser(t, pool, "alice", "pw", false) bob := seedUser(t, pool, "bob", "pw", false) @@ -136,7 +135,6 @@ func TestListAdminQuarantine_AggregatedShape(t *testing.T) { func TestResolveQuarantine_HappyPath(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - resetRequests(t, h) alice := seedUser(t, pool, "alice", "pw", false) bob := seedUser(t, pool, "bob", "pw", false) @@ -180,7 +178,6 @@ func TestResolveQuarantine_HappyPath(t *testing.T) { func TestDeleteQuarantineFile_HappyPath(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - resetRequests(t, h) alice := seedUser(t, pool, "alice", "pw", false) admin := seedUser(t, pool, "admin", "pw", true) @@ -209,33 +206,3 @@ func TestDeleteQuarantineFile_HappyPath(t *testing.T) { t.Error("track row still exists") } } - -// TestQuarantineAdminEndpointsRequire403ForNonAdmin verifies all five admin -// endpoints reject non-admin callers with 403. -func TestQuarantineAdminEndpointsRequire403ForNonAdmin(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - resetRequests(t, h) - - nonAdmin := seedUser(t, pool, "regular", "pw", false) - fakeID := "00000000-0000-0000-0000-000000000001" - - cases := []struct { - method string - path string - }{ - {http.MethodGet, "/api/admin/quarantine"}, - {http.MethodPost, "/api/admin/quarantine/" + fakeID + "/resolve"}, - {http.MethodPost, "/api/admin/quarantine/" + fakeID + "/delete-file"}, - {http.MethodGet, "/api/admin/quarantine/actions"}, - } - for _, tc := range cases { - tc := tc - t.Run(tc.method+" "+tc.path, func(t *testing.T) { - w := doAdminQuarantineReq(t, h, tc.method, tc.path, nil, nonAdmin) - if w.Code != http.StatusForbidden { - t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String()) - } - }) - } -} diff --git a/internal/api/admin_reacquisition.go b/internal/api/admin_reacquisition.go deleted file mode 100644 index 01d841c1..00000000 --- a/internal/api/admin_reacquisition.go +++ /dev/null @@ -1,78 +0,0 @@ -package api - -import ( - "encoding/json" - "errors" - "net/http" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition" -) - -// reacquisitionSettingsResp is the admin card's payload. -// -// Carries more than the stored settings: [UnnameableAlbums] is the count of -// albums with missing files that can never be wanted automatically because -// neither they nor their artist has an MBID. The card states that number -// rather than leaving an admin to wonder why some rows never get wanted — -// a feature that silently does nothing for part of its input reads as broken. -type reacquisitionSettingsResp struct { - Enabled bool `json:"enabled"` - GraceHours int32 `json:"grace_hours"` - MaxPerPass int32 `json:"max_per_pass"` - - UnnameableAlbums int64 `json:"unnameable_albums"` -} - -// handleGetReacquisitionSettings implements GET -// /api/admin/library/reacquisition. -func (h *handlers) handleGetReacquisitionSettings(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, h.reacquisitionPayload(r)) -} - -// handleUpdateReacquisitionSettings implements PUT -// /api/admin/library/reacquisition. -func (h *handlers) handleUpdateReacquisitionSettings(w http.ResponseWriter, r *http.Request) { - var req reacquisitionSettingsResp - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON")) - return - } - _, err := h.reacqSettings.Set(r.Context(), reacquisition.Settings{ - Enabled: req.Enabled, - GraceHours: req.GraceHours, - MaxPerPass: req.MaxPerPass, - }) - if err != nil { - // The Go-side validation mirrors migration 0056's CHECKs so the - // operator gets a readable message naming the field, rather than a - // constraint-violation string leaking through as a 500. - if errors.Is(err, reacquisition.ErrOutOfRange) { - writeErr(w, apierror.BadRequest("invalid_setting", err.Error())) - return - } - writeErrWithLog(w, h.logger, "admin reacquisition: update failed", apierror.Internal(err)) - return - } - // Echo the payload recomputed under the new values so the card reflects - // what it just did without a reload. - writeJSON(w, http.StatusOK, h.reacquisitionPayload(r)) -} - -func (h *handlers) reacquisitionPayload(r *http.Request) reacquisitionSettingsResp { - cur := h.reacqSettings.Get() - out := reacquisitionSettingsResp{ - Enabled: cur.Enabled, - GraceHours: cur.GraceHours, - MaxPerPass: cur.MaxPerPass, - } - // Best-effort: the settings are the point of this endpoint, and failing - // the whole card because a count query hiccuped would be the wrong trade. - if n, err := dbq.New(h.pool).CountAlbumsMissingWithoutMbid(r.Context()); err == nil { - out.UnnameableAlbums = n - } else { - h.logger.Warn("admin reacquisition: unnameable count failed", "err", err) - } - return out -} diff --git a/internal/api/admin_recommendation_trends.go b/internal/api/admin_recommendation_trends.go index 4d306b9c..d05e46fc 100644 --- a/internal/api/admin_recommendation_trends.go +++ b/internal/api/admin_recommendation_trends.go @@ -11,8 +11,8 @@ import ( "strconv" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) const ( diff --git a/internal/api/admin_recommendation_trends_test.go b/internal/api/admin_recommendation_trends_test.go index 278f9cdb..262302b1 100644 --- a/internal/api/admin_recommendation_trends_test.go +++ b/internal/api/admin_recommendation_trends_test.go @@ -11,7 +11,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func date(s string) pgtype.Date { diff --git a/internal/api/admin_recommendation_tuning.go b/internal/api/admin_recommendation_tuning.go index d5e69799..b2109050 100644 --- a/internal/api/admin_recommendation_tuning.go +++ b/internal/api/admin_recommendation_tuning.go @@ -12,9 +12,9 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation" - "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/recommendation" + "github.com/Fabled-Sword/minstrel/internal/recsettings" ) // weightsResp is one weight profile on the wire, keyed by the same @@ -67,30 +67,15 @@ func tasteRespFrom(t recsettings.TasteTuning) tasteTuningResp { } } -// discoverTuningResp is the Discover scope on the wire. -type discoverTuningResp struct { - TagOverlapWeight float64 `json:"tag_overlap_weight"` - SnoozeDays float64 `json:"snooze_days"` -} - -func discoverRespFrom(d recsettings.DiscoverTuning) discoverTuningResp { - return discoverTuningResp{ - TagOverlapWeight: d.TagOverlapWeight, - SnoozeDays: d.SnoozeDays, - } -} - // tuningSnapshot is both the GET response and the post-mutation echo: // current values alongside shipped defaults so the card can mark // which knobs deviate. type tuningSnapshot struct { Profiles map[string]weightsResp `json:"profiles"` Taste tasteTuningResp `json:"taste"` - Discover discoverTuningResp `json:"discover"` Shipped struct { Profiles map[string]weightsResp `json:"profiles"` Taste tasteTuningResp `json:"taste"` - Discover discoverTuningResp `json:"discover"` } `json:"shipped"` } @@ -102,14 +87,12 @@ func (h *handlers) tuningSnapshot() tuningSnapshot { recsettings.ScopeSongsLike: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeSongsLike)), } out.Taste = tasteRespFrom(h.recSettings.Taste()) - out.Discover = discoverRespFrom(h.recSettings.Discover()) out.Shipped.Profiles = map[string]weightsResp{ recsettings.ScopeRadio: weightsRespFrom(recsettings.ShippedRadioWeights()), recsettings.ScopeDailyMix: weightsRespFrom(recsettings.ShippedDailyMixWeights()), recsettings.ScopeSongsLike: weightsRespFrom(recsettings.ShippedSongsLikeWeights()), } out.Shipped.Taste = tasteRespFrom(recsettings.ShippedTasteTuning()) - out.Shipped.Discover = discoverRespFrom(recsettings.ShippedDiscoverTuning()) return out } @@ -143,8 +126,6 @@ func (h *handlers) handlePatchRecommendationTuning(w http.ResponseWriter, r *htt switch scope { case recsettings.ScopeTaste: err = h.recSettings.UpdateTaste(r.Context(), body.Values) - case recsettings.ScopeDiscover: - err = h.recSettings.UpdateDiscover(r.Context(), body.Values) default: err = h.recSettings.UpdateProfile(r.Context(), scope, body.Values) } diff --git a/internal/api/admin_recommendation_tuning_test.go b/internal/api/admin_recommendation_tuning_test.go index 4c6bba88..bd3d16d4 100644 --- a/internal/api/admin_recommendation_tuning_test.go +++ b/internal/api/admin_recommendation_tuning_test.go @@ -9,7 +9,7 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings" + "github.com/Fabled-Sword/minstrel/internal/recsettings" ) func newTuningRouter(h *handlers) chi.Router { diff --git a/internal/api/admin_requests.go b/internal/api/admin_requests.go deleted file mode 100644 index 4fd395eb..00000000 --- a/internal/api/admin_requests.go +++ /dev/null @@ -1,190 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "strconv" - - "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - "git.fabledsword.com/bvandeusen/minstrel/internal/requests" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" -) - -// validRequestStatuses is the set of allowed values for the ?status= param. -var validRequestStatuses = map[string]bool{ - "pending": true, - "approved": true, - "rejected": true, - "completed": true, - "failed": true, -} - -// handleListAdminRequests implements GET /api/admin/requests. -// ?status= defaults to "pending"; ?limit= defaults to 50, max 200. -func (h *handlers) handleListAdminRequests(w http.ResponseWriter, r *http.Request) { - status := r.URL.Query().Get("status") - if status == "" { - status = "pending" - } - if !validRequestStatuses[status] { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_status") - return - } - - limitStr := r.URL.Query().Get("limit") - limit := 50 - if limitStr != "" { - v, err := strconv.Atoi(limitStr) - if err != nil || v <= 0 { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_limit") - return - } - if v > 200 { - v = 200 - } - limit = v - } - - rows, err := h.requests.ListByStatus(r.Context(), status, int32(limit)) - if err != nil { - h.logger.Error("admin: list requests", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") - return - } - - q := dbq.New(h.pool) - names := requesterNames(r.Context(), q, rows) - out := make([]requestView, 0, len(rows)) - for _, row := range rows { - v := requestViewFrom(row) - v.Username = names[row.UserID] - fillProgress(r.Context(), q, row, &v) - out = append(out, v) - } - writeJSON(w, http.StatusOK, out) -} - -// requesterNames maps each request's user id to that user's username, in one -// query for the whole page. Like fillProgress, a failed lookup is swallowed: -// the names are a reporting nicety, and the page falls back to the id. -func requesterNames(ctx context.Context, q *dbq.Queries, rows []dbq.Request) map[pgtype.UUID]string { - ids := make([]pgtype.UUID, 0, len(rows)) - for _, row := range rows { - ids = append(ids, row.UserID) - } - names := make(map[pgtype.UUID]string, len(rows)) - users, err := q.ListUsernamesByIDs(ctx, ids) - if err != nil { - return names - } - for _, u := range users { - names[u.ID] = u.Username - } - return names -} - -// approveRequestBody is the optional JSON body for POST -// /api/admin/requests/:id/approve. profile_id picks the release-type profile an -// artist request is followed on; omitted, the default profile. -type approveRequestBody struct { - ProfileID string `json:"profile_id"` -} - -// handleApproveRequest implements POST /api/admin/requests/:id/approve. The -// request goes on the wanted list: an album or track request -// wants its album, an artist request follows the artist. -func (h *handlers) handleApproveRequest(w http.ResponseWriter, r *http.Request) { - admin, ok := auth.UserFromContext(r.Context()) - if !ok { - writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") - return - } - - id, ok := parseUUID(chi.URLParam(r, "id")) - if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") - return - } - - var body approveRequestBody - // Body is entirely optional; ignore decode errors. - _ = json.NewDecoder(r.Body).Decode(&body) - var profile pgtype.UUID - if body.ProfileID != "" { - if profile, ok = parseUUID(body.ProfileID); !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_profile") - return - } - } - - row, err := h.requests.Approve(r.Context(), id, admin.ID, profile) - if err != nil { - switch { - case errors.Is(err, requests.ErrNotFound): - writeAdminJSONErr(w, http.StatusNotFound, "request_not_found") - case errors.Is(err, requests.ErrNotPending): - writeAdminJSONErr(w, http.StatusConflict, "request_not_pending") - case errors.Is(err, wanted.ErrProfileNotFound): - writeAdminJSONErr(w, http.StatusBadRequest, "profile_not_found") - case errors.Is(err, wanted.ErrNotFollowable): - writeAdminJSONErr(w, http.StatusBadRequest, "not_followable") - default: - h.logger.Error("admin: approve request", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") - } - return - } - - h.notifyRequestDecided(r.Context(), notifications.KindRequestApproved, admin, row, "") - h.publishRequestStatusChanged(row) - writeJSON(w, http.StatusOK, requestViewFrom(row)) -} - -// rejectRequestBody is the optional JSON body for POST -// /api/admin/requests/:id/reject. -type rejectRequestBody struct { - Notes string `json:"notes"` -} - -// handleRejectRequest implements POST /api/admin/requests/:id/reject. -func (h *handlers) handleRejectRequest(w http.ResponseWriter, r *http.Request) { - admin, ok := auth.UserFromContext(r.Context()) - if !ok { - writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") - return - } - - id, ok := parseUUID(chi.URLParam(r, "id")) - if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") - return - } - - var body rejectRequestBody - _ = json.NewDecoder(r.Body).Decode(&body) - - row, err := h.requests.Reject(r.Context(), id, admin.ID, body.Notes) - if err != nil { - switch { - case errors.Is(err, requests.ErrNotFound): - writeAdminJSONErr(w, http.StatusNotFound, "request_not_found") - case errors.Is(err, requests.ErrNotPending): - writeAdminJSONErr(w, http.StatusConflict, "request_not_pending") - default: - h.logger.Error("admin: reject request", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") - } - return - } - - h.notifyRequestDecided(r.Context(), notifications.KindRequestRejected, admin, row, body.Notes) - h.publishRequestStatusChanged(row) - writeJSON(w, http.StatusOK, requestViewFrom(row)) -} diff --git a/internal/api/admin_requests_test.go b/internal/api/admin_requests_test.go deleted file mode 100644 index 734eadfc..00000000 --- a/internal/api/admin_requests_test.go +++ /dev/null @@ -1,335 +0,0 @@ -package api - -import ( - "bytes" - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" -) - -// newAdminRequestsRouter builds a test chi router with the three admin/requests -// endpoints. RequireAdmin middleware is applied. Tests inject a user into -// context directly (skipping RequireUser). -func newAdminRequestsRouter(h *handlers) chi.Router { - r := chi.NewRouter() - r.Route("/api/admin", func(admin chi.Router) { - admin.Use(auth.RequireAdmin()) - admin.Get("/requests", h.handleListAdminRequests) - admin.Post("/requests/{id}/approve", h.handleApproveRequest) - admin.Post("/requests/{id}/reject", h.handleRejectRequest) - }) - return r -} - -// doAdminRequestReq fires an HTTP request at the admin requests router with -// the given user injected into context (bypassing RequireUser). -func doAdminRequestReq(t *testing.T, h *handlers, method, path string, body []byte, user dbq.User) *httptest.ResponseRecorder { - t.Helper() - var reqBody *bytes.Buffer - if body != nil { - reqBody = bytes.NewBuffer(body) - } else { - reqBody = bytes.NewBuffer(nil) - } - req := httptest.NewRequest(method, path, reqBody) - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - req = withUser(req, user) - w := httptest.NewRecorder() - newAdminRequestsRouter(h).ServeHTTP(w, req) - return w -} - -// seedPendingArtistRequest creates a pending artist-kind request row -// for the given user and returns its parsed requestView. -func seedPendingArtistRequest(t *testing.T, h *handlers, user dbq.User, artistMBID, artistName string) requestView { - t.Helper() - return createArtistRequest(t, h, user, artistMBID, artistName) -} - -// TestHandleListAdminRequests_DefaultStatus_Pending seeds 2 pending + 1 -// rejected and verifies that GET without ?status returns only the 2 pending -// rows. -func TestHandleListAdminRequests_DefaultStatus_Pending(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, h.pool, "alice", "pw", false) - admin := seedUser(t, h.pool, "admin", "pw", true) - - createArtistRequest(t, h, alice, "mbid-pending-1", "Pending Artist 1") - createArtistRequest(t, h, alice, "mbid-pending-2", "Pending Artist 2") - - // Reject one request directly via service. - rv3 := createArtistRequest(t, h, alice, "mbid-reject-1", "Reject Me") - _, err := h.requests.Reject(context.Background(), rv3.ID, admin.ID, "test") - if err != nil { - t.Fatalf("reject seed: %v", err) - } - - w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests", nil, admin) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - - var results []requestView - if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if len(results) != 2 { - t.Fatalf("len(results) = %d, want 2 (pending only)", len(results)) - } - for _, rv := range results { - if rv.Status != "pending" { - t.Errorf("result status = %q, want pending", rv.Status) - } - if rv.Username != alice.Username { - t.Errorf("result username = %q, want %q (the requester)", rv.Username, alice.Username) - } - } -} - -// TestHandleListAdminRequests_StatusFilter verifies GET ?status=rejected -// returns only rejected rows. -func TestHandleListAdminRequests_StatusFilter(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, h.pool, "alice", "pw", false) - admin := seedUser(t, h.pool, "admin", "pw", true) - - createArtistRequest(t, h, alice, "mbid-pending-f1", "Pending Filter 1") - - rv2 := createArtistRequest(t, h, alice, "mbid-rejected-f1", "Rejected Filter 1") - _, err := h.requests.Reject(context.Background(), rv2.ID, admin.ID, "") - if err != nil { - t.Fatalf("reject seed: %v", err) - } - - w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=rejected", nil, admin) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - - var results []requestView - if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if len(results) != 1 { - t.Fatalf("len(results) = %d, want 1 rejected row", len(results)) - } - if results[0].Status != "rejected" { - t.Errorf("status = %q, want rejected", results[0].Status) - } -} - -// TestHandleListAdminRequests_BadStatus_400 verifies GET with an invalid -// ?status returns 400. -func TestHandleListAdminRequests_BadStatus_400(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - admin := seedUser(t, h.pool, "admin", "pw", true) - - w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=garbage", nil, admin) - if w.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) - } - var resp map[string]string - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if resp["error"] != "invalid_status" { - t.Errorf("error = %q, want invalid_status", resp["error"]) - } -} - -// TestHandleApproveRequest_NotPending_409 pre-rejects a row and verifies -// POST /approve → 409 request_not_pending. -func TestHandleApproveRequest_NotPending_409(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, h.pool, "alice", "pw", false) - admin := seedUser(t, h.pool, "admin", "pw", true) - - rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-notpending", "Not Pending") - - // Pre-reject the row. - _, err := h.requests.Reject(context.Background(), rv.ID, admin.ID, "pre-rejected") - if err != nil { - t.Fatalf("pre-reject: %v", err) - } - - w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin) - if w.Code != http.StatusConflict { - t.Fatalf("status = %d, want 409; body = %s", w.Code, w.Body.String()) - } - var resp map[string]string - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if resp["error"] != "request_not_pending" { - t.Errorf("error = %q, want request_not_pending", resp["error"]) - } -} - -// TestHandleRejectRequest_HappyPath verifies POST /reject with notes returns -// 200 and the row transitions to rejected with notes saved. -func TestHandleRejectRequest_HappyPath(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, h.pool, "alice", "pw", false) - admin := seedUser(t, h.pool, "admin", "pw", true) - - rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject", "Reject Me") - - body := []byte(`{"notes":"low-quality release; will look for the remaster"}`) - w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", body, admin) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - - var got requestView - if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if got.Status != "rejected" { - t.Errorf("status = %q, want rejected", got.Status) - } - if got.Notes == nil || *got.Notes != "low-quality release; will look for the remaster" { - t.Errorf("notes = %v, want expected string", got.Notes) - } -} - -// TestHandleRejectRequest_NoNotes_OK verifies POST /reject with empty body -// returns 200 (notes are optional). -func TestHandleRejectRequest_NoNotes_OK(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, h.pool, "alice", "pw", false) - admin := seedUser(t, h.pool, "admin", "pw", true) - - rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject-nonotes", "Reject No Notes") - - w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", nil, admin) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - - var got requestView - if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if got.Status != "rejected" { - t.Errorf("status = %q, want rejected", got.Status) - } -} - -// TestAdminRequestsEndpoints_NonAdmin403 is a table-driven test verifying that -// all 3 admin request endpoints reject non-admin users with 403. -func TestAdminRequestsEndpoints_NonAdmin403(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - nonAdmin := seedUser(t, h.pool, "regular", "pw", false) - - // Use a placeholder UUID for the ID endpoints. - fakeID := "00000000-0000-0000-0000-000000000001" - - cases := []struct { - method string - path string - body []byte - }{ - {http.MethodGet, "/api/admin/requests", nil}, - {http.MethodPost, "/api/admin/requests/" + fakeID + "/approve", nil}, - {http.MethodPost, "/api/admin/requests/" + fakeID + "/reject", nil}, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.method+" "+tc.path, func(t *testing.T) { - w := doAdminRequestReq(t, h, tc.method, tc.path, tc.body, nonAdmin) - if w.Code != http.StatusForbidden { - t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String()) - } - var resp map[string]string - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if resp["error"] != "not_authorized" { - t.Errorf("error = %q, want not_authorized", resp["error"]) - } - }) - } -} - -// TestHandleApproveRequest_AlbumBecomesAWant: approving an album request puts -// its release group on the wanted list, as the requester's. -func TestHandleApproveRequest_AlbumBecomesAWant(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - alice := seedUser(t, h.pool, "alice", "pw", false) - admin := seedUser(t, h.pool, "admin", "pw", true) - - w := doCreateRequest(h, alice, `{"kind":"album","artist_mbid":"artist-x","artist_name":"Gorillaz","album_mbid":"group-x","album_title":"Demon Days"}`) - if w.Code != http.StatusCreated { - t.Fatalf("create: %d %s", w.Code, w.Body.String()) - } - var rv requestView - _ = json.Unmarshal(w.Body.Bytes(), &rv) - - resp := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin) - if resp.Code != http.StatusOK { - t.Fatalf("approve: %d %s", resp.Code, resp.Body.String()) - } - want, err := dbq.New(h.pool).GetWantByReleaseGroup(context.Background(), "group-x") - if err != nil { - t.Fatalf("no want recorded: %v", err) - } - if want.Title != "Demon Days" || want.CreatedBy != alice.ID || want.Reason != "request" { - t.Errorf("want = %+v", want) - } -} - -// TestHandleApproveRequest_ArtistOnTheChosenProfile: an artist request is -// followed on the profile the admin picked; an unknown profile is a 400. -func TestHandleApproveRequest_ArtistOnTheChosenProfile(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - alice := seedUser(t, h.pool, "alice", "pw", false) - admin := seedUser(t, h.pool, "admin", "pw", true) - ctx := context.Background() - - profile, err := dbq.New(h.pool).CreateReleaseTypeProfile(ctx, dbq.CreateReleaseTypeProfileParams{ - Name: "Albums only", PrimaryTypes: []string{"Album"}, SecondaryTypes: []string{}, - }) - if err != nil { - t.Fatal(err) - } - rv := seedPendingArtistRequest(t, h, alice, "artist-profiled", "Profiled") - path := "/api/admin/requests/" + uuidToString(rv.ID) + "/approve" - - if resp := doAdminRequestReq(t, h, http.MethodPost, path, []byte(`{"profile_id":"00000000-0000-4000-8000-000000000000"}`), admin); resp.Code != http.StatusBadRequest { - t.Fatalf("unknown profile: %d %s", resp.Code, resp.Body.String()) - } - body := []byte(`{"profile_id":"` + uuidToString(profile.ID) + `"}`) - if resp := doAdminRequestReq(t, h, http.MethodPost, path, body, admin); resp.Code != http.StatusOK { - t.Fatalf("approve: %d %s", resp.Code, resp.Body.String()) - } - f, err := dbq.New(h.pool).GetFollow(ctx, "artist-profiled") - if err != nil || f.ProfileID != profile.ID || !f.WantExisting { - t.Errorf("follow = %+v, %v: on Albums only, wanting what exists", f, err) - } -} diff --git a/internal/api/admin_scan.go b/internal/api/admin_scan.go index 93e3bf63..c5ff0557 100644 --- a/internal/api/admin_scan.go +++ b/internal/api/admin_scan.go @@ -8,9 +8,9 @@ import ( "github.com/jackc/pgx/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // scanStatusResp mirrors the scan_runs row on the wire. Stage tallies are diff --git a/internal/api/admin_scan_test.go b/internal/api/admin_scan_test.go index db76b8d9..e65a6f04 100644 --- a/internal/api/admin_scan_test.go +++ b/internal/api/admin_scan_test.go @@ -5,12 +5,11 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/auth" ) func newAdminScanRouter(h *handlers) chi.Router { @@ -24,9 +23,6 @@ func newAdminScanRouter(h *handlers) chi.Router { } func TestAdminScanStatus_NoRowReturnsEmpty(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rootscan", "pw", true) req := httptest.NewRequest(http.MethodGet, "/api/admin/scan/status", nil) @@ -46,9 +42,6 @@ func TestAdminScanStatus_NoRowReturnsEmpty(t *testing.T) { } func TestAdminScanStatus_RowReturnsValues(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rootscan2", "pw", true) if _, err := pool.Exec(context.Background(), ` @@ -81,9 +74,6 @@ func TestAdminScanStatus_RowReturnsValues(t *testing.T) { } func TestAdminTriggerScan_InFlightReturns409(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rootscan3", "pw", true) if _, err := pool.Exec(context.Background(), ` diff --git a/internal/api/admin_search.go b/internal/api/admin_search.go deleted file mode 100644 index aaebdb50..00000000 --- a/internal/api/admin_search.go +++ /dev/null @@ -1,340 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "slices" - "time" - - "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/release" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" -) - -// Searching for wants and grabbing releases: the schedule's -// settings, each want's candidates, and a person's Search, Grab and "never -// this one". - -// searchTimeout bounds a search a person waits on: a Prowlarr fanning out to -// many trackers can take most of a minute. -const searchTimeout = 2 * time.Minute - -type searchSettingsView struct { - AutoGrab bool `json:"auto_grab"` - SearchIntervalHours int32 `json:"search_interval_hours"` - AllowedQualities []string `json:"allowed_qualities"` - Tiers []release.TierInfo `json:"tiers"` - LastPassAt *string `json:"last_pass_at"` - LastPass json.RawMessage `json:"last_pass"` - // ImportRoot is the library folder new music is filed into; "" - // is the first of ScanPaths, the library's folders. - ImportRoot string `json:"import_root"` - ScanPaths []string `json:"scan_paths"` - // The download lifecycle: seed an imported download to this - // ratio or for this many days; give up on one nobody shares after this - // many hours. 0 is: remove once imported, no time limit, never. - SeedRatio float32 `json:"seed_ratio"` - SeedDays int32 `json:"seed_days"` - StallHours int32 `json:"stall_hours"` - // UpgradeUntil is the tier a held album is upgraded to; "" is - // no quality upgrades. - UpgradeUntil string `json:"upgrade_until"` -} - -func searchSettings(s dbq.AcquisitionSetting, roots []string) searchSettingsView { - v := searchSettingsView{ - AutoGrab: s.AutoGrab, SearchIntervalHours: s.SearchIntervalHours, - AllowedQualities: s.AllowedQualities, Tiers: release.Tiers, LastPass: s.LastPass, - ImportRoot: s.ImportRoot, ScanPaths: roots, - SeedRatio: s.SeedRatio, SeedDays: s.SeedDays, StallHours: s.StallHours, - UpgradeUntil: s.UpgradeUntil, - } - if v.ScanPaths == nil { - v.ScanPaths = []string{} - } - if v.AllowedQualities == nil { - v.AllowedQualities = []string{} - } - if len(v.LastPass) == 0 { - v.LastPass = json.RawMessage("{}") - } - if s.LastPassAt.Valid { - at := formatTimestamp(s.LastPassAt) - v.LastPassAt = &at - } - return v -} - -// handleGetSearchSettings implements GET /api/admin/acquisition/settings. -func (h *handlers) handleGetSearchSettings(w http.ResponseWriter, r *http.Request) { - s, err := dbq.New(h.pool).GetAcquisitionSettings(r.Context()) - if err != nil { - writeErrWithLog(w, h.logger, "admin search settings: get", apierror.Internal(err)) - return - } - writeJSON(w, http.StatusOK, searchSettings(s, h.importer.Roots())) -} - -type putSearchSettingsBody struct { - AutoGrab bool `json:"auto_grab"` - SearchIntervalHours int32 `json:"search_interval_hours"` - AllowedQualities []string `json:"allowed_qualities"` - ImportRoot string `json:"import_root"` - SeedRatio float32 `json:"seed_ratio"` - SeedDays int32 `json:"seed_days"` - StallHours int32 `json:"stall_hours"` - UpgradeUntil string `json:"upgrade_until"` -} - -// handlePutSearchSettings implements PUT /api/admin/acquisition/settings. -func (h *handlers) handlePutSearchSettings(w http.ResponseWriter, r *http.Request) { - var body putSearchSettingsBody - if !decodeBody(w, r, &body) { - return - } - if body.SearchIntervalHours < 0 || body.SearchIntervalHours > 720 { - writeErr(w, apierror.BadRequest("bad_interval", "search_interval_hours must be between 0 and 720")) - return - } - if len(body.AllowedQualities) == 0 { - writeErr(w, apierror.BadRequest("bad_quality", "allow at least one quality")) - return - } - for _, t := range body.AllowedQualities { - if !release.KnownTier(t) { - writeErr(w, apierror.BadRequest("bad_quality", "unknown quality "+t)) - return - } - } - if body.UpgradeUntil != "" && !release.KnownTier(body.UpgradeUntil) { - writeErr(w, apierror.BadRequest("bad_upgrade_until", "unknown quality "+body.UpgradeUntil)) - return - } - if body.ImportRoot != "" && !slices.Contains(h.importer.Roots(), body.ImportRoot) { - writeErr(w, apierror.BadRequest("bad_import_root", "file new music into one of the library's folders")) - return - } - if body.SeedRatio < 0 || body.SeedRatio > 100 || body.SeedDays < 0 || body.SeedDays > 365 || - body.StallHours < 0 || body.StallHours > 720 { - writeErr(w, apierror.BadRequest("bad_lifecycle", - "seed ratio must be 0 to 100, seed days 0 to 365 and stall hours 0 to 720")) - return - } - s, err := dbq.New(h.pool).UpdateAcquisitionSettings(r.Context(), dbq.UpdateAcquisitionSettingsParams{ - AutoGrab: body.AutoGrab, SearchIntervalHours: body.SearchIntervalHours, AllowedQualities: body.AllowedQualities, - ImportRoot: body.ImportRoot, SeedRatio: body.SeedRatio, SeedDays: body.SeedDays, StallHours: body.StallHours, - UpgradeUntil: body.UpgradeUntil, - }) - if err != nil { - writeErrWithLog(w, h.logger, "admin search settings: put", apierror.Internal(err)) - return - } - writeJSON(w, http.StatusOK, searchSettings(s, h.importer.Roots())) -} - -// candidateView is one release a want's last search found. -type candidateView struct { - Key string `json:"key"` - Name string `json:"name"` - InfoHash string `json:"info_hash"` - Indexer string `json:"indexer"` - SizeBytes int64 `json:"size_bytes"` - Seeders int32 `json:"seeders"` - FilesCount int32 `json:"files_count"` - Format string `json:"format"` - Quality string `json:"quality"` - Year int32 `json:"year"` - Verdict string `json:"verdict"` - Reason string `json:"reason"` - Reasons json.RawMessage `json:"reasons"` - FoldedFrom []string `json:"folded_from"` - SearchedAt string `json:"searched_at"` - Downloading bool `json:"downloading"` -} - -// handleListCandidates implements GET /api/admin/wanted/{id}/candidates. -func (h *handlers) handleListCandidates(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - q := dbq.New(h.pool) - rows, err := q.ListWantCandidates(r.Context(), id) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: candidates", apierror.Internal(err)) - return - } - live, err := q.GetLiveGrab(r.Context(), id) - if err != nil && !errors.Is(err, pgx.ErrNoRows) { - writeErrWithLog(w, h.logger, "admin wanted: live grab", apierror.Internal(err)) - return - } - out := make([]candidateView, 0, len(rows)) - for _, c := range rows { - v := candidateView{ - Key: c.Key, Name: c.Name, InfoHash: c.InfoHash, Indexer: c.Indexer, SizeBytes: c.SizeBytes, - Seeders: c.Seeders, FilesCount: c.FilesCount, Format: c.Format, Quality: c.Quality, Year: c.Year, - Verdict: c.Verdict, Reason: c.Reason, Reasons: c.Reasons, FoldedFrom: c.FoldedFrom, - SearchedAt: formatTimestamp(c.SearchedAt), - Downloading: live.ID.Valid && live.Key == c.Key, - } - if v.FoldedFrom == nil { - v.FoldedFrom = []string{} - } - if len(v.Reasons) == 0 { - v.Reasons = json.RawMessage("[]") - } - out = append(out, v) - } - writeJSON(w, http.StatusOK, map[string]any{"items": out}) -} - -// handleSearchWant implements POST /api/admin/wanted/{id}/search: search -// now, as the schedule would, taking the best release when auto-grab is on. -func (h *handlers) handleSearchWant(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - ctx, cancel := context.WithTimeout(r.Context(), searchTimeout) - defer cancel() - res, err := h.searcher.SearchNow(ctx, id) - if h.writeSearchErr(w, err) { - return - } - writeJSON(w, http.StatusOK, res) -} - -type grabBody struct { - Key string `json:"key"` - Force bool `json:"force"` -} - -// grabView is what came of a person's grab. -type grabView struct { - Added bool `json:"added"` - Refused bool `json:"refused"` - Gone bool `json:"gone"` - Unconfigured bool `json:"unconfigured"` - Missing string `json:"missing,omitempty"` - Kept bool `json:"kept"` - Replaced bool `json:"replaced"` - Verdict string `json:"verdict,omitempty"` - Reason string `json:"reason,omitempty"` - Error string `json:"error,omitempty"` -} - -// handleGrabCandidate implements POST /api/admin/wanted/{id}/grab: take the -// release named by key. The search runs again first, so the indexer's link -// never leaves the server; force takes what the verdict would not. -func (h *handlers) handleGrabCandidate(w http.ResponseWriter, r *http.Request) { - admin, ok := requireUser(w, r) - if !ok { - return - } - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - var body grabBody - if !decodeBody(w, r, &body) { - return - } - ctx, cancel := context.WithTimeout(r.Context(), searchTimeout) - defer cancel() - took, err := h.searcher.Take(ctx, id, body.Key, body.Force, admin.ID) - if h.writeSearchErr(w, err) { - return - } - v := grabView{ - Added: took.Added, Refused: took.Refused, Gone: took.Gone, Unconfigured: took.Unconfigured, - Missing: took.Missing, Error: took.Error, - } - if took.Chosen != nil { - v.Verdict, v.Reason = string(took.Chosen.Verdict), took.Chosen.Reason - } - if took.Contest != nil { - v.Kept, v.Replaced = took.Contest.Kept, took.Contest.Replaced - if took.Contest.Kept { - v.Reason = took.Contest.Reason - } - } - writeJSON(w, http.StatusOK, v) -} - -type blockBody struct { - Key string `json:"key"` -} - -// handleBlockCandidate implements POST /api/admin/wanted/{id}/block: never -// take this release again, for any want. -func (h *handlers) handleBlockCandidate(w http.ResponseWriter, r *http.Request) { - admin, ok := requireUser(w, r) - if !ok { - return - } - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - var body blockBody - if !decodeBody(w, r, &body) { - return - } - c, err := dbq.New(h.pool).GetWantCandidate(r.Context(), dbq.GetWantCandidateParams{WantID: id, Key: body.Key}) - if errors.Is(err, pgx.ErrNoRows) { - writeErr(w, apierror.NotFound("candidate")) - return - } - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: block", apierror.Internal(err)) - return - } - if c.InfoHash == "" { - writeErr(w, apierror.BadRequest("no_infohash", "this release has no infohash to set aside by")) - return - } - if err := acquire.NewMemory(h.pool).Block(r.Context(), dbq.BlockReleaseParams{ - InfoHash: c.InfoHash, Name: c.Name, Reason: acquire.BlockOperator, WantID: id, BlockedBy: admin.ID, - }); err != nil { - writeErrWithLog(w, h.logger, "admin wanted: block", apierror.Internal(err)) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// handleUnblockRelease implements DELETE /api/admin/release-blocks/{hash}. -func (h *handlers) handleUnblockRelease(w http.ResponseWriter, r *http.Request) { - removed, err := acquire.NewMemory(h.pool).Unblock(r.Context(), chi.URLParam(r, "hash")) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: unblock", apierror.Internal(err)) - return - } - if !removed { - writeErr(w, apierror.NotFound("block")) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// writeSearchErr answers a Searcher error, and says whether there was one. -func (h *handlers) writeSearchErr(w http.ResponseWriter, err error) bool { - switch { - case err == nil: - return false - case errors.Is(err, pgx.ErrNoRows): - writeErr(w, apierror.NotFound("want")) - case errors.Is(err, wanted.ErrWantHeld): - writeErr(w, apierror.Conflict("want_held", "the library already holds this album, and it isn't wanted for a better copy")) - default: - writeErrWithLog(w, h.logger, "admin wanted: search", apierror.Internal(err)) - } - return true -} diff --git a/internal/api/admin_smtp.go b/internal/api/admin_smtp.go index fd2c2378..77a73094 100644 --- a/internal/api/admin_smtp.go +++ b/internal/api/admin_smtp.go @@ -7,9 +7,10 @@ import ( "net/http" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/secret" ) type smtpConfigResp struct { @@ -76,11 +77,15 @@ func (h *handlers) handleUpdateSMTPConfig(w http.ResponseWriter, r *http.Request writeErrWithLog(w, h.logger, "admin smtp: get failed", apierror.Internal(err)) return } - // Preserve existing password when the request sends "" (so the - // admin doesn't have to re-enter it on every save). - password := req.Password - if password == "" { - password = current.Password + // Preserve the stored (sealed) password when the request sends "", so + // the admin doesn't have to re-enter it on every save. + password := current.Password + if req.Password != "" { + password, err = secret.Seal(secret.SMTPPassword.Purpose(), "", req.Password) + if err != nil { + writeErrWithLog(w, h.logger, "admin smtp: seal password", apierror.Internal(err)) + return + } } if err := q.UpdateSMTPConfig(r.Context(), dbq.UpdateSMTPConfigParams{ Enabled: req.Enabled, @@ -115,9 +120,12 @@ func (h *handlers) handleTestSMTPConfig(w http.ResponseWriter, r *http.Request) defer cancel() sender := mailer.NewSMTPSender(h.pool, h.logger) - textBody := "This is a test message from your Minstrel server.\n\nIf you got this, your SMTP config is working.\n\n— Minstrel" - htmlBody := "

This is a test message from your Minstrel server.

If you got this, your SMTP config is working.

— Minstrel

" - if err := sender.Send(ctx, *caller.Email, "Minstrel SMTP test", textBody, htmlBody); err != nil { + textBody, htmlBody, err := mailer.RenderSMTPTestEmail(h.netSettings.PublicURL()) + if err != nil { + writeErrWithLog(w, h.logger, "admin smtp: render test email failed", apierror.Internal(err)) + return + } + if err := sender.Send(ctx, *caller.Email, mailer.SMTPTestSubject, textBody, htmlBody); err != nil { if errors.Is(err, mailer.ErrNotConfigured) { writeErr(w, apierror.BadRequest("not_configured", "SMTP is not enabled or required fields are empty")) diff --git a/internal/api/admin_smtp_test.go b/internal/api/admin_smtp_test.go index 663a0cb8..b7864bb7 100644 --- a/internal/api/admin_smtp_test.go +++ b/internal/api/admin_smtp_test.go @@ -6,12 +6,11 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/auth" ) func newAdminSMTPRouter(h *handlers) chi.Router { @@ -26,9 +25,6 @@ func newAdminSMTPRouter(h *handlers) chi.Router { } func TestSMTPConfig_GetMasksPassword(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "smtpadmin", "pw", true) @@ -56,9 +52,6 @@ func TestSMTPConfig_GetMasksPassword(t *testing.T) { } func TestSMTPConfig_UpdatePreservesPasswordWhenEmpty(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "smtpupd", "pw", true) @@ -100,9 +93,6 @@ func TestSMTPConfig_UpdatePreservesPasswordWhenEmpty(t *testing.T) { } func TestSMTPConfig_UpdateValidatesEnabled(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "smtpvalid", "pw", true) @@ -119,9 +109,6 @@ func TestSMTPConfig_UpdateValidatesEnabled(t *testing.T) { } func TestSMTPConfig_TestRequiresEmail(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) // Admin without email on file. admin := seedUser(t, pool, "noemail", "pw", true) diff --git a/internal/api/admin_status.go b/internal/api/admin_status.go index 17c6f8fa..d2b693a6 100644 --- a/internal/api/admin_status.go +++ b/internal/api/admin_status.go @@ -5,13 +5,14 @@ import ( "syscall" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/logging" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/buildinfo" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/logging" ) // The admin Overview's status sections: after the verdict, who is -// listening, what is downloading, what the library holds and how much room +// listening, what the library holds and how much room // it has, and how the server itself is doing. One read for the page, polled // while it is open. @@ -36,17 +37,6 @@ type listeningStatusView struct { LastPlayAt *string `json:"last_play_at"` } -type downloadsStatusView struct { - Running int64 `json:"running"` - NeedsYou int64 `json:"needs_you"` - NeedsYouSince *string `json:"needs_you_since"` - ImportedDay int64 `json:"imported_day"` - GivenUpDay int64 `json:"given_up_day"` - // Live is the downloads not yet ended, the ones needing a person first. - Live []downloadView `json:"live"` - ClientsDown []clientDownView `json:"clients_down"` -} - // diskView is the filesystem one library folder, or the data folder, sits // on. type diskView struct { @@ -91,15 +81,10 @@ type serverStatusView struct { type adminStatusView struct { Listening listeningStatusView `json:"listening"` - Downloads downloadsStatusView `json:"downloads"` Library libraryStatusView `json:"library"` Server serverStatusView `json:"server"` } -// overviewLiveDownloads is how many running downloads the Overview lists; -// Activity has the rest. -const overviewLiveDownloads = 5 - // overviewErrors is how many recent errors the Overview lists. const overviewErrors = 10 @@ -112,7 +97,7 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request) now, err := q.ListListeningNow(ctx) if err != nil { h.logger.Error("admin status: listening", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } out.Listening.Now = make([]listeningView, 0, len(now)) @@ -127,7 +112,7 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request) day, err := q.PlaysLastDay(ctx) if err != nil { h.logger.Error("admin status: plays", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } out.Listening.PlaysDay, out.Listening.ListenersDay = day.Plays, day.Listeners @@ -136,22 +121,16 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request) out.Listening.LastPlayAt = &at } - if err := h.downloadsStatus(r, q, &out.Downloads); err != nil { - h.logger.Error("admin status: downloads", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") - return - } - lib, err := q.LibraryStatus(ctx) if err != nil { h.logger.Error("admin status: library", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } out.Library = libraryStatusView{Tracks: lib.Tracks, Albums: lib.Albums, Artists: lib.Artists, Bytes: lib.Bytes, Disks: []diskView{}} - if h.importer != nil { - for _, root := range h.importer.Roots() { + if h.scanner != nil { + for _, root := range h.scanner.Roots() { out.Library.Disks = append(out.Library.Disks, diskOf(root)) } } @@ -170,39 +149,6 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request) writeJSON(w, http.StatusOK, out) } -func (h *handlers) downloadsStatus(r *http.Request, q *dbq.Queries, out *downloadsStatusView) error { - st, err := q.DownloadsStatus(r.Context()) - if err != nil { - return err - } - *out = downloadsStatusView{Running: st.Running, NeedsYou: st.NeedsYou, - ImportedDay: st.ImportedDay, GivenUpDay: st.GivenUpDay, - Live: []downloadView{}, ClientsDown: []clientDownView{}} - if st.NeedsYou > 0 && st.NeedsYouSince.Valid { - since := formatTimestamp(st.NeedsYouSince) - out.NeedsYouSince = &since - } - // ListGrabs puts the ones needing a person first, then the running ones. - rows, err := q.ListGrabs(r.Context(), dbq.ListGrabsParams{MaxRows: overviewLiveDownloads}) - if err != nil { - return err - } - for _, g := range rows { - if !g.EndedAt.Valid { - out.Live = append(out.Live, downloadFrom(g)) - } - } - down, err := q.ListClientsDown(r.Context()) - if err != nil { - return err - } - for _, c := range down { - out.ClientsDown = append(out.ClientsDown, clientDownView{Client: c.Client, Detail: c.Detail, - Since: formatTimestamp(c.FirstSeen)}) - } - return nil -} - // diskOf reads the size and free space of the filesystem path is on. func diskOf(path string) diskView { var st syscall.Statfs_t diff --git a/internal/api/admin_status_test.go b/internal/api/admin_status_test.go index 4e2bcc07..3b89190d 100644 --- a/internal/api/admin_status_test.go +++ b/internal/api/admin_status_test.go @@ -9,8 +9,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo" - "git.fabledsword.com/bvandeusen/minstrel/internal/logging" + "github.com/Fabled-Sword/minstrel/internal/buildinfo" + "github.com/Fabled-Sword/minstrel/internal/logging" ) // openPlay records a play by user of track that started ago and has not @@ -76,7 +76,7 @@ func TestAdminStatus_ListeningAndServer(t *testing.T) { if got.Library.Tracks != 2 || got.Library.Albums != 2 || got.Library.Bytes != 10 { t.Errorf("library = %+v, want 2 tracks, 2 albums, 10 bytes", got.Library) } - if got.Downloads.Live == nil || got.Downloads.ClientsDown == nil || got.Library.Disks == nil { + if got.Library.Disks == nil { t.Error("lists must be [], never null") } diff --git a/internal/api/admin_summary.go b/internal/api/admin_summary.go index 9a870497..084a1604 100644 --- a/internal/api/admin_summary.go +++ b/internal/api/admin_summary.go @@ -5,7 +5,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // adminQueueView is one queue that waits on a person: how many, and since @@ -19,7 +20,6 @@ type adminQueueView struct { // every queue an admin acts on, in one response, so each admin page pays one // cheap read for its rail. type adminSummaryView struct { - Requests adminQueueView `json:"requests"` Reports adminQueueView `json:"reports"` Duplicates adminQueueView `json:"duplicates"` Suspect adminQueueView `json:"suspect"` @@ -37,7 +37,6 @@ func queueView(count int64, since pgtype.Timestamptz) adminQueueView { func adminSummaryFrom(row dbq.AdminSummaryRow) adminSummaryView { return adminSummaryView{ - Requests: queueView(row.Requests, row.RequestsSince), Reports: queueView(row.Reports, row.ReportsSince), Duplicates: queueView(row.Duplicates, row.DuplicatesSince), Suspect: queueView(row.Suspect, row.SuspectSince), @@ -50,7 +49,7 @@ func (h *handlers) handleGetAdminSummary(w http.ResponseWriter, r *http.Request) row, err := dbq.New(h.pool).AdminSummary(r.Context()) if err != nil { h.logger.Error("admin: summary", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } writeJSON(w, http.StatusOK, adminSummaryFrom(row)) diff --git a/internal/api/admin_summary_test.go b/internal/api/admin_summary_test.go index f6970512..271ebd3a 100644 --- a/internal/api/admin_summary_test.go +++ b/internal/api/admin_summary_test.go @@ -9,8 +9,8 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func getAdminSummary(t *testing.T, h *handlers, user dbq.User) (int, adminSummaryView) { @@ -35,6 +35,7 @@ func getAdminSummary(t *testing.T, h *handlers, user dbq.User) (int, adminSummar // oldest item has waited; an empty queue has no since. func TestAdminSummary_CountsTheQueuesAndSinceWhen(t *testing.T) { h, _ := testHandlers(t) + truncateLibrary(t, h.pool) admin := seedUser(t, h.pool, "admin", "pw", true) listener := seedUser(t, h.pool, "listener", "pw", false) ctx := context.Background() @@ -43,19 +44,17 @@ func TestAdminSummary_CountsTheQueuesAndSinceWhen(t *testing.T) { if code != http.StatusOK { t.Fatalf("status = %d", code) } - if empty.Requests.Count != 0 || empty.Requests.Since != nil || empty.Missing.Count != 0 { + if empty.Missing.Count != 0 || empty.Missing.Since != nil { t.Errorf("empty summary = %+v", empty) } - if _, err := dbq.New(h.pool).CreateRequest(ctx, dbq.CreateRequestParams{ - UserID: listener.ID, Kind: dbq.RequestKindArtist, ArtistMbid: "a0000000-0000-4000-8000-000000000001", - ArtistName: "Annadale", - }); err != nil { + track := seedQuarantineTrack(t, h, "sum-missing") + if _, err := h.pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, track.ID); err != nil { t.Fatal(err) } _, got := getAdminSummary(t, h, admin) - if got.Requests.Count != 1 || got.Requests.Since == nil { - t.Errorf("requests = %+v, want 1 with a since", got.Requests) + if got.Missing.Count != 1 || got.Missing.Since == nil { + t.Errorf("missing = %+v, want 1 with a since", got.Missing) } if code, _ := getAdminSummary(t, h, listener); code != http.StatusForbidden { diff --git a/internal/api/admin_suspect_sources.go b/internal/api/admin_suspect_sources.go index 8e5a0e90..2c7aaecf 100644 --- a/internal/api/admin_suspect_sources.go +++ b/internal/api/admin_suspect_sources.go @@ -2,13 +2,18 @@ package api import ( "encoding/json" + "errors" "net/http" "time" "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // suspectTrackView is one flagged track. FilePath is the evidence: the @@ -31,15 +36,11 @@ type suspectTrackView struct { // first pass. VerdictAt is when it was last set. Verdict *string `json:"verdict"` VerdictAt *string `json:"verdict_at"` - // Replacing: the album is on the wanted list for a clean copy; - // SearchedAt is when one was last searched for, null before the first. - Replacing bool `json:"replacing"` - SearchedAt *string `json:"searched_at"` } // suspectGroupView is a folder's worth of flagged tracks. As on the -// missing-files report, the folder is the unit of decision: Humanz was 62 rows -// in one folder, which is one problem to look at, not 62. +// missing-files report, the folder is the unit of decision: sixty flagged rows +// in one folder are one problem to look at, not sixty. type suspectGroupView struct { Directory string `json:"directory"` Tracks []suspectTrackView `json:"tracks"` @@ -62,7 +63,7 @@ type adminSuspectSourcesResponse struct { func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Request) { limit, offset, err := parsePaging(r.URL.Query()) if err != nil { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") + writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset")) return } @@ -70,7 +71,7 @@ func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Reque total, err := q.CountSuspectSourceTracks(r.Context(), library.SuspectSourcePattern) if err != nil { h.logger.Error("admin: count suspect-source tracks", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } rows, err := q.ListSuspectSourceTracks(r.Context(), dbq.ListSuspectSourceTracksParams{ @@ -80,7 +81,7 @@ func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Reque }) if err != nil { h.logger.Error("admin: list suspect-source tracks", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } @@ -116,11 +117,6 @@ func groupSuspectByDirectory(rows []dbq.ListSuspectSourceTracksRow) []suspectGro at := row.SourceVerdictAt.Time.UTC().Format(time.RFC3339) t.VerdictAt = &at } - t.Replacing = row.WantUpgrade == "rip" - if t.Replacing && row.SearchedAt.Valid { - at := row.SearchedAt.Time.UTC().Format(time.RFC3339) - t.SearchedAt = &at - } if n := len(groups); n > 0 && groups[n-1].Directory == row.Directory { groups[n-1].Tracks = append(groups[n-1].Tracks, t) continue @@ -144,27 +140,78 @@ type suspectVerdictRequest struct { func (h *handlers) handleSetSuspectSourceVerdict(w http.ResponseWriter, r *http.Request) { id, ok := parseUUID(chi.URLParam(r, "id")) if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } var req suspectVerdictRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") + writeErr(w, apierror.BadRequest("invalid_body", "invalid request body")) return } if req.Verdict != "fine" && req.Verdict != "suspect" { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_verdict") + writeErr(w, apierror.BadRequest("invalid_verdict", "verdict must be fine or suspect")) return } n, err := dbq.New(h.pool).SetTrackSourceVerdict(r.Context(), dbq.SetTrackSourceVerdictParams{Verdict: req.Verdict, ID: id}) if err != nil { h.logger.Error("admin: set suspect-source verdict", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } if n == 0 { - writeAdminJSONErr(w, http.StatusNotFound, "suspect_track_not_found") + writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list")) return } writeJSON(w, http.StatusOK, map[string]string{"verdict": req.Verdict}) } + +// handleRemoveSuspectSourceFile implements POST +// /api/admin/library/suspect-sources/{id}/remove: the rip's file goes and the +// track stays, missing, until a clean copy lands in the library. Its +// recording MBID goes with the file, since a video rip is often another +// recording of the song (a live take, a video edit). +// +// Errors: 404 suspect_track_not_found when the track is gone, missing, or its +// file name carries no video-title marker; 409 library_not_writable / 500 +// file_delete_failed when the file could not be removed. +func (h *handlers) handleRemoveSuspectSourceFile(w http.ResponseWriter, r *http.Request) { + admin, ok := requireUser(w, r) + if !ok { + return + } + id, ok := parseUUID(chi.URLParam(r, "id")) + if !ok { + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) + return + } + track, err := dbq.New(h.pool).GetTrackByID(r.Context(), id) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && (track.MissingSince.Valid || len(library.SourceMarkersFor(track.FilePath)) == 0)) { + writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list")) + return + } + if err != nil { + h.logger.Error("admin: read suspect track", "err", err) + writeErr(w, apierror.Internal(err)) + return + } + if _, err := library.RemoveFile(r.Context(), h.pool, h.logger, library.RemoveFileParams{ + TrackID: id, ActorID: admin.ID, Reason: library.RemovedForSuspect, ForgetMBID: true, + }); err != nil { + if apiErr, ok := fileRemoveAPIError(err); ok { + logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id)) + writeErr(w, apiErr) + return + } + if errors.Is(err, library.ErrTrackNotFound) { + writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list")) + return + } + h.logger.Error("admin: remove suspect file", "err", err) + writeErr(w, apierror.New(http.StatusInternalServerError, "file_delete_failed", "the file could not be deleted")) + return + } + audit.WriteOrLog(r.Context(), h.pool, h.logger, admin.ID, pgtype.UUID{}, audit.ActionSuspectFileRemove, map[string]any{ + "track_id": uuidToString(id), "title": track.Title, "file_path": track.FilePath, + }) + w.WriteHeader(http.StatusNoContent) +} diff --git a/internal/api/admin_suspect_sources_test.go b/internal/api/admin_suspect_sources_test.go index bf812a55..aff7d41b 100644 --- a/internal/api/admin_suspect_sources_test.go +++ b/internal/api/admin_suspect_sources_test.go @@ -16,14 +16,14 @@ func TestHandleListSuspectSources_Integration(t *testing.T) { truncateLibrary(t, pool) admin := seedUser(t, pool, "suspect-admin", "pw", true) - artist := seedArtist(t, pool, "Gorillaz") - humanz := seedAlbum(t, pool, artist.ID, "Humanz", 2017) - seedTrack(t, pool, humanz.ID, artist.ID, "Saturnz Barz (Official Video)", 1, 180_000) - seedTrack(t, pool, humanz.ID, artist.ID, "Momentz (Visualizer)", 2, 200_000) - seedTrack(t, pool, humanz.ID, artist.ID, "Andromeda [Audio]", 3, 190_000) - seedTrack(t, pool, humanz.ID, artist.ID, "Chain Reaction", 4, 190_000) - seedTrack(t, pool, humanz.ID, artist.ID, "Busted and Blue", 5, 190_000) - gone := seedTrack(t, pool, humanz.ID, artist.ID, "Ascension (Lyric Video)", 6, 156_000) + artist := seedArtist(t, pool, "Plastic Apes") + mammalz := seedAlbum(t, pool, artist.ID, "Mammalz", 2017) + seedTrack(t, pool, mammalz.ID, artist.ID, "Neptunez Barz (Official Video)", 1, 180_000) + seedTrack(t, pool, mammalz.ID, artist.ID, "Minutez (Visualizer)", 2, 200_000) + seedTrack(t, pool, mammalz.ID, artist.ID, "Cassiopeia [Audio]", 3, 190_000) + seedTrack(t, pool, mammalz.ID, artist.ID, "Chain Reaction", 4, 190_000) + seedTrack(t, pool, mammalz.ID, artist.ID, "Bruised and Grey", 5, 190_000) + gone := seedTrack(t, pool, mammalz.ID, artist.ID, "Elevation (Lyric Video)", 6, 156_000) if _, err := pool.Exec(context.Background(), `UPDATE tracks SET missing_since = now() WHERE id = $1`, gone.ID); err != nil { t.Fatalf("mark missing: %v", err) @@ -41,8 +41,8 @@ func TestHandleListSuspectSources_Integration(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } - // Three present files carry a marker. "Chain Reaction" and "Busted and - // Blue" carry none, and the lyric video's file is missing. + // Three present files carry a marker. "Chain Reaction" and "Bruised and + // Grey" carry none, and the lyric video's file is missing. if resp.Total != 3 { t.Errorf("total = %d, want 3", resp.Total) } @@ -54,9 +54,9 @@ func TestHandleListSuspectSources_Integration(t *testing.T) { got[tr.Title] = tr.Markers } want := map[string][]string{ - "Saturnz Barz (Official Video)": {"music video"}, - "Momentz (Visualizer)": {"visualiser"}, - "Andromeda [Audio]": {"[Audio]"}, + "Neptunez Barz (Official Video)": {"music video"}, + "Minutez (Visualizer)": {"visualiser"}, + "Cassiopeia [Audio]": {"[Audio]"}, } if len(got) != len(want) { t.Fatalf("tracks = %v, want %v", got, want) @@ -67,3 +67,41 @@ func TestHandleListSuspectSources_Integration(t *testing.T) { } } } + +// Removing a suspect source keeps its track, missing, and only a track whose +// file name carries a video-title marker can be removed this way. +func TestHandleRemoveSuspectSourceFile_Integration(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + admin := seedUser(t, pool, "suspect-remover", "pw", true) + artist := seedArtist(t, pool, "Plastic Apes") + mammalz := seedAlbum(t, pool, artist.ID, "Mammalz", 2017) + rip := seedTrack(t, pool, mammalz.ID, artist.ID, "Neptunez Barz (Official Video)", 1, 180_000) + clean := seedTrack(t, pool, mammalz.ID, artist.ID, "Chain Reaction", 4, 190_000) + + remove := func(id string) int { + req := httptest.NewRequest(http.MethodPost, "/api/admin/library/suspect-sources/"+id+"/remove", nil) + req = withURLParam(withUser(req, admin), "id", id) + w := httptest.NewRecorder() + h.handleRemoveSuspectSourceFile(w, req) + return w.Code + } + if code := remove(uuidToString(clean.ID)); code != http.StatusNotFound { + t.Errorf("removing a clean file's track: status %d, want 404", code) + } + if code := remove(uuidToString(rip.ID)); code != http.StatusNoContent { + t.Fatalf("removing the rip: status %d, want 204", code) + } + var reason *string + var missing bool + if err := pool.QueryRow(context.Background(), + `SELECT removed_reason, missing_since IS NOT NULL FROM tracks WHERE id = $1`, rip.ID).Scan(&reason, &missing); err != nil { + t.Fatalf("the rip's track went with its file: %v", err) + } + if !missing || reason == nil || *reason != "suspect" { + t.Errorf("rip's track = missing %v, reason %v; want missing for a suspect source", missing, reason) + } + if code := remove(uuidToString(rip.ID)); code != http.StatusNotFound { + t.Errorf("removing it again: status %d, want 404 for a track already waiting", code) + } +} diff --git a/internal/api/admin_tag_sources.go b/internal/api/admin_tag_sources.go index 412a1a42..00093f52 100644 --- a/internal/api/admin_tag_sources.go +++ b/internal/api/admin_tag_sources.go @@ -1,139 +1,27 @@ package api import ( - "encoding/json" - "errors" "net/http" - "time" - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/tags" + "github.com/Fabled-Sword/minstrel/internal/apierror" ) -// tagSourceResp is the wire shape for one tag-enrichment provider in the -// GET /api/admin/tag-sources list. Mirrors the cover-sources admin surface -// (admin_cover_sources.go) — a separate, independent settings card so a new -// tag source is added without touching art settings. -type tagSourceResp struct { - ID string `json:"id"` - DisplayName string `json:"display_name"` - RequiresAPIKey bool `json:"requires_api_key"` - Supports []string `json:"supports"` - Enabled bool `json:"enabled"` - APIKeySet bool `json:"api_key_set"` - DisplayOrder int32 `json:"display_order"` - Testable bool `json:"testable"` -} - -func tagSourceRespFrom(info tags.ProviderInfo) tagSourceResp { - supports := info.Supports - if supports == nil { - supports = []string{} - } - return tagSourceResp{ - ID: info.ID, - DisplayName: info.DisplayName, - RequiresAPIKey: info.RequiresAPIKey, - Supports: supports, - Enabled: info.Enabled, - APIKeySet: info.APIKeySet, - DisplayOrder: info.DisplayOrder, - Testable: info.Testable, - } -} - -type tagSourcesListResp struct { - Providers []tagSourceResp `json:"providers"` - SourcesVersion int32 `json:"sources_version"` -} +// The tag-sources admin card: the shared provider-source handlers +// (admin_provider_sources.go) over the tag settings. // handleListTagSources implements GET /api/admin/tag-sources. func (h *handlers) handleListTagSources(w http.ResponseWriter, _ *http.Request) { - infos := h.tagSettings.ListProviderInfo() - out := tagSourcesListResp{ - Providers: make([]tagSourceResp, 0, len(infos)), - SourcesVersion: h.tagSettings.CurrentVersion(), - } - for _, info := range infos { - out.Providers = append(out.Providers, tagSourceRespFrom(info)) - } - writeJSON(w, http.StatusOK, out) -} - -// updateTagSourceReq is the PATCH body. nil pointers mean "leave -// unchanged"; non-nil sets (empty api_key clears). -type updateTagSourceReq struct { - Enabled *bool `json:"enabled,omitempty"` - APIKey *string `json:"api_key,omitempty"` -} - -type updateTagSourceResp struct { - tagSourceResp - VersionBumped bool `json:"version_bumped"` + listProviderSources(w, h.tagSettings.Service) } // handleUpdateTagSource implements PATCH /api/admin/tag-sources/{provider_id}. func (h *handlers) handleUpdateTagSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - var body updateTagSourceReq - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - writeErr(w, apierror.BadRequest("bad_body", "invalid JSON")) - return - } - - bumped, err := h.tagSettings.UpdateProvider(r.Context(), id, tags.ProviderUpdatePatch{ - Enabled: body.Enabled, - APIKey: body.APIKey, - }) - if err != nil { - if errors.Is(err, tags.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - h.logger.Error("admin: update tag source", "id", id, "err", err) - writeErr(w, apierror.InternalMsg("update failed", err)) - return - } - - var found tagSourceResp - for _, info := range h.tagSettings.ListProviderInfo() { - if info.ID == id { - found = tagSourceRespFrom(info) - break - } - } - writeJSON(w, http.StatusOK, updateTagSourceResp{tagSourceResp: found, VersionBumped: bumped}) + h.updateProviderSource(w, r, h.tagSettings.Service) } -type testTagSourceResp struct { - OK bool `json:"ok"` - DurationMs int64 `json:"duration_ms,omitempty"` - Error string `json:"error,omitempty"` -} - -// handleTestTagSource implements POST -// /api/admin/tag-sources/{provider_id}/test. +// handleTestTagSource implements POST /api/admin/tag-sources/{provider_id}/test. func (h *handlers) handleTestTagSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - start := time.Now() - err := h.tagSettings.TestProvider(r.Context(), id) - duration := time.Since(start).Milliseconds() - - if err == nil { - writeJSON(w, http.StatusOK, testTagSourceResp{OK: true, DurationMs: duration}) - return - } - if errors.Is(err, tags.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - // Not testable, or the test failed — both surface as ok=false with a - // 200 (the operation completed; the result is data, not an error). - writeJSON(w, http.StatusOK, testTagSourceResp{OK: false, DurationMs: duration, Error: err.Error()}) + testProviderSource(w, r, h.tagSettings.Service) } type researchTagsResp struct { diff --git a/internal/api/admin_tag_sources_test.go b/internal/api/admin_tag_sources_test.go index cb00a0a8..f7b57c01 100644 --- a/internal/api/admin_tag_sources_test.go +++ b/internal/api/admin_tag_sources_test.go @@ -6,13 +6,12 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/tags" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/tags" ) // apiTestTagProvider is a minimal TrackTagProvider for api-package tests. @@ -31,13 +30,6 @@ func (p *apiTestTagProvider) FetchTrackTags(_ context.Context, _ tags.TrackRef) return []tags.Tag{{Name: "x", Weight: 1}}, nil } -// apiTestTestableTagProvider also implements TestableProvider. -type apiTestTestableTagProvider struct { - apiTestTagProvider -} - -func (p *apiTestTestableTagProvider) TestConnection(_ context.Context) error { return nil } - func newAdminTagSourcesRouter(h *handlers) chi.Router { r := chi.NewRouter() r.Route("/api/admin", func(admin chi.Router) { @@ -64,9 +56,6 @@ func testHandlersWithTagSettings(t *testing.T) *handlers { } func TestAdminListTagSources_ReturnsRegisteredProviders(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } tags.ResetRegistryForTests() t.Cleanup(tags.ResetRegistryForTests) tags.Register(&apiTestTagProvider{id: "test-tag-prov", display: "Test Tag Provider"}) @@ -82,7 +71,7 @@ func TestAdminListTagSources_ReturnsRegisteredProviders(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp tagSourcesListResp + var resp providerSourcesListResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -104,9 +93,6 @@ func TestAdminListTagSources_ReturnsRegisteredProviders(t *testing.T) { } func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } tags.ResetRegistryForTests() t.Cleanup(tags.ResetRegistryForTests) tags.Register(&apiTestTagProvider{id: "flip-tag", display: "Flip Tag"}) @@ -115,7 +101,7 @@ func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(t *testing.T) { admin := seedUser(t, h.pool, "tsflip", "pw", true) disabled := false - body, _ := json.Marshal(updateTagSourceReq{Enabled: &disabled}) + body, _ := json.Marshal(updateProviderSourceReq{Enabled: &disabled}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/tag-sources/flip-tag", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -125,7 +111,7 @@ func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp updateTagSourceResp + var resp updateProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -134,10 +120,7 @@ func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(t *testing.T) { } } -func TestAdminUpdateTagSource_KeyOnlyDoesNotBump(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } +func TestAdminUpdateTagSource_ReplacingAKeyDoesNotBump(t *testing.T) { tags.ResetRegistryForTests() t.Cleanup(tags.ResetRegistryForTests) tags.Register(&apiTestTagProvider{id: "key-tag", display: "Key Tag"}) @@ -145,40 +128,43 @@ func TestAdminUpdateTagSource_KeyOnlyDoesNotBump(t *testing.T) { h := testHandlersWithTagSettings(t) admin := seedUser(t, h.pool, "tskey", "pw", true) - newKey := "newkey" - body, _ := json.Marshal(updateTagSourceReq{APIKey: &newKey}) - req := httptest.NewRequest(http.MethodPatch, "/api/admin/tag-sources/key-tag", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - req = withUser(req, admin) - rec := httptest.NewRecorder() - newAdminTagSourcesRouter(h).ServeHTTP(rec, req) + // The first key on an enabled source moves the version (it searched + // without one until now); replacing that key with another doesn't. + for i, step := range []struct { + key string + wantBumped bool + }{{"firstkey", true}, {"newkey", false}} { + body, _ := json.Marshal(updateProviderSourceReq{APIKey: &step.key}) + req := httptest.NewRequest(http.MethodPatch, "/api/admin/tag-sources/key-tag", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req = withUser(req, admin) + rec := httptest.NewRecorder() + newAdminTagSourcesRouter(h).ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - var resp updateTagSourceResp - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.VersionBumped { - t.Error("version_bumped = true, want false for key-only change") - } - if !resp.APIKeySet { - t.Error("api_key_set = false, want true after setting key") + if rec.Code != http.StatusOK { + t.Fatalf("step %d: status = %d, want 200; body=%s", i, rec.Code, rec.Body.String()) + } + var resp updateProviderSourceResp + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if resp.VersionBumped != step.wantBumped { + t.Errorf("key %q: version_bumped = %v, want %v", step.key, resp.VersionBumped, step.wantBumped) + } + if !resp.APIKeySet { + t.Error("api_key_set = false, want true after setting key") + } } } func TestAdminUpdateTagSource_UnknownProvider404(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } tags.ResetRegistryForTests() t.Cleanup(tags.ResetRegistryForTests) h := testHandlersWithTagSettings(t) admin := seedUser(t, h.pool, "ts404", "pw", true) - body, _ := json.Marshal(updateTagSourceReq{}) + body, _ := json.Marshal(updateProviderSourceReq{}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/tag-sources/missing", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -190,31 +176,7 @@ func TestAdminUpdateTagSource_UnknownProvider404(t *testing.T) { } } -func TestAdminTestTagSource_NonAdminReturns403(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - tags.ResetRegistryForTests() - t.Cleanup(tags.ResetRegistryForTests) - tags.Register(&apiTestTestableTagProvider{apiTestTagProvider{id: "testable-tag", display: "Testable Tag"}}) - - h := testHandlersWithTagSettings(t) - nonAdmin := seedUser(t, h.pool, "tsnoadmin", "pw", false) - - req := httptest.NewRequest(http.MethodPost, "/api/admin/tag-sources/testable-tag/test", nil) - req = withUser(req, nonAdmin) - rec := httptest.NewRecorder() - newAdminTagSourcesRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String()) - } -} - func TestAdminTestTagSource_NotTestableReturnsOkFalse(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } tags.ResetRegistryForTests() t.Cleanup(tags.ResetRegistryForTests) tags.Register(&apiTestTagProvider{id: "nontestable-tag", display: "Non-Testable Tag"}) @@ -230,7 +192,7 @@ func TestAdminTestTagSource_NotTestableReturnsOkFalse(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp testTagSourceResp + var resp testProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } diff --git a/internal/api/admin_tracks.go b/internal/api/admin_tracks.go deleted file mode 100644 index e944a257..00000000 --- a/internal/api/admin_tracks.go +++ /dev/null @@ -1,76 +0,0 @@ -package api - -import ( - "errors" - "net/http" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/tracks" -) - -// removeTrackResponse is DELETE /api/admin/tracks/{id}'s answer. The two -// optional fields are omitted unless the corresponding cleanup actually -// happened, so the response stays minimal in the common case. -type removeTrackResponse struct { - DeletedTrackID string `json:"deleted_track_id"` - DeletedAlbumID *string `json:"deleted_album_id,omitempty"` - DeletedArtistID *string `json:"deleted_artist_id,omitempty"` -} - -// handleRemoveTrack implements DELETE /api/admin/tracks/{id}. -// -// Admin-only (gated by auth.RequireAdmin on the /admin route group). Deletes -// the file, then the DB row, and runs the album/artist cascade tidy-up — and -// deletes nothing at all when the file cannot be removed. -// -// The codes this handler emits are not_found, -// library_not_writable (409) and file_delete_failed when the file could not be -// removed, server_error, plus the auth codes the middleware emits upstream. -func (h *handlers) handleRemoveTrack(w http.ResponseWriter, r *http.Request) { - idStr := chi.URLParam(r, "id") - trackID, ok := parseUUID(idStr) - if !ok { - // Malformed id is functionally equivalent to "no such track" for - // the spec's error surface — collapse both to 404 not_found so - // the client doesn't have to handle a separate bad_request branch - // for a code path that's only reachable via UI bugs. - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "track not found"}) - return - } - - // Defensive: RequireUser+RequireAdmin should have run upstream. If - // we got here without a user in context the routing is broken. - admin, ok := requireUser(w, r) - if !ok { - return - } - - deletedAlbum, deletedArtist, err := h.tracks.RemoveTrack(r.Context(), trackID, admin.ID) - if err != nil { - if errors.Is(err, tracks.ErrNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "track not found"}) - return - } - if apiErr, ok := fileRemoveAPIError(err); ok { - logFileRemoveFailure(h.logger, apiErr, "track_id", idStr) - writeErr(w, apiErr) - return - } - h.logger.Error("api: remove track failed", "err", err, "track_id", idStr) - writeErr(w, apierror.InternalMsg("remove failed", err)) - return - } - - resp := removeTrackResponse{DeletedTrackID: idStr} - if deletedAlbum != nil { - s := uuidToString(*deletedAlbum) - resp.DeletedAlbumID = &s - } - if deletedArtist != nil { - s := uuidToString(*deletedArtist) - resp.DeletedArtistID = &s - } - writeJSON(w, http.StatusOK, resp) -} diff --git a/internal/api/admin_tracks_test.go b/internal/api/admin_tracks_test.go deleted file mode 100644 index 0dd9a4cb..00000000 --- a/internal/api/admin_tracks_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package api - -import ( - "bytes" - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "testing" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" -) - -// newAdminTracksRouter builds a test chi router with the admin-tracks -// endpoint. RequireAdmin middleware is applied; tests inject the user into -// context manually (RequireUser is bypassed). Mirrors the pattern from -// admin_quarantine_test.go. -func newAdminTracksRouter(h *handlers) chi.Router { - r := chi.NewRouter() - r.Route("/api/admin", func(admin chi.Router) { - admin.Use(auth.RequireAdmin()) - admin.Delete("/tracks/{id}", h.handleRemoveTrack) - }) - return r -} - -// doAdminTracksReq fires an HTTP request against the admin-tracks router -// with the given user in context. -func doAdminTracksReq(t *testing.T, h *handlers, method, path string, user dbq.User) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequest(method, path, bytes.NewBuffer(nil)) - req = withUser(req, user) - w := httptest.NewRecorder() - newAdminTracksRouter(h).ServeHTTP(w, req) - return w -} - -// doAdminTracksReqNoUser fires a request directly at the handler with NO -// user injected into context. Used to exercise the defensive 401 branch -// inside the handler — real traffic hits RequireUser upstream, but the -// handler defends against routing misconfigurations and we test that path -// here. We bypass the admin router entirely since RequireAdmin would -// short-circuit with 500 internal_error on missing-user-in-context (which -// is its programmer-error contract); the handler's own 401 path is what -// we want to assert. -func doAdminTracksReqNoUser(t *testing.T, h *handlers, method, path, idParam string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequest(method, path, bytes.NewBuffer(nil)) - rctx := chi.NewRouteContext() - rctx.URLParams.Add("id", idParam) - req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx)) - w := httptest.NewRecorder() - h.handleRemoveTrack(w, req) - return w -} - -// seedTrackForRemoveTest creates a fresh artist+album+track on disk and -// returns the track row. The mbids are set on the track and album when -// non-empty. -func seedTrackForRemoveTest(t *testing.T, h *handlers, unique, trackMbid, albumMbid string) (dbq.Track, string) { - t.Helper() - artist := seedArtist(t, h.pool, "RemoveTest Artist "+unique) - dir := t.TempDir() - path := filepath.Join(dir, "track-"+unique+".mp3") - if err := os.WriteFile(path, []byte("audio"), 0o644); err != nil { - t.Fatalf("write file: %v", err) - } - q := dbq.New(h.pool) - var albumMbidPtr *string - if albumMbid != "" { - albumMbidPtr = &albumMbid - } - album, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{ - Title: "RemoveTest Album " + unique, - SortTitle: "RemoveTest Album " + unique, - ArtistID: artist.ID, - Mbid: albumMbidPtr, - }) - if err != nil { - t.Fatalf("UpsertAlbum: %v", err) - } - one := int32(1) - var trackMbidPtr *string - if trackMbid != "" { - trackMbidPtr = &trackMbid - } - tr, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{ - Title: "RemoveTest Track " + unique, - AlbumID: album.ID, - ArtistID: artist.ID, - TrackNumber: &one, - DurationMs: 30000, - FilePath: path, - FileSize: 5, - FileFormat: "mp3", - Mbid: trackMbidPtr, - }) - if err != nil { - t.Fatalf("UpsertTrack: %v", err) - } - return tr, path -} - -// TestHandleRemoveTrack_NonAdmin403 verifies the RequireAdmin middleware -// rejects non-admin callers, with the shared middleware's -// {"error":"not_authorized"} envelope, which this handler doesn't own. -func TestHandleRemoveTrack_NonAdmin403(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - nonAdmin := seedUser(t, pool, "regular", "pw", false) - fakeID := "00000000-0000-0000-0000-000000000001" - - w := doAdminTracksReq(t, h, http.MethodDelete, "/api/admin/tracks/"+fakeID, nonAdmin) - if w.Code != http.StatusForbidden { - t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String()) - } - var resp map[string]string - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if resp["error"] != "not_authorized" { - t.Errorf("error = %q, want not_authorized", resp["error"]) - } -} - -// TestHandleRemoveTrack_NoSession401 exercises the defensive no-user-in- -// context branch in the handler itself. Real traffic hits RequireUser -// upstream (which emits 401 with text "unauthenticated"), but the handler -// also defends against routing misconfigurations and we test that -// directly. -func TestHandleRemoveTrack_NoSession401(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - - tr, _ := seedTrackForRemoveTest(t, h, "no-session", "", "") - w := doAdminTracksReqNoUser(t, h, http.MethodDelete, - "/api/admin/tracks/"+uuidToString(tr.ID), uuidToString(tr.ID)) - if w.Code != http.StatusUnauthorized { - t.Fatalf("status = %d, want 401; body = %s", w.Code, w.Body.String()) - } - var env errorBody - if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if env.Error.Code != "unauthenticated" { - t.Errorf("error.code = %q, want unauthenticated", env.Error.Code) - } -} - -// TestHandleRemoveTrack_UnknownID404 verifies ErrNotFound from the service -// maps to 404 not_found in the spec envelope. -func TestHandleRemoveTrack_UnknownID404(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - admin := seedUser(t, pool, "admin", "pw", true) - - // Well-formed UUID with no matching row in the DB. - missing := "00000000-0000-0000-0000-0000000000aa" - w := doAdminTracksReq(t, h, http.MethodDelete, "/api/admin/tracks/"+missing, admin) - if w.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String()) - } - var env errorBody - if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if env.Error.Code != "not_found" { - t.Errorf("error.code = %q, want not_found", env.Error.Code) - } -} - -// TestHandleRemoveTrack_HappyPath verifies the success envelope: 200 with -// deleted_track_id and the optional cascade fields when they fired. -func TestHandleRemoveTrack_HappyPath(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - admin := seedUser(t, pool, "admin", "pw", true) - - // Track with no mbid; sole track on its album/artist so the cascade - // fills both deleted_album_id and deleted_artist_id. - tr, path := seedTrackForRemoveTest(t, h, "noumon-happy", "", "") - w := doAdminTracksReq(t, h, http.MethodDelete, - "/api/admin/tracks/"+uuidToString(tr.ID), admin) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - - var got removeTrackResponse - if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if got.DeletedTrackID != uuidToString(tr.ID) { - t.Errorf("deleted_track_id = %q, want %q", got.DeletedTrackID, uuidToString(tr.ID)) - } - if got.DeletedAlbumID == nil { - t.Error("deleted_album_id missing; expected sole-track cascade") - } - if got.DeletedArtistID == nil { - t.Error("deleted_artist_id missing; expected sole-track cascade") - } - - // File is gone, DB row is gone. - if _, err := os.Stat(path); !os.IsNotExist(err) { - t.Errorf("file still exists: %v", err) - } - if _, err := dbq.New(pool).GetTrackByID(context.Background(), tr.ID); err == nil { - t.Error("track row still exists") - } -} diff --git a/internal/api/admin_users.go b/internal/api/admin_users.go index 9c729e79..0f8813d0 100644 --- a/internal/api/admin_users.go +++ b/internal/api/admin_users.go @@ -5,25 +5,22 @@ import ( "net/http" "time" - "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" - "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) type adminUserView struct { - ID string `json:"id"` - Username string `json:"username"` - DisplayName *string `json:"display_name"` - IsAdmin bool `json:"is_admin"` - AutoApproveRequests bool `json:"auto_approve_requests"` - DebugModeEnabled bool `json:"debug_mode_enabled"` - CreatedAt string `json:"created_at"` + ID string `json:"id"` + Username string `json:"username"` + DisplayName *string `json:"display_name"` + IsAdmin bool `json:"is_admin"` + DebugModeEnabled bool `json:"debug_mode_enabled"` + CreatedAt string `json:"created_at"` } type listUsersResp struct { @@ -40,13 +37,12 @@ func (h *handlers) handleAdminListUsers(w http.ResponseWriter, r *http.Request) out := make([]adminUserView, 0, len(rows)) for _, row := range rows { v := adminUserView{ - ID: uuidToString(row.ID), - Username: row.Username, - DisplayName: row.DisplayName, - IsAdmin: row.IsAdmin, - AutoApproveRequests: row.AutoApproveRequests, - DebugModeEnabled: row.DebugModeEnabled, - CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339), + ID: uuidToString(row.ID), + Username: row.Username, + DisplayName: row.DisplayName, + IsAdmin: row.IsAdmin, + DebugModeEnabled: row.DebugModeEnabled, + CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339), } out = append(out, v) } @@ -117,13 +113,12 @@ func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request) audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, action, nil) writeJSON(w, http.StatusOK, adminUserView{ - ID: uuidToString(updated.ID), - Username: updated.Username, - DisplayName: updated.DisplayName, - IsAdmin: updated.IsAdmin, - AutoApproveRequests: updated.AutoApproveRequests, - DebugModeEnabled: updated.DebugModeEnabled, - CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339), + ID: uuidToString(updated.ID), + Username: updated.Username, + DisplayName: updated.DisplayName, + IsAdmin: updated.IsAdmin, + DebugModeEnabled: updated.DebugModeEnabled, + CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339), }) } @@ -149,12 +144,11 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request) writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen")) return } - if len(req.Password) < minPasswordLength { - writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars")) + if !checkNewPassword(w, req.Password) { return } - hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) + hash, err := hashPassword(req.Password) if err != nil { writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err)) return @@ -174,9 +168,8 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request) DisplayName: req.DisplayName, }) if err != nil { - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation { - writeErr(w, apierror.Conflict("username_taken", "")) + if db.IsUniqueViolation(err) { + writeErr(w, apierror.Conflict("username_taken", "username is already taken")) return } writeErrWithLog(w, h.logger, "admin create user: insert failed", apierror.Internal(err)) @@ -187,13 +180,12 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request) map[string]any{"is_admin": req.IsAdmin}) writeJSON(w, http.StatusOK, adminUserView{ - ID: uuidToString(user.ID), - Username: user.Username, - DisplayName: user.DisplayName, - IsAdmin: user.IsAdmin, - AutoApproveRequests: user.AutoApproveRequests, - DebugModeEnabled: user.DebugModeEnabled, - CreatedAt: user.CreatedAt.Time.UTC().Format(time.RFC3339), + ID: uuidToString(user.ID), + Username: user.Username, + DisplayName: user.DisplayName, + IsAdmin: user.IsAdmin, + DebugModeEnabled: user.DebugModeEnabled, + CreatedAt: user.CreatedAt.Time.UTC().Format(time.RFC3339), }) } @@ -256,8 +248,7 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque if !decodeBody(w, r, &req) { return } - if len(req.Password) < minPasswordLength { - writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars")) + if !checkNewPassword(w, req.Password) { return } @@ -272,7 +263,7 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque return } - hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) + hash, err := hashPassword(req.Password) if err != nil { writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err)) return @@ -285,9 +276,10 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque return } - // The target's existing sessions end with the old password. An admin - // resetting their own password keeps the session they're using, the - // same as a self-service change. + // The target's existing sessions end with the old password, and so does + // their Subsonic apps' access (signOutSubsonicApps). An admin resetting + // their own password keeps the session they're using, the same as a + // self-service change. sessID, ownSession := auth.SessionIDFromContext(r.Context()) if targetID == caller.ID && ownSession { _, err = q.DeleteOtherSessionsForUser(r.Context(), dbq.DeleteOtherSessionsForUserParams{UserID: targetID, ID: sessID}) @@ -297,56 +289,11 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque if err != nil { h.logger.Error("admin reset password: revoke sessions failed", "err", err) } + if err := h.signOutSubsonicApps(r.Context(), targetID); err != nil { + h.logger.Error("admin reset password: sign out subsonic apps failed", "err", err) + } audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionPasswordResetAdmin, nil) w.WriteHeader(http.StatusNoContent) } - -// --- Admin auto-approve toggle --------------------------------------------- - -type adminAutoApproveReq struct { - AutoApprove bool `json:"auto_approve"` -} - -func (h *handlers) handleAdminAutoApproveToggle(w http.ResponseWriter, r *http.Request) { - caller, ok := requireUser(w, r) - if !ok { - return - } - targetID, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - var req adminAutoApproveReq - if !decodeBody(w, r, &req) { - return - } - - q := dbq.New(h.pool) - updated, err := q.UpdateUserAutoApprove(r.Context(), dbq.UpdateUserAutoApproveParams{ - ID: targetID, - AutoApproveRequests: req.AutoApprove, - }) - if err != nil { - if errors.Is(err, pgx.ErrNoRows) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""}) - return - } - writeErrWithLog(w, h.logger, "admin auto-approve: update failed", apierror.Internal(err)) - return - } - - audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionAutoApproveToggle, - map[string]any{"auto_approve": req.AutoApprove}) - - writeJSON(w, http.StatusOK, adminUserView{ - ID: uuidToString(updated.ID), - Username: updated.Username, - DisplayName: updated.DisplayName, - IsAdmin: updated.IsAdmin, - AutoApproveRequests: updated.AutoApproveRequests, - DebugModeEnabled: updated.DebugModeEnabled, - CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339), - }) -} diff --git a/internal/api/admin_users_test.go b/internal/api/admin_users_test.go index 6895fb72..ce9320e4 100644 --- a/internal/api/admin_users_test.go +++ b/internal/api/admin_users_test.go @@ -6,13 +6,13 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func newAdminUsersRouter(h *handlers) chi.Router { @@ -25,15 +25,11 @@ func newAdminUsersRouter(h *handlers) chi.Router { admin.Post("/users", h.handleAdminCreateUser) admin.Delete("/users/{id}", h.handleAdminDeleteUser) admin.Post("/users/{id}/reset-password", h.handleAdminResetPassword) - admin.Put("/users/{id}/auto-approve", h.handleAdminAutoApproveToggle) }) return r } func TestAdminUsers_List(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "listadmin", "pw", true) @@ -57,9 +53,6 @@ func TestAdminUsers_List(t *testing.T) { } func TestAdminUsers_Promote(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "promadmin", "pw", true) target := seedUser(t, pool, "promtarget", "pw", false) @@ -84,56 +77,7 @@ func TestAdminUsers_Promote(t *testing.T) { } } -func TestAdminUsers_Demote_LastAdmin_Refused(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - // Reset to ensure exactly one admin exists. - if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { - t.Fatalf("reset: %v", err) - } - soleAdmin := seedUser(t, pool, "soleadmin", "pw", true) - - body := `{"is_admin": false}` - req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(soleAdmin.ID)+"/admin", - bytes.NewReader([]byte(body))) - req = withUser(req, soleAdmin) - rec := httptest.NewRecorder() - newAdminUsersRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusConflict { - t.Errorf("status = %d, want 409 (last_admin guard)", rec.Code) - } -} - -func TestAdminUsers_Demote_OtherAdmin_Allowed(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { - t.Fatalf("reset: %v", err) - } - caller := seedUser(t, pool, "caller", "pw", true) - target := seedUser(t, pool, "targetadmin", "pw", true) - - body := `{"is_admin": false}` - req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/admin", - bytes.NewReader([]byte(body))) - req = withUser(req, caller) - rec := httptest.NewRecorder() - newAdminUsersRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Errorf("status = %d, want 200 (two admins exist; demoting one is fine); body=%s", rec.Code, rec.Body.String()) - } -} - func TestAdminCreateUser_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "creator", "pw", true) @@ -156,9 +100,6 @@ func TestAdminCreateUser_Happy(t *testing.T) { } func TestAdminCreateUser_DuplicateUsername_409(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "duper", "pw", true) seedUser(t, pool, "existing", "pw", false) @@ -178,9 +119,6 @@ func TestAdminCreateUser_DuplicateUsername_409(t *testing.T) { } func TestAdminDeleteUser_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "delcaller", "pw", true) target := seedUser(t, pool, "deltarget", "pw", false) @@ -204,9 +142,6 @@ func TestAdminDeleteUser_Happy(t *testing.T) { } func TestAdminDeleteUser_LastAdmin_Refused(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { t.Fatalf("reset: %v", err) @@ -224,9 +159,6 @@ func TestAdminDeleteUser_LastAdmin_Refused(t *testing.T) { } func TestAdminResetPassword_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rcaller", "pw", true) target := seedUser(t, pool, "rtarget", "oldpw1234", false) @@ -253,9 +185,6 @@ func TestAdminResetPassword_Happy(t *testing.T) { } func TestAdminResetPassword_TooShort_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rsadm", "pw", true) target := seedUser(t, pool, "rstgt", "pw", false) @@ -272,39 +201,47 @@ func TestAdminResetPassword_TooShort_400(t *testing.T) { } } -func TestAdminAutoApproveToggle(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } +func TestAdminResetPassword_SignsOutSubsonicApps(t *testing.T) { h, pool := testHandlers(t) - admin := seedUser(t, pool, "aacaller", "pw", true) - target := seedUser(t, pool, "aatarget", "pw", false) + admin := seedUser(t, pool, "rsubadm", "pw", true) + target := seedUser(t, pool, "rsubtgt", "oldpw1234", false) + giveSubsonicPassword(t, h, target) + before, _ := subsonicCredentials(t, h, target) - body := `{"auto_approve":true}` - req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/auto-approve", - bytes.NewReader([]byte(body))) - req = withUser(req, admin) + req := httptest.NewRequest(http.MethodPost, "/api/admin/users/"+uuidToString(target.ID)+"/reset-password", + bytes.NewReader([]byte(`{"password":"newpassword1"}`))) rec := httptest.NewRecorder() - newAdminUsersRouter(h).ServeHTTP(rec, req) + newAdminUsersRouter(h).ServeHTTP(rec, withUser(req, admin)) + if rec.Code != http.StatusNoContent { + t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String()) + } + assertSubsonicSignedOut(t, h, target, before) +} - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - var resp adminUserView - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if !resp.AutoApproveRequests { - t.Errorf("auto_approve_requests = false on response; expected true") +// An admin can take admin away from another admin, but never from the last +// one: the server always keeps someone who can manage it. +func TestAdminUsers_DemotingStopsAtTheLastAdmin(t *testing.T) { + h, pool := testHandlers(t) + if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { + t.Fatalf("reset: %v", err) } + caller := seedUser(t, pool, "caller", "pw", true) + other := seedUser(t, pool, "otheradmin", "pw", true) - // Verify DB. - var aa bool - if err := pool.QueryRow(context.Background(), - "SELECT auto_approve_requests FROM users WHERE id = $1", target.ID).Scan(&aa); err != nil { - t.Fatalf("verify: %v", err) - } - if !aa { - t.Errorf("DB row not updated") + for _, step := range []struct { + target dbq.User + status int + }{ + {other, http.StatusOK}, // two admins: one can go + {caller, http.StatusConflict}, // the last admin stays + } { + req := withUser(httptest.NewRequest(http.MethodPut, + "/api/admin/users/"+uuidToString(step.target.ID)+"/admin", + bytes.NewReader([]byte(`{"is_admin": false}`))), caller) + rec := httptest.NewRecorder() + newAdminUsersRouter(h).ServeHTTP(rec, req) + if rec.Code != step.status { + t.Errorf("demote %s: status %d, want %d; body=%s", step.target.Username, rec.Code, step.status, rec.Body.String()) + } } } diff --git a/internal/api/admin_wanted.go b/internal/api/admin_wanted.go deleted file mode 100644 index 0cb28b80..00000000 --- a/internal/api/admin_wanted.go +++ /dev/null @@ -1,821 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" -) - -// The wanted list's admin surface: wants, follows and -// release-type profiles. - -// wantView is one row of GET /api/admin/wanted. -type wantView struct { - ID string `json:"id"` - ReleaseGroupMBID string `json:"release_group_mbid"` - Title string `json:"title"` - ArtistMBID string `json:"artist_mbid"` - ArtistName string `json:"artist_name"` - ArtistID string `json:"artist_id,omitempty"` - PrimaryType string `json:"primary_type"` - SecondaryTypes []string `json:"secondary_types"` - Year string `json:"year"` - Reason string `json:"reason"` - RequestedBy string `json:"requested_by,omitempty"` - AlbumID string `json:"album_id,omitempty"` - WantedAt string `json:"wanted_at"` - HeldAt *string `json:"held_at"` - ImageURL string `json:"image_url"` - // Upgrade: why a held album is wanted again, quality or rip, and - // HeldQuality what the library's copy is. - Upgrade string `json:"upgrade,omitempty"` - HeldQuality string `json:"held_quality,omitempty"` - // Search is the schedule's last look; Grab the download running. - Search *wantSearchView `json:"search"` - Grab *wantGrabView `json:"grab"` -} - -type wantSearchView struct { - SearchedAt string `json:"searched_at"` - Outcome string `json:"outcome"` - Considered int32 `json:"considered"` - BestRelease string `json:"best_release"` - BestVerdict string `json:"best_verdict"` - Error string `json:"error"` -} - -// wantGrabView is the want's latest download, running or ended, and what -// its import made of it. -type wantGrabView struct { - ID string `json:"id"` - Name string `json:"name"` - GrabbedAt string `json:"grabbed_at"` - Origin string `json:"origin"` - Quality string `json:"quality"` - Live bool `json:"live"` - EndReason string `json:"end_reason"` - Progress float32 `json:"progress"` - ImportState string `json:"import_state"` - ImportReason string `json:"import_reason"` - EndDetail string `json:"end_detail"` - ImportedAt *string `json:"imported_at"` - ImportedFiles int32 `json:"imported_files"` -} - -// wantCounts sizes each tab of the Wanted page. Artists: how many artists -// the list holds albums of, its main page. -type wantCounts struct { - Artists int64 `json:"artists"` - // Unmatched: library albums waiting to be matched by hand. - Unmatched int64 `json:"unmatched"` - Wanted int64 `json:"wanted"` - Missing int64 `json:"missing"` - Held int64 `json:"held"` - // Upgrades: held albums wanted for a better copy. - Upgrades int64 `json:"upgrades"` - Following int64 `json:"following"` - // Activity: downloads running; Attention: of those, the ones waiting on - // a person; Blocked: releases set aside. - Activity int64 `json:"activity"` - Attention int64 `json:"attention"` - Blocked int64 `json:"blocked"` -} - -type wantsPage struct { - Items []wantView `json:"items"` - Total int64 `json:"total"` - Limit int `json:"limit"` - Offset int `json:"offset"` - Counts wantCounts `json:"counts"` - // Library is the one-time listing of the library's albums. - Library libraryListingView `json:"library"` - // Artist heads one artist's page, when the list is narrowed to them. - Artist *wantArtistView `json:"artist,omitempty"` -} - -// wantArtistView is one artist on the Wanted view's main page: how -// many of their albums the list holds, of how many. -type wantArtistView struct { - ArtistMBID string `json:"artist_mbid"` - ArtistName string `json:"artist_name"` - SortName string `json:"sort_name"` - ArtistID string `json:"artist_id,omitempty"` - ImageURL string `json:"image_url"` - Albums int32 `json:"albums"` - Held int32 `json:"held"` - Wanted int32 `json:"wanted"` - Missing int32 `json:"missing"` - Downloading int32 `json:"downloading"` - Following bool `json:"following"` -} - -type wantArtistsPage struct { - Items []wantArtistView `json:"items"` - Total int64 `json:"total"` - Limit int `json:"limit"` - Offset int `json:"offset"` - Counts wantCounts `json:"counts"` - Library libraryListingView `json:"library"` -} - -// libraryListingView: whether the library's albums are all on the list -// yet, and how many could not be matched to MusicBrainz; those are -// listed in the Collection's Unmatched section. -type libraryListingView struct { - ListedAt *string `json:"listed_at"` - Unlisted int32 `json:"unlisted"` -} - -// unmatchedAlbumView is one album in the Collection's Unmatched section: why -// no MusicBrainz album matched it, or that a person left it off. -type unmatchedAlbumView struct { - AlbumID string `json:"album_id"` - Title string `json:"title"` - Artist string `json:"artist"` - Detail string `json:"detail"` - Tracks int32 `json:"tracks"` - LeftOff bool `json:"left_off"` - DecidedAt string `json:"decided_at"` -} - -// unmatchedShown bounds the Unmatched section: a library a listing could -// not match more of than this has a bigger problem than one page shows. -const unmatchedShown = 500 - -const wantsPageSize = 50 - -// wantArtistsPageSize fills a few rows of the artist grid a page. -const wantArtistsPageSize = 96 - -// wantsHeader is what every Collection page carries: each section's count, -// and how the one-time library listing went. -func (h *handlers) wantsHeader(r *http.Request, q *dbq.Queries) (wantCounts, libraryListingView, error) { - counts, err := q.CountWants(r.Context()) - if err != nil { - return wantCounts{}, libraryListingView{}, err - } - listing, err := q.GetLibraryListing(r.Context()) - if err != nil { - return wantCounts{}, libraryListingView{}, err - } - lib := libraryListingView{Unlisted: listing.LibraryUnlisted} - if listing.LibraryListedAt.Valid { - at := formatTimestamp(listing.LibraryListedAt) - lib.ListedAt = &at - } - return wantCounts{Artists: counts.Artists, Unmatched: counts.Unmatched, Wanted: counts.Wanted, Missing: counts.Missing, Held: counts.Held, - Upgrades: counts.Upgrades, Following: counts.Following, Activity: counts.Activity, Attention: counts.Attention, Blocked: counts.Blocked}, lib, nil -} - -func offsetParam(r *http.Request) int { - offset, _ := strconv.Atoi(r.URL.Query().Get("offset")) - return max(offset, 0) -} - -func wantArtistViewOf(row dbq.ListWantArtistsRow) wantArtistView { - v := wantArtistView{ - ArtistMBID: row.ArtistMbid, ArtistName: row.ArtistName, SortName: row.SortName, - ImageURL: artistArtURL(row.ArtistMbid, row.ArtistName), - Albums: row.Albums, Held: row.Held, Wanted: row.Wanted, Missing: row.Missing, - Downloading: row.Downloading, Following: row.Following, - } - if row.LibraryArtistID.Valid { - v.ArtistID = uuidToString(row.LibraryArtistID) - } - return v -} - -// handleListWantArtists implements GET /api/admin/wanted/artists?q=&offset=: -// the Wanted view's main page, every artist on the list A–Z. -func (h *handlers) handleListWantArtists(w http.ResponseWriter, r *http.Request) { - offset := offsetParam(r) - q := dbq.New(h.pool) - rows, err := q.ListWantArtists(r.Context(), dbq.ListWantArtistsParams{ - Q: strings.TrimSpace(r.URL.Query().Get("q")), Skip: int32(offset), MaxRows: wantArtistsPageSize}) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: artists", apierror.Internal(err)) - return - } - counts, lib, err := h.wantsHeader(r, q) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: counts", apierror.Internal(err)) - return - } - out := wantArtistsPage{Items: make([]wantArtistView, 0, len(rows)), Limit: wantArtistsPageSize, Offset: offset, - Counts: counts, Library: lib} - for _, row := range rows { - out.Total = row.Total - out.Items = append(out.Items, wantArtistViewOf(row)) - } - writeJSON(w, http.StatusOK, out) -} - -// handleListWants implements GET -// /api/admin/wanted?state=wanted|missing|upgrade|held|all&artist=&q=&offset=. -// wanted is everything open but missing files; upgrade the held albums wanted -// for a better copy. Each list runs artist by artist, A–Z, like the library; q -// narrows it to an artist or album, and artist to one artist's page, which it -// then heads. -func (h *handlers) handleListWants(w http.ResponseWriter, r *http.Request) { - state := r.URL.Query().Get("state") - if state == "" { - state = "wanted" - } - if state != "wanted" && state != "missing" && state != "upgrade" && state != "held" && state != "all" { - writeErr(w, apierror.BadRequest("bad_state", "state must be wanted, missing, upgrade, held or all")) - return - } - offset := offsetParam(r) - artist := strings.TrimSpace(r.URL.Query().Get("artist")) - q := dbq.New(h.pool) - rows, err := q.ListWants(r.Context(), dbq.ListWantsParams{State: state, ArtistMbid: artist, - Q: strings.TrimSpace(r.URL.Query().Get("q")), Skip: int32(offset), MaxRows: wantsPageSize}) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: list", apierror.Internal(err)) - return - } - counts, lib, err := h.wantsHeader(r, q) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: counts", apierror.Internal(err)) - return - } - out := wantsPage{Library: lib, Counts: counts, - Items: make([]wantView, 0, len(rows)), Limit: wantsPageSize, Offset: offset} - if artist != "" { - heads, err := q.ListWantArtists(r.Context(), dbq.ListWantArtistsParams{ArtistMbid: artist, MaxRows: 1}) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: artist", apierror.Internal(err)) - return - } - if len(heads) == 0 { - writeErr(w, apierror.NotFound("artist")) - return - } - v := wantArtistViewOf(heads[0]) - out.Artist = &v - } - for _, row := range rows { - out.Total = row.Total - out.Items = append(out.Items, wantViewOf(row)) - } - writeJSON(w, http.StatusOK, out) -} - -// wantViewOf is one ListWants row as the wanted list and the Missing page -// send it. -func wantViewOf(row dbq.ListWantsRow) wantView { - v := wantView{ - ID: uuidToString(row.ID), ReleaseGroupMBID: row.ReleaseGroupMbid, Title: row.Title, - ArtistMBID: row.ArtistMbid, ArtistName: row.ArtistName, - PrimaryType: row.PrimaryType, SecondaryTypes: row.SecondaryTypes, - Year: first4(row.FirstReleaseDate), Reason: row.Reason, - WantedAt: formatTimestamp(row.WantedAt), Upgrade: row.Upgrade, HeldQuality: row.HeldQuality, - ImageURL: groupArtURL(musicbrainz.ReleaseGroup{MBID: row.ReleaseGroupMbid, Title: row.Title, ArtistCredit: row.ArtistName}), - } - if row.LibraryArtistID.Valid { - v.ArtistID = uuidToString(row.LibraryArtistID) - } - if row.AlbumID.Valid { - v.AlbumID = uuidToString(row.AlbumID) - } - if row.RequestedBy != nil { - v.RequestedBy = *row.RequestedBy - } - if row.FulfilledAt.Valid { - held := formatTimestamp(row.FulfilledAt) - v.HeldAt = &held - } - if v.SecondaryTypes == nil { - v.SecondaryTypes = []string{} - } - if row.SearchedAt.Valid { - v.Search = &wantSearchView{ - SearchedAt: formatTimestamp(row.SearchedAt), Outcome: row.SearchOutcome, - Considered: row.SearchConsidered, BestRelease: row.BestRelease, - BestVerdict: row.BestVerdict, Error: row.SearchError, - } - } - if row.GrabName != nil { - v.Grab = &wantGrabView{ID: uuidToString(row.GrabID), Name: *row.GrabName, - GrabbedAt: formatTimestamp(row.GrabbedAt), Live: !row.GrabEndedAt.Valid, - Origin: deref(row.GrabOrigin), Quality: deref(row.GrabQuality), EndReason: deref(row.GrabEndReason), - ImportState: deref(row.GrabImportState), ImportReason: deref(row.GrabImportReason), - EndDetail: deref(row.GrabEndDetail)} - if row.GrabProgress != nil { - v.Grab.Progress = *row.GrabProgress - } - if row.GrabImportedFiles != nil { - v.Grab.ImportedFiles = *row.GrabImportedFiles - } - if row.GrabImportedAt.Valid { - at := formatTimestamp(row.GrabImportedAt) - v.Grab.ImportedAt = &at - } - } - return v -} - -// wantTracksView is an album's track list for the Wanted view: the -// library's own tracks for an album it holds or held, else MusicBrainz's -// standard edition of what is wanted. -type wantTracksView struct { - // library, musicbrainz, or none when MusicBrainz lists no edition. - Source string `json:"source"` - // Edition names the MusicBrainz release the list is from. - Edition string `json:"edition,omitempty"` - Tracks []wantTrackView `json:"tracks"` -} - -type wantTrackView struct { - Disc int32 `json:"disc"` - Number int32 `json:"number"` - Title string `json:"title"` - LengthMs int32 `json:"length_ms"` - // Missing: the library's file for it is gone. - Missing bool `json:"missing"` -} - -// handleWantTracks implements GET /api/admin/wanted/{id}/tracks. -func (h *handlers) handleWantTracks(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - q := dbq.New(h.pool) - want, err := q.GetWantAlbum(r.Context(), id) - if errors.Is(err, pgx.ErrNoRows) { - writeErr(w, apierror.NotFound("want")) - return - } - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: tracks", apierror.Internal(err)) - return - } - out := wantTracksView{Tracks: []wantTrackView{}} - if want.AlbumID.Valid { - rows, err := q.ListLibraryAlbumTracks(r.Context(), want.AlbumID) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: library tracks", apierror.Internal(err)) - return - } - out.Source = "library" - for _, t := range rows { - v := wantTrackView{Title: t.Title, LengthMs: t.DurationMs, Missing: t.Missing} - if t.DiscNumber != nil { - v.Disc = *t.DiscNumber - } - if t.TrackNumber != nil { - v.Number = *t.TrackNumber - } - out.Tracks = append(out.Tracks, v) - } - writeJSON(w, http.StatusOK, out) - return - } - eds, err := h.catalogue.Releases(r.Context(), want.ReleaseGroupMbid) - switch { - case errors.Is(err, catalogue.ErrNotFound): - out.Source = "none" - writeJSON(w, http.StatusOK, out) - return - case errors.Is(err, musicbrainz.ErrUnreachable), errors.Is(err, musicbrainz.ErrBadResponse): - writeErr(w, &apierror.Error{Status: 503, Code: "musicbrainz_unreachable", Message: "MusicBrainz can't be reached", Cause: err}) - return - case err != nil: - writeErrWithLog(w, h.logger, "admin wanted: editions", apierror.Internal(err)) - return - } - e, ok := standardEdition(eds.Editions) - if !ok { - out.Source = "none" - writeJSON(w, http.StatusOK, out) - return - } - out.Source = "musicbrainz" - out.Edition = editionLabel(e.Release) - for _, t := range e.Tracks { - out.Tracks = append(out.Tracks, wantTrackView{Disc: t.MediumPosition, Number: t.Position, Title: t.Title, LengthMs: t.LengthMs}) - } - writeJSON(w, http.StatusOK, out) -} - -// standardEdition is the edition a person would call the album: an official -// one with the fewest tracks, else any with the fewest. The catalogue lists -// official editions first by date, so a tie goes to the earliest. -func standardEdition(eds []catalogue.Edition) (catalogue.Edition, bool) { - best := -1 - for i, e := range eds { - if len(e.Tracks) == 0 { - continue - } - if best < 0 { - best = i - continue - } - b := eds[best] - bo, eo := b.Release.Status == "Official", e.Release.Status == "Official" - if (eo && !bo) || (eo == bo && len(e.Tracks) < len(b.Tracks)) { - best = i - } - } - if best < 0 { - return catalogue.Edition{}, false - } - return eds[best], true -} - -// editionLabel names a release for a person: "2023 · CD · GB". -func editionLabel(r dbq.MbRelease) string { - var parts []string - for _, p := range []string{first4(r.ReleaseDate), r.Formats, r.Country} { - if p != "" { - parts = append(parts, p) - } - } - return strings.Join(parts, " · ") -} - -func first4(date string) string { - if len(date) < 4 { - return "" - } - return date[:4] -} - -// handleRemoveWant implements DELETE /api/admin/wanted/{id}. -func (h *handlers) handleRemoveWant(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - removed, err := h.wanted.RemoveWant(r.Context(), id) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: remove", apierror.Internal(err)) - return - } - if !removed { - writeErr(w, apierror.NotFound("want")) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// followView is a followed artist. -type followView struct { - ArtistMBID string `json:"artist_mbid"` - ArtistName string `json:"artist_name"` - ArtistID string `json:"artist_id,omitempty"` - ProfileID string `json:"profile_id"` - ProfileName string `json:"profile_name"` - FollowedAt string `json:"followed_at"` - CheckedAt *string `json:"checked_at"` - OpenWants int64 `json:"open_wants"` - ImageURL string `json:"image_url"` -} - -// handleListFollows implements GET /api/admin/follows. -func (h *handlers) handleListFollows(w http.ResponseWriter, r *http.Request) { - rows, err := dbq.New(h.pool).ListFollows(r.Context()) - if err != nil { - writeErrWithLog(w, h.logger, "admin follows: list", apierror.Internal(err)) - return - } - out := make([]followView, 0, len(rows)) - for _, f := range rows { - v := followView{ - ArtistMBID: f.ArtistMbid, ArtistName: f.ArtistName, - ProfileID: uuidToString(f.ProfileID), ProfileName: f.ProfileName, - FollowedAt: formatTimestamp(f.FollowedAt), OpenWants: f.OpenWants, - ImageURL: artistArtURL(f.ArtistMbid, f.ArtistName), - } - if f.ArtistID.Valid { - v.ArtistID = uuidToString(f.ArtistID) - } - if f.CheckedAt.Valid { - checked := formatTimestamp(f.CheckedAt) - v.CheckedAt = &checked - } - out = append(out, v) - } - writeJSON(w, http.StatusOK, out) -} - -// followStateView answers whether one artist is followed, for the control on -// an artist page. -type followStateView struct { - Following bool `json:"following"` - ProfileID string `json:"profile_id,omitempty"` - ProfileName string `json:"profile_name,omitempty"` -} - -// handleGetFollow implements GET /api/admin/follows/{mbid}. -func (h *handlers) handleGetFollow(w http.ResponseWriter, r *http.Request) { - f, err := dbq.New(h.pool).GetFollow(r.Context(), chi.URLParam(r, "mbid")) - if errors.Is(err, pgx.ErrNoRows) { - writeJSON(w, http.StatusOK, followStateView{}) - return - } - if err != nil { - writeErrWithLog(w, h.logger, "admin follows: get", apierror.Internal(err)) - return - } - writeJSON(w, http.StatusOK, followStateView{ - Following: true, ProfileID: uuidToString(f.ProfileID), ProfileName: f.ProfileName, - }) -} - -type putFollowBody struct { - ArtistName string `json:"artist_name"` - ProfileID string `json:"profile_id"` - WantExisting bool `json:"want_existing"` -} - -// handlePutFollow implements PUT /api/admin/follows/{mbid}: follow an artist, -// or change the profile it is followed on. want_existing also wants what the -// artist has already released that the profile passes and isn't held. -func (h *handlers) handlePutFollow(w http.ResponseWriter, r *http.Request) { - admin, ok := requireUser(w, r) - if !ok { - return - } - var body putFollowBody - if !decodeBody(w, r, &body) { - return - } - var profile pgtype.UUID - if body.ProfileID != "" { - if profile, ok = parseUUID(body.ProfileID); !ok { - writeErr(w, apierror.BadRequest("bad_profile", "profile_id is not an id")) - return - } - } - mbid := chi.URLParam(r, "mbid") - if _, err := h.wanted.Follow(r.Context(), wanted.FollowParams{ - ArtistMBID: mbid, ArtistName: body.ArtistName, ProfileID: profile, - By: admin.ID, WantExisting: body.WantExisting, - }); err != nil { - switch { - case errors.Is(err, wanted.ErrNotFollowable): - writeErr(w, apierror.BadRequest("not_followable", "Various Artists and MusicBrainz placeholders can't be followed")) - case errors.Is(err, wanted.ErrProfileNotFound): - writeErr(w, apierror.BadRequest("profile_not_found", "no such profile")) - default: - writeErrWithLog(w, h.logger, "admin follows: put", apierror.Internal(err)) - } - return - } - h.handleGetFollow(w, r) -} - -// handleDeleteFollow implements DELETE /api/admin/follows/{mbid}. What the -// follow already wanted stays on the list. -func (h *handlers) handleDeleteFollow(w http.ResponseWriter, r *http.Request) { - removed, err := h.wanted.Unfollow(r.Context(), chi.URLParam(r, "mbid")) - if err != nil { - writeErrWithLog(w, h.logger, "admin follows: delete", apierror.Internal(err)) - return - } - if !removed { - writeErr(w, apierror.NotFound("follow")) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// releaseProfileView is a release-type profile. -type releaseProfileView struct { - ID string `json:"id"` - Name string `json:"name"` - PrimaryTypes []string `json:"primary_types"` - SecondaryTypes []string `json:"secondary_types"` - IsDefault bool `json:"is_default"` - FollowCount int64 `json:"follow_count"` -} - -// releaseProfilesResponse also carries MusicBrainz's types, so the editor -// offers exactly what a profile may hold. -type releaseProfilesResponse struct { - Profiles []releaseProfileView `json:"profiles"` - PrimaryTypes []string `json:"primary_types"` - SecondaryTypes []string `json:"secondary_types"` -} - -// handleListReleaseProfiles implements GET /api/admin/release-profiles. -func (h *handlers) handleListReleaseProfiles(w http.ResponseWriter, r *http.Request) { - rows, err := dbq.New(h.pool).ListReleaseTypeProfiles(r.Context()) - if err != nil { - writeErrWithLog(w, h.logger, "admin release profiles: list", apierror.Internal(err)) - return - } - out := releaseProfilesResponse{ - Profiles: make([]releaseProfileView, 0, len(rows)), - PrimaryTypes: wanted.PrimaryTypes, SecondaryTypes: wanted.SecondaryTypes, - } - for _, p := range rows { - out.Profiles = append(out.Profiles, releaseProfileView{ - ID: uuidToString(p.ID), Name: p.Name, PrimaryTypes: p.PrimaryTypes, - SecondaryTypes: p.SecondaryTypes, IsDefault: p.IsDefault, FollowCount: p.FollowCount, - }) - } - writeJSON(w, http.StatusOK, out) -} - -type releaseProfileBody struct { - Name string `json:"name"` - PrimaryTypes []string `json:"primary_types"` - SecondaryTypes []string `json:"secondary_types"` - IsDefault bool `json:"is_default"` -} - -func (b releaseProfileBody) input() wanted.ProfileInput { - return wanted.ProfileInput{ - Name: b.Name, PrimaryTypes: b.PrimaryTypes, SecondaryTypes: b.SecondaryTypes, IsDefault: b.IsDefault, - } -} - -// handleCreateReleaseProfile implements POST /api/admin/release-profiles. -func (h *handlers) handleCreateReleaseProfile(w http.ResponseWriter, r *http.Request) { - var body releaseProfileBody - if !decodeBody(w, r, &body) { - return - } - p, err := h.wanted.CreateProfile(r.Context(), body.input()) - if err != nil { - h.writeProfileErr(w, err) - return - } - writeJSON(w, http.StatusCreated, releaseProfileView{ - ID: uuidToString(p.ID), Name: p.Name, PrimaryTypes: p.PrimaryTypes, - SecondaryTypes: p.SecondaryTypes, IsDefault: p.IsDefault, - }) -} - -// handleUpdateReleaseProfile implements PUT /api/admin/release-profiles/{id}. -// A follow on the profile judges new releases by the new types from its next -// check; releases it has already judged are not judged again. -func (h *handlers) handleUpdateReleaseProfile(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - var body releaseProfileBody - if !decodeBody(w, r, &body) { - return - } - p, err := h.wanted.UpdateProfile(r.Context(), id, body.input()) - if err != nil { - h.writeProfileErr(w, err) - return - } - writeJSON(w, http.StatusOK, releaseProfileView{ - ID: uuidToString(p.ID), Name: p.Name, PrimaryTypes: p.PrimaryTypes, - SecondaryTypes: p.SecondaryTypes, IsDefault: p.IsDefault, - }) -} - -// handleDeleteReleaseProfile implements DELETE -// /api/admin/release-profiles/{id}. -func (h *handlers) handleDeleteReleaseProfile(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - if err := h.wanted.DeleteProfile(r.Context(), id); err != nil { - h.writeProfileErr(w, err) - return - } - w.WriteHeader(http.StatusNoContent) -} - -func (h *handlers) writeProfileErr(w http.ResponseWriter, err error) { - switch { - case errors.Is(err, wanted.ErrProfileInvalid): - writeErr(w, apierror.BadRequest("profile_invalid", err.Error())) - case errors.Is(err, wanted.ErrProfileNotFound): - writeErr(w, apierror.NotFound("profile")) - case errors.Is(err, wanted.ErrProfileNameUsed): - writeErr(w, apierror.Conflict("profile_name_taken", "a profile already has that name")) - case errors.Is(err, wanted.ErrProfileInUse): - writeErr(w, apierror.Conflict("profile_in_use", "artists are followed on this profile; move them first")) - case errors.Is(err, wanted.ErrProfileDefault): - writeErr(w, apierror.Conflict("profile_is_default", "the default profile can't be deleted")) - default: - writeErrWithLog(w, h.logger, "admin release profiles", apierror.Internal(err)) - } -} - -// deref is a nullable column's text, or "". -func deref(s *string) string { - if s == nil { - return "" - } - return *s -} - -// handleListUnmatched implements GET /api/admin/wanted/unmatched: the -// Collection's Unmatched section, the albums no MusicBrainz album -// matched and, after them, the ones a person left off. -func (h *handlers) handleListUnmatched(w http.ResponseWriter, r *http.Request) { - rows, err := dbq.New(h.pool).ListUnmatchedLibraryAlbums(r.Context(), unmatchedShown) - if err != nil { - writeErrWithLog(w, h.logger, "admin wanted: unmatched", apierror.Internal(err)) - return - } - out := struct { - Items []unmatchedAlbumView `json:"items"` - }{Items: make([]unmatchedAlbumView, 0, len(rows))} - for _, u := range rows { - out.Items = append(out.Items, unmatchedAlbumView{ - AlbumID: uuidToString(u.AlbumID), Title: u.Title, Artist: u.ArtistName, Detail: u.Detail, - Tracks: u.Tracks, LeftOff: u.Outcome == "dismissed", DecidedAt: formatTimestamp(u.DecidedAt), - }) - } - writeJSON(w, http.StatusOK, out) -} - -type manualMatchView struct { - ReleaseGroupMBID string `json:"release_group_mbid"` - Title string `json:"title"` - Artist string `json:"artist"` - Agree int `json:"agree"` - Tracks int `json:"tracks"` -} - -// handleMatchUnmatched implements POST /api/admin/wanted/unmatched/{id}/match -// {"ref": ""}: the album goes on the list as held, -// as that MusicBrainz album. -func (h *handlers) handleMatchUnmatched(w http.ResponseWriter, r *http.Request) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - var body struct { - Ref string `json:"ref"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - writeErr(w, apierror.BadRequest("bad_body", "expected {\"ref\": \"…\"}")) - return - } - m, err := h.wanted.MatchAlbumTo(r.Context(), id, body.Ref) - switch { - case errors.Is(err, wanted.ErrMatchRef): - writeErr(w, apierror.BadRequest("bad_ref", "That isn't a MusicBrainz album link or id.")) - return - case errors.Is(err, wanted.ErrMatchNoGroup): - writeErr(w, &apierror.Error{Status: http.StatusUnprocessableEntity, Code: "no_such_album", - Message: "MusicBrainz has no album at that link.", Cause: err}) - return - case errors.Is(err, wanted.ErrAlbumNotUnmatched): - writeErr(w, apierror.NotFound("unmatched album")) - return - case errors.Is(err, musicbrainz.ErrUnreachable), errors.Is(err, musicbrainz.ErrBadResponse): - writeErr(w, &apierror.Error{Status: http.StatusServiceUnavailable, Code: "musicbrainz_unreachable", - Message: "MusicBrainz can't be reached", Cause: err}) - return - case err != nil: - writeErrWithLog(w, h.logger, "admin wanted: match by hand", apierror.Internal(err)) - return - } - writeJSON(w, http.StatusOK, manualMatchView{ReleaseGroupMBID: m.Group, Title: m.Title, Artist: m.Artist, - Agree: m.Agree, Tracks: m.Tracks}) -} - -// handleLeaveUnmatchedOff implements POST -// /api/admin/wanted/unmatched/{id}/leave-off, and handlePutUnmatchedBack its -// undoing, POST …/{id}/put-back. -func (h *handlers) handleLeaveUnmatchedOff(w http.ResponseWriter, r *http.Request) { - h.setUnmatched(w, r, h.wanted.LeaveAlbumOff) -} - -func (h *handlers) handlePutUnmatchedBack(w http.ResponseWriter, r *http.Request) { - h.setUnmatched(w, r, h.wanted.PutAlbumBack) -} - -func (h *handlers) setUnmatched(w http.ResponseWriter, r *http.Request, set func(context.Context, pgtype.UUID) error) { - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - err := set(r.Context(), id) - switch { - case errors.Is(err, wanted.ErrAlbumNotUnmatched): - writeErr(w, apierror.NotFound("unmatched album")) - case err != nil: - writeErrWithLog(w, h.logger, "admin wanted: unmatched", apierror.Internal(err)) - default: - w.WriteHeader(http.StatusNoContent) - } -} diff --git a/internal/api/admin_wanted_test.go b/internal/api/admin_wanted_test.go deleted file mode 100644 index e80a2edb..00000000 --- a/internal/api/admin_wanted_test.go +++ /dev/null @@ -1,371 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" -) - -func doWantedReq(t *testing.T, h *handlers, path string, user dbq.User) *httptest.ResponseRecorder { - t.Helper() - return doWanted(t, h, http.MethodGet, path, "", user) -} - -func doWanted(t *testing.T, h *handlers, method, path, body string, user dbq.User) *httptest.ResponseRecorder { - t.Helper() - r := chi.NewRouter() - r.Route("/api/admin", func(admin chi.Router) { - admin.Use(auth.RequireAdmin()) - admin.Get("/wanted", h.handleListWants) - admin.Get("/wanted/artists", h.handleListWantArtists) - admin.Get("/wanted/unmatched", h.handleListUnmatched) - admin.Post("/wanted/unmatched/{id}/match", h.handleMatchUnmatched) - admin.Post("/wanted/unmatched/{id}/leave-off", h.handleLeaveUnmatchedOff) - admin.Post("/wanted/unmatched/{id}/put-back", h.handlePutUnmatchedBack) - admin.Get("/wanted/{id}/tracks", h.handleWantTracks) - }) - w := httptest.NewRecorder() - r.ServeHTTP(w, withUser(httptest.NewRequest(method, path, strings.NewReader(body)), user)) - return w -} - -func seedWant(t *testing.T, h *handlers, group, artistMBID, artist, title, date string) dbq.Want { - t.Helper() - w, err := wanted.WantWith(context.Background(), dbq.New(h.pool), wanted.WantParams{ - GroupMBID: group, ArtistMBID: artistMBID, ArtistName: artist, Title: title, - PrimaryType: "Album", FirstReleaseDate: date, Reason: wanted.ReasonFollow, - }) - if err != nil { - t.Fatal(err) - } - return w -} - -func listWanted(t *testing.T, h *handlers, user dbq.User, q string) wantsPage { - t.Helper() - w := doWantedReq(t, h, "/api/admin/wanted?"+url.Values{"q": {q}}.Encode(), user) - if w.Code != http.StatusOK { - t.Fatalf("status = %d; body = %s", w.Code, w.Body.String()) - } - var page wantsPage - if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil { - t.Fatal(err) - } - return page -} - -// The list runs like the library: artists A–Z by the library's sort -// name where the library holds the artist, each artist's albums oldest -// first; q narrows it to an artist or an album. -func TestListWants_ArtistsAToZThenTheirAlbumsByDate(t *testing.T) { - h, _ := testHandlers(t) - admin := seedUser(t, h.pool, "admin", "pw", true) - ctx := context.Background() - beatles := "a0000000-0000-4000-8000-000000000002" - if _, err := dbq.New(h.pool).UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "The Beatles", SortName: "Beatles, The", Mbid: &beatles}); err != nil { - t.Fatal(err) - } - seedWant(t, h, "g0000000-0000-4000-8000-000000000001", "a0000000-0000-4000-8000-000000000003", "Zeds", "Zed Album", "2001") - seedWant(t, h, "g0000000-0000-4000-8000-000000000002", beatles, "The Beatles", "Abbey Road", "1969-09-26") - seedWant(t, h, "g0000000-0000-4000-8000-000000000003", beatles, "The Beatles", "Please Please Me", "1963-03-22") - seedWant(t, h, "g0000000-0000-4000-8000-000000000004", "a0000000-0000-4000-8000-000000000001", "Camel", "Moonmadness", "1976") - - page := listWanted(t, h, admin, "") - var got []string - for _, it := range page.Items { - got = append(got, it.ArtistName+"/"+it.Title) - } - want := "[The Beatles/Please Please Me The Beatles/Abbey Road Camel/Moonmadness Zeds/Zed Album]" - if fmt.Sprint(got) != want { - t.Errorf("order = %v, want %s", got, want) - } - if page.Items[0].ArtistID == "" || page.Items[2].ArtistID != "" { - t.Errorf("artist ids = %q, %q: only an artist the library holds has one", page.Items[0].ArtistID, page.Items[2].ArtistID) - } - - page = listWanted(t, h, admin, "BEATLES") - if len(page.Items) != 2 || page.Total != 2 { - t.Errorf("q=BEATLES: %d items, total %d; want the two Beatles albums", len(page.Items), page.Total) - } - page = listWanted(t, h, admin, "moon") - if len(page.Items) != 1 || page.Items[0].Title != "Moonmadness" || page.Total != 1 { - t.Errorf("q=moon: %+v, total %d", page.Items, page.Total) - } - if page = listWanted(t, h, admin, "nothing like it"); len(page.Items) != 0 || page.Total != 0 { - t.Errorf("no match: %d items, total %d", len(page.Items), page.Total) - } -} - -// The Collection's catalogue: every artist on the list A–Z, each -// with how many of their albums are held; an artist's page lists every album -// of theirs, held or not, under that artist. -func TestListWantArtists_CatalogueAndAnArtistsPage(t *testing.T) { - h, _ := testHandlers(t) - admin := seedUser(t, h.pool, "admin", "pw", true) - ctx := context.Background() - q := dbq.New(h.pool) - beatles := "a0000000-0000-4000-8000-000000000002" - camel := "a0000000-0000-4000-8000-000000000001" - if _, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "The Beatles", SortName: "Beatles, The", Mbid: &beatles}); err != nil { - t.Fatal(err) - } - seedWant(t, h, "g0000000-0000-4000-8000-000000000002", beatles, "The Beatles", "Abbey Road", "1969") - held := seedWant(t, h, "g0000000-0000-4000-8000-000000000003", beatles, "The Beatles", "Please Please Me", "1963") - if _, err := h.pool.Exec(ctx, `UPDATE wants SET fulfilled_at = now() WHERE id = $1`, held.ID); err != nil { - t.Fatal(err) - } - seedWant(t, h, "g0000000-0000-4000-8000-000000000004", camel, "Camel", "Moonmadness", "1976") - if _, err := h.pool.Exec(ctx, `INSERT INTO follows (artist_mbid, artist_name, profile_id) - SELECT $1, 'Camel', id FROM release_type_profiles WHERE is_default`, camel); err != nil { - t.Fatal(err) - } - - w := doWantedReq(t, h, "/api/admin/wanted/artists", admin) - if w.Code != http.StatusOK { - t.Fatalf("status = %d; body = %s", w.Code, w.Body.String()) - } - var page wantArtistsPage - if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil { - t.Fatal(err) - } - if len(page.Items) != 2 || page.Total != 2 || page.Counts.Artists != 2 { - t.Fatalf("catalogue = %+v, total %d, artists %d", page.Items, page.Total, page.Counts.Artists) - } - b, c := page.Items[0], page.Items[1] - if b.ArtistName != "The Beatles" || b.SortName != "Beatles, The" || b.Albums != 2 || b.Held != 1 || b.Wanted != 1 || - b.ArtistID == "" || b.Following || b.ImageURL == "" { - t.Errorf("Beatles = %+v", b) - } - if c.ArtistName != "Camel" || c.Albums != 1 || c.Held != 0 || !c.Following || c.ArtistID != "" { - t.Errorf("Camel = %+v", c) - } - - // q finds an artist by an album's title. - w = doWantedReq(t, h, "/api/admin/wanted/artists?q=moon", admin) - page = wantArtistsPage{} - if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil { - t.Fatal(err) - } - if len(page.Items) != 1 || page.Items[0].ArtistName != "Camel" { - t.Errorf("q=moon: %+v", page.Items) - } - - // The Beatles' page: both albums, held or not, headed by the artist. - w = doWantedReq(t, h, "/api/admin/wanted?state=all&artist="+beatles, admin) - var albums wantsPage - if err := json.Unmarshal(w.Body.Bytes(), &albums); err != nil { - t.Fatal(err) - } - if len(albums.Items) != 2 || albums.Items[0].Title != "Please Please Me" || albums.Items[0].HeldAt == nil || - albums.Artist == nil || albums.Artist.Held != 1 { - t.Errorf("artist page = %+v, head %+v", albums.Items, albums.Artist) - } - if w := doWantedReq(t, h, "/api/admin/wanted?state=all&artist=nobody", admin); w.Code != http.StatusNotFound { - t.Errorf("an artist with nothing on the list: status %d, want 404", w.Code) - } -} - -// fakeEditions is a MusicBrainz holding one group with two editions, the -// shorter official one the standard, or 503 when down is set. -func fakeEditions(t *testing.T, group string, down bool) *httptest.Server { - t.Helper() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if down { - w.WriteHeader(http.StatusServiceUnavailable) - return - } - switch { - case r.URL.Path == "/release-group/"+group: - _, _ = fmt.Fprintf(w, `{"id": %q, "title": "Moonmadness", "primary-type": "Album", "first-release-date": "1976"}`, group) - case r.URL.Path == "/release" && r.URL.Query().Get("release-group") == group: - _, _ = fmt.Fprint(w, `{"release-count": 2, "releases": [ - {"id": "r-deluxe", "title": "Moonmadness", "status": "Official", "date": "2009", "country": "GB", - "media": [{"position": 1, "format": "CD", "tracks": [ - {"position": 1, "number": "1", "title": "Aristillus", "length": 120000, "recording": {"id": "rec-1"}}, - {"position": 2, "number": "2", "title": "Song Within a Song", "length": 433000, "recording": {"id": "rec-2"}}, - {"position": 3, "number": "3", "title": "Bonus", "length": 200000, "recording": {"id": "rec-3"}}]}]}, - {"id": "r-orig", "title": "Moonmadness", "status": "Official", "date": "1976-03", "country": "GB", - "media": [{"position": 1, "format": "12\" Vinyl", "tracks": [ - {"position": 1, "number": "A1", "title": "Aristillus", "length": 120000, "recording": {"id": "rec-1"}}, - {"position": 2, "number": "A2", "title": "Song Within a Song", "length": 433000, "recording": {"id": "rec-2"}}]}]}]}`) - default: - w.WriteHeader(http.StatusNotFound) - } - })) - t.Cleanup(srv.Close) - return srv -} - -func wantTracks(t *testing.T, h *handlers, user dbq.User, id string) (int, wantTracksView) { - t.Helper() - w := doWantedReq(t, h, "/api/admin/wanted/"+id+"/tracks", user) - var out wantTracksView - if w.Code == http.StatusOK { - if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { - t.Fatal(err) - } - } - return w.Code, out -} - -// An album not yet held shows MusicBrainz's standard edition: the shortest -// official one. -func TestWantTracks_StandardEditionFromMusicBrainz(t *testing.T) { - const group = "g0000000-0000-4000-8000-000000000010" - for _, down := range []bool{false, true} { - h, pool := testHandlers(t) - admin := seedUser(t, h.pool, "admin", "pw", true) - h.catalogue = catalogue.New(pool, &musicbrainz.Client{BaseURL: fakeEditions(t, group, down).URL, - Pace: &musicbrainz.Pacer{}, Retries: -1}, h.logger) - w := seedWant(t, h, group, "a0000000-0000-4000-8000-000000000001", "Camel", "Moonmadness", "1976") - - code, out := wantTracks(t, h, admin, uuidToString(w.ID)) - if down { - if code != http.StatusServiceUnavailable { - t.Errorf("MusicBrainz down: status %d, want 503", code) - } - continue - } - if code != http.StatusOK || out.Source != "musicbrainz" || len(out.Tracks) != 2 { - t.Fatalf("status %d, %+v: want the two-track original", code, out) - } - if out.Edition != "1976 · 12\" Vinyl · GB" { - t.Errorf("edition = %q", out.Edition) - } - if tr := out.Tracks[1]; tr.Disc != 1 || tr.Number != 2 || tr.Title != "Song Within a Song" || tr.LengthMs != 433000 { - t.Errorf("track 2 = %+v", tr) - } - } -} - -// A held album shows the library's own tracks, a lost file marked. -func TestWantTracks_HeldAlbumShowsTheLibrarysTracks(t *testing.T) { - h, _ := testHandlers(t) - admin := seedUser(t, h.pool, "admin", "pw", true) - ctx := context.Background() - q := dbq.New(h.pool) - mbid := "a0000000-0000-4000-8000-000000000001" - artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Camel", SortName: "Camel", Mbid: &mbid}) - if err != nil { - t.Fatal(err) - } - album, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Moonmadness", SortTitle: "Moonmadness", ArtistID: artist.ID}) - if err != nil { - t.Fatal(err) - } - for i, title := range []string{"Aristillus", "Song Within a Song"} { - num := int32(i + 1) - if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ - Title: title, AlbumID: album.ID, ArtistID: artist.ID, TrackNumber: &num, DurationMs: 120000, - FilePath: fmt.Sprintf("/music/camel/%02d.flac", i+1), FileSize: 1, FileFormat: "flac", - }); err != nil { - t.Fatal(err) - } - } - if _, err := h.pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE title = 'Aristillus'`); err != nil { - t.Fatal(err) - } - w := seedWant(t, h, "g0000000-0000-4000-8000-000000000011", mbid, "Camel", "Moonmadness", "1976") - if err := q.FulfillWant(ctx, dbq.FulfillWantParams{ID: w.ID, AlbumID: album.ID}); err != nil { - t.Fatal(err) - } - - code, out := wantTracks(t, h, admin, uuidToString(w.ID)) - if code != http.StatusOK || out.Source != "library" || len(out.Tracks) != 2 { - t.Fatalf("status %d, %+v", code, out) - } - if !out.Tracks[0].Missing || out.Tracks[1].Missing || out.Tracks[1].Number != 2 { - t.Errorf("tracks = %+v: the first is missing, the second on disk", out.Tracks) - } -} - -// The Unmatched section: the albums matching could not place, a -// local band's album left off and put back, and a link that names no -// MusicBrainz album refused before MusicBrainz is asked. -func TestUnmatched_ListLeaveOffPutBack(t *testing.T) { - h, _ := testHandlers(t) - admin := seedUser(t, h.pool, "admin", "pw", true) - ctx := context.Background() - q := dbq.New(h.pool) - artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Annadale", SortName: "Annadale"}) - if err != nil { - t.Fatal(err) - } - album, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Dial Tone", SortTitle: "Dial Tone", ArtistID: artist.ID}) - if err != nil { - t.Fatal(err) - } - if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ - Title: "Intro", AlbumID: album.ID, ArtistID: artist.ID, DurationMs: 120000, - FilePath: "/music/annadale/01.flac", FileSize: 1, FileFormat: "flac", - }); err != nil { - t.Fatal(err) - } - if err := q.RecordAlbumMatch(ctx, dbq.RecordAlbumMatchParams{ - AlbumID: album.ID, Outcome: "unmatched", Detail: "MusicBrainz has no album by that name", Matcher: 1}); err != nil { - t.Fatal(err) - } - id := uuidToString(album.ID) - - list := func() []unmatchedAlbumView { - t.Helper() - w := doWantedReq(t, h, "/api/admin/wanted/unmatched", admin) - if w.Code != http.StatusOK { - t.Fatalf("status = %d; body = %s", w.Code, w.Body.String()) - } - var out struct { - Items []unmatchedAlbumView `json:"items"` - } - if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { - t.Fatal(err) - } - return out.Items - } - if got := list(); len(got) != 1 || got[0].AlbumID != id || got[0].Artist != "Annadale" || got[0].Tracks != 1 || - got[0].LeftOff || got[0].Detail == "" || got[0].DecidedAt == "" { - t.Fatalf("unmatched = %+v", got) - } - - for _, c := range []struct { - path, body string - code int - }{ - {"/api/admin/wanted/unmatched/" + id + "/match", `{"ref":"Dial Tone"}`, http.StatusBadRequest}, - {"/api/admin/wanted/unmatched/" + id + "/match", `nope`, http.StatusBadRequest}, - {"/api/admin/wanted/unmatched/not-a-uuid/leave-off", "", http.StatusBadRequest}, - {"/api/admin/wanted/unmatched/" + id + "/put-back", "", http.StatusNotFound}, - {"/api/admin/wanted/unmatched/" + id + "/leave-off", "", http.StatusNoContent}, - {"/api/admin/wanted/unmatched/" + id + "/leave-off", "", http.StatusNotFound}, - } { - if w := doWanted(t, h, http.MethodPost, c.path, c.body, admin); w.Code != c.code { - t.Errorf("POST %s %s = %d, want %d; body = %s", c.path, c.body, w.Code, c.code, w.Body.String()) - } - } - if got := list(); len(got) != 1 || !got[0].LeftOff { - t.Fatalf("left off = %+v", got) - } - if w := doWanted(t, h, http.MethodPost, "/api/admin/wanted/unmatched/"+id+"/put-back", "", admin); w.Code != http.StatusNoContent { - t.Fatalf("put back = %d; body = %s", w.Code, w.Body.String()) - } - if got := list(); len(got) != 1 || got[0].LeftOff { - t.Errorf("put back = %+v", got) - } - - user := seedUser(t, h.pool, "listener", "pw", false) - if w := doWantedReq(t, h, "/api/admin/wanted/unmatched", user); w.Code != http.StatusForbidden { - t.Errorf("a listener reads the unmatched section: %d", w.Code) - } -} diff --git a/internal/api/api.go b/internal/api/api.go index bb222fe6..91c585fe 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -13,34 +13,29 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/config" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" - "git.fabledsword.com/bvandeusen/minstrel/internal/importer" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" - "git.fabledsword.com/bvandeusen/minstrel/internal/lifecycle" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" - "git.fabledsword.com/bvandeusen/minstrel/internal/netsettings" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" - "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" - "git.fabledsword.com/bvandeusen/minstrel/internal/quarantine" - "git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition" - "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation" - "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings" - "git.fabledsword.com/bvandeusen/minstrel/internal/requests" - "git.fabledsword.com/bvandeusen/minstrel/internal/tags" - "git.fabledsword.com/bvandeusen/minstrel/internal/tracks" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/config" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/eventbus" + "github.com/Fabled-Sword/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/lookups" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/netsettings" + "github.com/Fabled-Sword/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/playevents" + "github.com/Fabled-Sword/minstrel/internal/playlists" + "github.com/Fabled-Sword/minstrel/internal/quarantine" + "github.com/Fabled-Sword/minstrel/internal/recommendation" + "github.com/Fabled-Sword/minstrel/internal/recsettings" + "github.com/Fabled-Sword/minstrel/internal/tags" + "github.com/Fabled-Sword/minstrel/internal/tracks" ) // Mount attaches /api/* handlers to r. Public endpoints (login) are outside // RequireUser; everything else is gated by the middleware. The events writer // is shared with the Subsonic mount so /rest/scrobble feeds the same store. -func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, requestSvc *requests.Service, quarantineSvc *quarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, reacqSettings *reacquisition.SettingsService, fpSettings *library.FingerprintSettingsService, loudSettings *library.LoudnessSettingsService, acoustIDLookup *library.AcoustIDLookupWorker) { +func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, quarantineSvc *quarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, fpSettings *library.FingerprintSettingsService, loudSettings *library.LoudnessSettingsService, acoustIDLookup *library.AcoustIDLookupWorker, lookupSettings *lookups.Service, backups *backup.Service, restart func()) { rng := rand.New(rand.NewSource(rand.Int63())) setupToken, err := auth.NewSetupToken() if err != nil { @@ -49,12 +44,10 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev panic("api: mint setup token: " + err.Error()) } logSetupTokenIfNeeded(pool, logger, setupToken) - cat := catalogue.New(pool, nil, logger) h := &handlers{ pool: pool, logger: logger, events: events, recCfg: recCfg, recSettings: recSettings, rng: rng.Float64, - requests: requestSvc, quarantine: quarantineSvc, tracks: tracksSvc, playlists: playlistsSvc, @@ -70,18 +63,12 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev playlistScheduler: playlistScheduler, streamSecret: streamSecret, netSettings: netSettings, - reacqSettings: reacqSettings, fingerprintSettings: fpSettings, loudnessSettings: loudSettings, acoustIDLookup: acoustIDLookup, - acquisition: acquire.NewStore(pool), - catalogue: cat, - wanted: wanted.New(pool, cat, logger), - searcher: wanted.NewSearcher(pool, cat, logger), - importer: importer.New(pool, scanner, cat, nil, scannerRoots(scanner), logger), - lifecycle: lifecycle.New(pool, logger), - catalogueSearches: newSearchCache(), - catalogueArt: catalogue.NewArt(dataDir, artSources(coverSettings)), + lookupSettings: lookupSettings, + backups: backups, + restart: restart, leveled: newLeveledRenderer(dataDir, loudSettings, logger), librarySize: recommendation.NewLibrarySize(nil), loginGuard: auth.NewLoginGuard(), @@ -97,6 +84,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev api.Post("/auth/login", h.handleLogin) api.Post("/auth/register", h.handleRegister) api.Get("/auth/setup-status", h.handleSetupStatus) + api.Post("/auth/restore", h.handleRestore) api.Post("/auth/forgot-password", h.handleForgotPassword) api.Post("/auth/reset-password", h.handleResetPassword) @@ -148,6 +136,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev authed.Get("/artists/{id}/tracks", h.handleGetArtistTracks) authed.Get("/artists/{id}/similar", h.handleGetSimilarArtists) authed.Get("/artists/{id}/top-tracks", h.handleGetArtistTopTracks) + authed.Get("/artists/{id}/image", h.handleGetArtistImage) authed.Get("/albums/{id}", h.handleGetAlbum) authed.Get("/albums/{id}/cover", h.handleGetCover) authed.Get("/library/shuffle", h.handleLibraryShuffle) @@ -166,12 +155,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev // it can accept either a session or a signed token. authed.Get("/search", h.handleSearch) authed.Get("/radio", h.handleRadio) - authed.Get("/discover/suggestions", h.handleListSuggestions) - // Snooze = "not right now", time-boxed and self-expiring. - // Not a dislike — see the migration for why. - authed.Post("/discover/suggestions/{mbid}/snooze", h.handleSnoozeSuggestion) - authed.Delete("/discover/suggestions/{mbid}/snooze", h.handleUnsnoozeSuggestion) - authed.Get("/discover/snoozes", h.handleListSuggestionSnoozes) authed.Get("/home", h.handleGetHome) authed.Get("/home/index", h.handleGetHomeIndex) authed.Post("/events", h.handleEvents) @@ -190,17 +173,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev authed.Get("/likes/artists", h.handleListLikedArtists) authed.Get("/likes/ids", h.handleGetLikedIDs) - // The release catalogue: request search asks - // MusicBrainz, and art for what isn't held comes through - // Minstrel from the enabled cover-art sources. - authed.Get("/catalogue/search", h.handleCatalogueSearch) - authed.Get("/catalogue/art/{kind}/{mbid}", h.handleCatalogueArt) - - authed.Post("/requests", h.handleCreateRequest) - authed.Get("/requests", h.handleListRequests) - authed.Get("/requests/{id}", h.handleGetRequest) - authed.Delete("/requests/{id}", h.handleCancelRequest) - authed.Post("/quarantine", h.handleFlag) authed.Delete("/quarantine/{track_id}", h.handleUnflag) authed.Get("/quarantine/mine", h.handleListMyQuarantine) @@ -223,79 +195,25 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev authed.Route("/admin", func(admin chi.Router) { admin.Use(auth.RequireAdmin()) - admin.Get("/acquisition/services", h.handleListAcquisitionServices) - admin.Post("/acquisition/services", h.handleCreateAcquisitionService) - admin.Put("/acquisition/services/{code}", h.handleUpdateAcquisitionService) - admin.Delete("/acquisition/services/{code}", h.handleDeleteAcquisitionService) - admin.Post("/acquisition/services/{code}/test", h.handleTestAcquisitionService) - admin.Put("/acquisition/services/{code}/api-key", h.handleSetAcquisitionSecret("api_key")) - admin.Delete("/acquisition/services/{code}/api-key", h.handleSetAcquisitionSecret("api_key")) - admin.Put("/acquisition/services/{code}/password", h.handleSetAcquisitionSecret("password")) - admin.Delete("/acquisition/services/{code}/password", h.handleSetAcquisitionSecret("password")) // The queues that wait on an admin, for the rail and the // Overview. admin.Get("/summary", h.handleGetAdminSummary) admin.Get("/status", h.handleGetAdminStatus) - admin.Get("/requests", h.handleListAdminRequests) - admin.Post("/requests/{id}/approve", h.handleApproveRequest) - admin.Post("/requests/{id}/reject", h.handleRejectRequest) - - // The wanted list: what Minstrel is looking - // for, the artists it follows, and the release-type - // profiles that decide which of their releases count. - admin.Get("/wanted", h.handleListWants) - admin.Get("/wanted/artists", h.handleListWantArtists) - admin.Get("/wanted/unmatched", h.handleListUnmatched) - admin.Post("/wanted/unmatched/{id}/match", h.handleMatchUnmatched) - admin.Post("/wanted/unmatched/{id}/leave-off", h.handleLeaveUnmatchedOff) - admin.Post("/wanted/unmatched/{id}/put-back", h.handlePutUnmatchedBack) - admin.Delete("/wanted/{id}", h.handleRemoveWant) - // Searching and grabbing. - admin.Get("/acquisition/settings", h.handleGetSearchSettings) - admin.Put("/acquisition/settings", h.handlePutSearchSettings) - admin.Get("/wanted/{id}/candidates", h.handleListCandidates) - admin.Get("/wanted/{id}/tracks", h.handleWantTracks) - admin.Post("/wanted/{id}/search", h.handleSearchWant) - admin.Post("/wanted/{id}/grab", h.handleGrabCandidate) - admin.Post("/wanted/{id}/block", h.handleBlockCandidate) - admin.Delete("/release-blocks/{hash}", h.handleUnblockRelease) - admin.Get("/release-blocks", h.handleListReleaseBlocks) - admin.Get("/downloads", h.handleListDownloads) - admin.Post("/downloads/{id}/import", h.handleImportAnyway) - admin.Post("/downloads/{id}/retry", h.handleRetryImport) - admin.Post("/downloads/{id}/refuse", h.handleRefuseDownload) - admin.Post("/downloads/{id}/abandon", h.handleAbandonDownload) - admin.Get("/follows", h.handleListFollows) - admin.Get("/follows/{mbid}", h.handleGetFollow) - admin.Put("/follows/{mbid}", h.handlePutFollow) - admin.Delete("/follows/{mbid}", h.handleDeleteFollow) - admin.Get("/release-profiles", h.handleListReleaseProfiles) - admin.Post("/release-profiles", h.handleCreateReleaseProfile) - admin.Put("/release-profiles/{id}", h.handleUpdateReleaseProfile) - admin.Delete("/release-profiles/{id}", h.handleDeleteReleaseProfile) - admin.Get("/quarantine", h.handleListAdminQuarantine) admin.Post("/quarantine/{track_id}/resolve", h.handleResolveQuarantine) admin.Get("/playback-errors", h.handleListAdminPlaybackErrors) admin.Post("/playback-errors/{id}/resolve", h.handleResolvePlaybackError) admin.Post("/quarantine/{track_id}/delete-file", h.handleDeleteQuarantineFile) + admin.Post("/quarantine/{track_id}/remove-file", h.handleRemoveQuarantineFile) admin.Get("/quarantine/actions", h.handleListQuarantineActions) - admin.Delete("/tracks/{id}", h.handleRemoveTrack) - admin.Post("/albums/{id}/cover/refetch", h.handleAdminAlbumRefetchCover) admin.Post("/covers/refetch-missing", h.handleAdminBulkRefetchCovers) admin.Get("/network-settings", h.handleGetNetworkSettings) admin.Put("/network-settings", h.handleUpdateNetworkSettings) - // Policy for wanting back an album whose files went missing - // Sits beside the missing-files list it governs, because an - // admin meets it on that surface. - admin.Get("/library/reacquisition", h.handleGetReacquisitionSettings) - admin.Put("/library/reacquisition", h.handleUpdateReacquisitionSettings) - // Where the library lives. A changed folder moves its // tracks rather than re-adding them. admin.Get("/library/folders", h.handleGetLibraryFolders) @@ -303,13 +221,14 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Get("/scan/status", h.handleGetScanStatus) admin.Post("/scan/run", h.handleTriggerScan) - // Sits under /library rather than /tracks because what it - // reports is a property of the library's relationship to disk, - // and because the destructive /tracks/{id} route above must - // not be mistaken for it. + // Needs a file: tracks waiting for a good copy, what to give + // whatever finds music, and forgetting the ones not worth it. admin.Get("/library/missing", h.handleListMissingTracks) + admin.Get("/library/missing.csv", h.handleExportMissingTracks) + admin.Post("/library/missing/forget", h.handleForgetMissingTracks) admin.Get("/library/suspect-sources", h.handleListSuspectSources) admin.Put("/library/suspect-sources/{id}", h.handleSetSuspectSourceVerdict) + admin.Post("/library/suspect-sources/{id}/remove", h.handleRemoveSuspectSourceFile) admin.Get("/library/coverage", h.handleGetLibraryCoverage) admin.Get("/library/fingerprints", h.handleGetFingerprintCoverage) @@ -321,6 +240,8 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Get("/library/acoustid", h.handleGetAcoustID) admin.Put("/library/acoustid-settings", h.handleUpdateAcoustIDSettings) admin.Post("/library/acoustid/run", h.handleRunAcoustIDLookup) + admin.Get("/lookup-settings", h.handleGetLookupSettings) + admin.Put("/lookup-settings", h.handleUpdateLookupSettings) admin.Get("/library/acoustid/unsettled", h.handleListUnsettledAcoustID) // Duplicates report: proposals from the duplicate sweep, a // trigger to sweep now, dismissal, and the merge, which deletes @@ -331,7 +252,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Post("/library/duplicates/sweep", h.handleRunDuplicateSweep) admin.Post("/library/duplicates/{id}/dismiss", h.handleDismissDuplicateGroup) admin.Post("/library/duplicates/{id}/merge", h.handleMergeDuplicateGroup) - admin.Post("/library/duplicates/{id}/refetch", h.handleRefetchDuplicateGroup) + admin.Post("/library/duplicates/{id}/remove-files", h.handleRemoveWrongSlotFiles) admin.Get("/invites", h.handleListInvites) admin.Post("/invites", h.handleCreateInvite) @@ -341,7 +262,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Post("/users", h.handleAdminCreateUser) admin.Delete("/users/{id}", h.handleAdminDeleteUser) admin.Post("/users/{id}/reset-password", h.handleAdminResetPassword) - admin.Put("/users/{id}/auto-approve", h.handleAdminAutoApproveToggle) admin.Put("/users/{id}/debug-mode", h.handleAdminDebugModeToggle) // Device diagnostics timeline + device overview. @@ -358,6 +278,11 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Post("/tag-sources/{provider_id}/test", h.handleTestTagSource) admin.Post("/tag-sources/research", h.handleResearchTags) + admin.Get("/backups", h.handleGetBackups) + admin.Put("/backups", h.handleUpdateBackups) + admin.Post("/backups/test", h.handleTestBackups) + admin.Post("/backups/run", h.handleRunBackup) + admin.Get("/smtp-config", h.handleGetSMTPConfig) admin.Put("/smtp-config", h.handleUpdateSMTPConfig) admin.Post("/smtp-config/test", h.handleTestSMTPConfig) @@ -399,7 +324,6 @@ type handlers struct { // Held here rather than counted per request: the count is a // full table scan, and library size only moves when a scan runs. librarySize *recommendation.LibrarySize - requests *requests.Service quarantine *quarantine.Service tracks *tracks.Service playlists *playlists.Service @@ -415,10 +339,6 @@ type handlers struct { // notifier records nothing, which is what most handler tests want. notifier *notifications.Notifier playlistScheduler *playlists.Scheduler - // reacqSettings is the DB-backed policy for auto re-acquisition of - // missing files — grace window, backoff, attempt caps. - // Cached in the service, so the admin card reads it without a query. - reacqSettings *reacquisition.SettingsService // fingerprintSettings is the fingerprinting policy, the same // instance the scanner and the fingerprint workers read, so a save from the // admin card reaches them without a restart. Nil serves the defaults. @@ -429,26 +349,15 @@ type handlers struct { // acoustIDLookup is the AcoustID lookup worker: its settings, its // status and "look up now". Nil serves the defaults (off). acoustIDLookup *library.AcoustIDLookupWorker - // acquisition is the configured indexers and download clients. - acquisition *acquire.Store - // catalogue is the release catalogue read from MusicBrainz, and - // catalogueArt the images for what isn't held. - catalogue *catalogue.Service - catalogueArt *catalogue.Art - // wanted is the wanted list: follows, release-type profiles and wants. - // Its worker runs in main; the API reads and edits. - wanted *wanted.Service - // searcher searches for wants and grabs releases for them. - searcher *wanted.Searcher - // importer refuses a download at a person's word. The import - // loop itself runs in main; this one only acts on a request. - importer *importer.Importer - // lifecycle gives up on a download at a person's word; its loop - // runs in main. - lifecycle *lifecycle.Service - // catalogueSearches reuses recent MusicBrainz answers; nil asks every - // time, which is what handler tests get. - catalogueSearches *searchCache + // lookupSettings are the switches for ListenBrainz similarity and + // MusicBrainz track lists, the same instance their workers read. Nil + // serves the defaults (both on) and refuses saves. + lookupSettings *lookups.Service + // backups is the server's own backup: settings, status, test and run. + backups *backup.Service + // restart stops the server and starts it again in place, so a restored + // backup's settings are read at boot. Nil in tests. + restart func() // leveled renders the leveled streams handed to Sonos/UPnP speakers. Nil // when its cache directory cannot be made: a level request then gets the // plain stream. @@ -488,24 +397,3 @@ func newLeveledRenderer(dataDir string, settings *library.LoudnessSettingsServic } return r } - -// artSources hands the art cache the cover-art settings, or nothing when -// there are none: a nil *SettingsService inside the interface would not -// compare equal to nil and would be called. -func artSources(s *coverart.SettingsService) catalogue.ArtSources { - if s == nil { - return nil - } - return s -} - -// scannerRoots reads the library folders, or none when the API runs without -// a scanner (tests). -func scannerRoots(s *library.Scanner) func() []string { - return func() []string { - if s == nil { - return nil - } - return s.Roots() - } -} diff --git a/internal/api/artistimage_test.go b/internal/api/artistimage_test.go new file mode 100644 index 00000000..c108c3ef --- /dev/null +++ b/internal/api/artistimage_test.go @@ -0,0 +1,107 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// getArt fetches path and returns the image body, or "" with the status +// when the answer is not an image. +func getArt(t *testing.T, h *handlers, path string) (string, int) { + t.Helper() + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if w.Code != http.StatusOK { + return "", w.Code + } + return w.Body.String(), w.Code +} + +// coverURLs returns the cover_url of every artist in the alphabetical +// listing, by name. +func coverURLs(t *testing.T, h *handlers) map[string]string { + t.Helper() + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/artists", nil)) + var got Page[ArtistRef] + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode artists: %v body=%s", err, w.Body.String()) + } + out := map[string]string{} + for _, a := range got.Items { + out[a.Name] = a.CoverURL + } + return out +} + +func detailCoverURL(t *testing.T, h *handlers, id string) string { + t.Helper() + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/artists/"+id, nil)) + var got ArtistDetail + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode artist: %v body=%s", err, w.Body.String()) + } + return got.CoverURL +} + +func exec(t *testing.T, pool *pgxpool.Pool, sql string, args ...any) { + t.Helper() + if _, err := pool.Exec(context.Background(), sql, args...); err != nil { + t.Fatalf("%s: %v", sql, err) + } +} + +// An artist's image is the picture fetched for them, or else their newest +// album cover; artist listings point at it when there is a picture, and the +// artist page whenever the artist has albums. +func TestArtistImage_PictureOrNewestAlbumCover(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + dir := t.TempDir() + write := func(name, body string) string { + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return path + } + orchard := seedArtist(t, pool, "Tin Orchard") + album := seedAlbum(t, pool, orchard.ID, "Paper Boats", 2012) + exec(t, pool, `UPDATE albums SET cover_art_path = $2 WHERE id = $1`, album.ID, write("boats.jpg", "boats")) + quiet := seedArtist(t, pool, "Quiet Field") + orchardImage := "/api/artists/" + uuidToString(orchard.ID) + "/image" + albumCover := "/api/albums/" + uuidToString(album.ID) + "/cover" + + if got, code := getArt(t, h, orchardImage); got != "boats" { + t.Errorf("no picture: got %q (status %d), want the album cover", got, code) + } + if got := coverURLs(t, h); got["Tin Orchard"] != albumCover || got["Quiet Field"] != "" { + t.Errorf("no picture: listing cover_url = %v, want the album cover for Tin Orchard and none for Quiet Field", got) + } + + exec(t, pool, `UPDATE artists SET artist_thumb_path = $2 WHERE id = $1`, orchard.ID, write("thumb.jpg", "thumb")) + if got, code := getArt(t, h, orchardImage); got != "thumb" { + t.Errorf("with a picture: got %q (status %d), want the picture", got, code) + } + if got := coverURLs(t, h); got["Tin Orchard"] != orchardImage { + t.Errorf("with a picture: listing cover_url = %q, want %q", got["Tin Orchard"], orchardImage) + } + + if got := detailCoverURL(t, h, uuidToString(orchard.ID)); got != orchardImage { + t.Errorf("artist page cover_url = %q, want %q", got, orchardImage) + } + if got := detailCoverURL(t, h, uuidToString(quiet.ID)); got != "" { + t.Errorf("artist page with no albums: cover_url = %q, want none", got) + } + if _, code := getArt(t, h, "/api/artists/"+uuidToString(quiet.ID)+"/image"); code != http.StatusNotFound { + t.Errorf("no picture and no albums: status %d, want 404", code) + } +} diff --git a/internal/api/auth.go b/internal/api/auth.go index 89bcc13f..01692302 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -9,14 +9,15 @@ import ( "github.com/jackc/pgx/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) -// sessionCookieMaxAge is the cookie lifetime. Sessions don't auto-expire -// server-side yet (future work); the cookie still caps browser-side lifetime -// so an abandoned laptop doesn't stay logged in forever. +// sessionCookieMaxAge is the cookie lifetime, matching the server's idle +// limit: a session unused for 30 days, or a year old, no longer signs anyone +// in (GetSessionByTokenHash), and the browser drops the cookie on the same +// idle clock. const sessionCookieMaxAge = 30 * 24 * time.Hour // Limits on the unauthenticated auth routes other than login (which uses diff --git a/internal/api/auth_forgot.go b/internal/api/auth_forgot.go index 57baf6b7..75d84115 100644 --- a/internal/api/auth_forgot.go +++ b/internal/api/auth_forgot.go @@ -13,10 +13,10 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/mailer" ) const ( @@ -52,14 +52,14 @@ func (h *handlers) handleForgotPassword(w http.ResponseWriter, r *http.Request) // inbox). Applied whether or not the email matches, so a 429 says // nothing about which addresses are registered. addr := auth.ClientIP(r, h.netSettings.Hops()) - blockedAddr, waitAddr := h.forgotAddressLimit.Blocked(addr) - blockedEmail, waitEmail := h.forgotEmailLimit.Blocked(email) - if blockedAddr || blockedEmail { - writeRateLimited(w, max(waitAddr, waitEmail)) + if ok, wait := h.forgotAddressLimit.Allow(addr); !ok { + writeRateLimited(w, wait) + return + } + if ok, wait := h.forgotEmailLimit.Allow(email); !ok { + writeRateLimited(w, wait) return } - h.forgotAddressLimit.Record(addr) - h.forgotEmailLimit.Record(email) q := dbq.New(h.pool) var matched bool @@ -117,6 +117,7 @@ func (h *handlers) sendResetEmail(ctx context.Context, user dbq.User) error { Username: user.Username, ResetURL: resetURL, ExpiryHours: int(resetTokenTTL.Hours()), + Server: h.netSettings.PublicURL(), }) if err != nil { return err diff --git a/internal/api/auth_forgot_test.go b/internal/api/auth_forgot_test.go index d5ce4d5a..638375b8 100644 --- a/internal/api/auth_forgot_test.go +++ b/internal/api/auth_forgot_test.go @@ -6,14 +6,13 @@ import ( "errors" "net/http" "net/http/httptest" - "os" "strings" "testing" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" - "git.fabledsword.com/bvandeusen/minstrel/internal/netsettings" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/netsettings" ) // withPublicURL gives h a network-settings service holding url, restoring an @@ -34,9 +33,6 @@ func withPublicURL(t *testing.T, h *handlers, pool *pgxpool.Pool, url string) { // With no public URL set, a reset email is not sent at all, and the response // is still the same opaque 200. func TestForgotPassword_NoPublicURL_SendsNothing(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) fake := &mailer.FakeSender{} h.mailer = fake @@ -61,9 +57,6 @@ func TestForgotPassword_NoPublicURL_SendsNothing(t *testing.T) { } func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) fake := &mailer.FakeSender{} h.mailer = fake @@ -111,9 +104,6 @@ func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) { } func TestForgotPassword_UnknownEmail_Returns200_NoSend(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) fake := &mailer.FakeSender{} h.mailer = fake @@ -133,9 +123,6 @@ func TestForgotPassword_UnknownEmail_Returns200_NoSend(t *testing.T) { } func TestForgotPassword_MailerFailure_StillReturns200(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) fake := &mailer.FakeSender{FailNext: errors.New("simulated SMTP failure")} h.mailer = fake diff --git a/internal/api/auth_register.go b/internal/api/auth_register.go index 02d142f5..7430db4e 100644 --- a/internal/api/auth_register.go +++ b/internal/api/auth_register.go @@ -9,16 +9,14 @@ import ( "regexp" "time" - "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" - "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // usernameRe enforces a conservative username shape: 3-32 chars, @@ -26,8 +24,6 @@ import ( // the frontend for live validation. var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{3,32}$`) -const minPasswordLength = 8 - type registerReq struct { Username string `json:"username"` Password string `json:"password"` @@ -40,35 +36,36 @@ type registerReq struct { // handleRegister implements POST /api/auth/register. // +// An invite from an admin is the only way to an account. The one exception is +// the first account on an empty server, which becomes the admin and needs the +// setup token from the server log instead. +// // Flow: // 1. Validate username/password format + minimum lengths. -// 2. Look up registration_settings.mode and current user count. -// 3. If users table is empty: insert via CreateUserFirstAdminRace -// (sets is_admin from a SELECT NOT EXISTS subquery). Skip invite -// check. -// 4. Else if mode == 'invite_only': atomically redeem invite via -// RedeemInvite (returns rows-affected; 0 means no usable -// invite — reject 400). -// 5. Else (mode == 'open'): proceed without invite check. -// 6. Hash password, mint session token, insert session row, set +// 2. If users table is empty: check the setup token, then insert via +// CreateUserFirstAdminRace (sets is_admin from a SELECT NOT EXISTS +// subquery). +// 3. Otherwise check the invite. The user insert and the invite claim +// (RedeemInvite) then run in one transaction, so of several sign-ups +// racing on one invite exactly one makes an account. +// 4. Hash password, mint session token, insert session row, set // cookie, return user + token. -// 7. Audit ActionRegister and (if invite was used) ActionInviteRedeem. +// 5. Audit ActionRegister and ActionInviteRedeem. // // Errors: // - 400 invalid_body / username_invalid / password_too_short -// - 400 invite_required (invite_only mode, no token supplied) +// - 400 invite_required (no token supplied) // - 400 invite_invalid (token doesn't exist, expired, or already redeemed) // - 409 username_taken (PG unique violation on users.username) // - 500 server_error otherwise func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { - // Every attempt counts, not only failures: a successful registration is - // the thing being sprayed when the mode is open. + // Every attempt counts, not only failures, so invite tokens can't be + // guessed at speed. addr := auth.ClientIP(r, h.netSettings.Hops()) - if blocked, wait := h.registerLimit.Blocked(addr); blocked { + if ok, wait := h.registerLimit.Allow(addr); !ok { writeRateLimited(w, wait) return } - h.registerLimit.Record(addr) var req registerReq if err := json.NewDecoder(r.Body).Decode(&req); err != nil { @@ -79,8 +76,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen")) return } - if len(req.Password) < minPasswordLength { - writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars")) + if !checkNewPassword(w, req.Password) { return } @@ -107,42 +103,34 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { return } - // Validate invite (skipped on empty-users state; skipped in 'open' mode). + // Every account after the first needs an invite. usedInviteToken := "" if userCount > 0 { - mode, err := q.GetRegistrationMode(r.Context()) - if err != nil { - h.logger.Error("register: get mode failed", "err", err) - writeErr(w, apierror.Internal(err)) + if req.InviteToken == "" { + writeErr(w, apierror.BadRequest("invite_required", "an invite token is required to register")) return } - if mode == "invite_only" { - if req.InviteToken == "" { - writeErr(w, apierror.BadRequest("invite_required", "an invite token is required to register")) + // Pre-validate existence + non-redeemed + non-expired so we fail + // fast on bad tokens before creating the user. + invite, ierr := q.GetInviteByToken(r.Context(), req.InviteToken) + if ierr != nil { + if errors.Is(ierr, pgx.ErrNoRows) { + writeErr(w, apierror.BadRequest("invite_invalid", "invite token not found")) return } - // Pre-validate existence + non-redeemed + non-expired so we fail - // fast on bad tokens before creating the user. - invite, ierr := q.GetInviteByToken(r.Context(), req.InviteToken) - if ierr != nil { - if errors.Is(ierr, pgx.ErrNoRows) { - writeErr(w, apierror.BadRequest("invite_invalid", "invite token not found")) - return - } - h.logger.Error("register: get invite failed", "err", ierr) - writeErr(w, apierror.Internal(ierr)) - return - } - if invite.RedeemedAt.Valid || invite.ExpiresAt.Time.Before(time.Now()) { - writeErr(w, apierror.BadRequest("invite_invalid", "invite token is expired or already redeemed")) - return - } - usedInviteToken = req.InviteToken + h.logger.Error("register: get invite failed", "err", ierr) + writeErr(w, apierror.Internal(ierr)) + return } + if invite.RedeemedAt.Valid || invite.ExpiresAt.Time.Before(time.Now()) { + writeErr(w, apierror.BadRequest("invite_invalid", "invite token is expired or already redeemed")) + return + } + usedInviteToken = req.InviteToken } // Hash password. - hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) + hash, err := hashPassword(req.Password) if err != nil { h.logger.Error("register: hash password failed", "err", err) writeErr(w, apierror.Internal(err)) @@ -157,42 +145,25 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { return } - // Insert user (race-safe-first-admin variant). - user, err := q.CreateUserFirstAdminRace(r.Context(), dbq.CreateUserFirstAdminRaceParams{ + user, err := h.createRegisteredUser(r.Context(), dbq.CreateUserFirstAdminRaceParams{ Username: req.Username, PasswordHash: string(hash), ApiTokenHash: auth.HashAPIToken(apiToken), DisplayName: req.DisplayName, - }) - if err != nil { - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation { - writeErr(w, apierror.Conflict("username_taken", "username is already taken")) - return - } + }, usedInviteToken) + switch { + case errors.Is(err, errInviteTaken): + writeErr(w, apierror.BadRequest("invite_invalid", "invite token is expired or already redeemed")) + return + case db.IsUniqueViolation(err): + writeErr(w, apierror.Conflict("username_taken", "username is already taken")) + return + case err != nil: h.logger.Error("register: create user failed", "err", err) writeErr(w, apierror.Internal(err)) return } - // Atomic invite redeem (if applicable). Now we have user.ID for - // redeemed_by. - if usedInviteToken != "" { - rows, rerr := q.RedeemInvite(r.Context(), dbq.RedeemInviteParams{ - Token: usedInviteToken, - RedeemedBy: user.ID, - }) - if rerr != nil || rows != 1 { - // Race: another caller redeemed between our pre-check and now. - // User was already inserted — the redeem failed but the user - // row exists. Best to leave the user in place (operator can - // promote them manually) but surface a clear log entry. - h.logger.Error("register: invite redeem failed; user inserted but invite not consumed", - "user_id", uuidToString(user.ID), "rows", rows, "err", rerr) - // Don't fail the response — the user IS registered. - } - } - // Mint session token + cookie (same shape as handleLogin). sessionToken, err := auth.MintSessionToken() if err != nil { @@ -253,6 +224,38 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { }) } +// errInviteTaken means the invite was redeemed or expired between the +// handler's check and its claim: another sign-up on the same invite won. +var errInviteTaken = errors.New("api: invite already redeemed or expired") + +// createRegisteredUser inserts the user and, when inviteToken is set, claims +// the invite for them, in one transaction. RedeemInvite's UPDATE locks the +// invite row, so a second sign-up on the same invite waits for the first to +// commit, then finds it redeemed and rolls its own account back. An invite +// therefore makes one account however many requests carry it. +func (h *handlers) createRegisteredUser(ctx context.Context, params dbq.CreateUserFirstAdminRaceParams, inviteToken string) (dbq.User, error) { + tx, err := h.pool.Begin(ctx) + if err != nil { + return dbq.User{}, err + } + defer func() { _ = tx.Rollback(ctx) }() + tq := dbq.New(tx) + user, err := tq.CreateUserFirstAdminRace(ctx, params) + if err != nil { + return dbq.User{}, err + } + if inviteToken != "" { + rows, err := tq.RedeemInvite(ctx, dbq.RedeemInviteParams{Token: inviteToken, RedeemedBy: user.ID}) + if err != nil { + return dbq.User{}, err + } + if rows != 1 { + return dbq.User{}, errInviteTaken + } + } + return user, tx.Commit(ctx) +} + // handleSetupStatus implements GET /api/auth/setup-status. It tells the // register screen whether to ask for the setup token, i.e. whether no // account exists yet. Public, since it is needed before anyone can sign in; diff --git a/internal/api/auth_register_test.go b/internal/api/auth_register_test.go index 34b51587..c32205a9 100644 --- a/internal/api/auth_register_test.go +++ b/internal/api/auth_register_test.go @@ -6,11 +6,10 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "sync" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/auth" ) // resetUsers wipes the entire users table (including any non-prefixed admin @@ -34,9 +33,6 @@ func resetInvites(t *testing.T, h *handlers) { } func TestRegister_FirstUserBecomesAdmin(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) resetUsers(t, h) @@ -69,144 +65,25 @@ func TestRegister_FirstUserBecomesAdmin(t *testing.T) { } } -func TestRegister_InviteOnlyMode_RequiresToken(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - // Seed an admin user so we're past the empty-users state. - seedUser(t, pool, "existingadmin", "pw", true) - // Mode is default invite_only. - - body := `{"username":"newuser","password":"abcd1234"}` - req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) - rec := httptest.NewRecorder() - h.handleRegister(rec, req) - - if rec.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400 (invite_required)", rec.Code) - } -} - -func TestRegister_InviteOnlyMode_ValidTokenSucceeds(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - resetInvites(t, h) - admin := seedUser(t, pool, "admin1", "pw", true) - // Insert a fresh invite directly. - token := "test-invite-abc123" - if _, err := pool.Exec(context.Background(), - `INSERT INTO user_invites (token, invited_by, expires_at) - VALUES ($1, $2, now() + interval '24 hours')`, - token, admin.ID, - ); err != nil { - t.Fatalf("seed invite: %v", err) - } - - body := `{"username":"invitee1","password":"abcd1234","invite_token":"` + token + `"}` - req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) - rec := httptest.NewRecorder() - h.handleRegister(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - // Invite redeemed? - var redeemedAt *string - if err := pool.QueryRow(context.Background(), - `SELECT redeemed_at::text FROM user_invites WHERE token = $1`, token, - ).Scan(&redeemedAt); err != nil { - t.Fatalf("verify redeem: %v", err) - } - if redeemedAt == nil { - t.Errorf("invite not redeemed after successful registration") - } - // New user is_admin = false? - var isAdmin bool - if err := pool.QueryRow(context.Background(), - `SELECT is_admin FROM users WHERE username = 'invitee1'`).Scan(&isAdmin); err != nil { - t.Fatalf("verify user: %v", err) - } - if isAdmin { - t.Errorf("new invitee marked as admin; only first user should be admin") - } -} - -func TestRegister_InviteOnlyMode_InvalidTokenRejects(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - seedUser(t, pool, "adm", "pw", true) - - body := `{"username":"baduser","password":"abcd1234","invite_token":"nonexistent-token"}` - req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) - rec := httptest.NewRecorder() - h.handleRegister(rec, req) - - if rec.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400 (invite_invalid)", rec.Code) - } -} - -func TestRegister_OpenMode_NoTokenNeeded(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - seedUser(t, pool, "preexisting", "pw", true) - // Switch to open mode; restore invite_only afterwards so other tests are - // not affected (registration_settings is a singleton not truncated by - // ResetDB). - if _, err := pool.Exec(context.Background(), - "UPDATE registration_settings SET mode = 'open' WHERE id = true"); err != nil { - t.Fatalf("set mode: %v", err) - } - t.Cleanup(func() { - if _, err := pool.Exec(context.Background(), - "UPDATE registration_settings SET mode = 'invite_only' WHERE id = true"); err != nil { - t.Logf("cleanup: restore mode failed: %v", err) - } - }) - - body := `{"username":"openreg","password":"abcd1234"}` - req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) - rec := httptest.NewRecorder() - h.handleRegister(rec, req) - - if rec.Code != http.StatusOK { - t.Errorf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } -} - func TestRegister_DuplicateUsername_409(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) resetUsers(t, h) - // Switch to open mode so the second attempt is not rejected by invite - // check before it can reach the INSERT and hit the unique violation. - if _, err := pool.Exec(context.Background(), - "UPDATE registration_settings SET mode = 'open' WHERE id = true"); err != nil { - t.Fatalf("set mode: %v", err) - } - t.Cleanup(func() { - if _, err := pool.Exec(context.Background(), - "UPDATE registration_settings SET mode = 'invite_only' WHERE id = true"); err != nil { - t.Logf("cleanup: restore mode failed: %v", err) - } - }) + resetInvites(t, h) // First register succeeds (empty-users state → first-admin path). body := `{"username":"taken","password":"abcd1234"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) h.handleRegister(httptest.NewRecorder(), req) - // Second register with same username in open mode → 409 (unique violation). - req2 := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) + // A valid invite gets the second attempt past the invite check, to the + // INSERT and its unique violation. + if _, err := pool.Exec(context.Background(), + `INSERT INTO user_invites (token, invited_by, expires_at) + SELECT 'dup-invite', id, now() + interval '24 hours' FROM users WHERE username = 'taken'`); err != nil { + t.Fatalf("seed invite: %v", err) + } + dup := `{"username":"taken","password":"abcd1234","invite_token":"dup-invite"}` + req2 := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(dup))) rec2 := httptest.NewRecorder() h.handleRegister(rec2, req2) @@ -242,9 +119,6 @@ func TestRegister_FirstAdminRace(t *testing.T) { // usernames are different, so users.username uniqueness doesn't // arbitrate. Both will see "no users yet" and both insert as // admin. Test asserts the at-least-one-admin invariant. - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) resetUsers(t, h) @@ -278,9 +152,6 @@ func TestRegister_FirstAdminRace(t *testing.T) { // With the gate on (as Mount sets it), the first account needs the setup // token from the log; a missing or wrong one is refused and creates nothing. func TestRegister_FirstUserNeedsSetupToken(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) resetUsers(t, h) token, err := auth.NewSetupToken() @@ -315,18 +186,10 @@ func TestRegister_FirstUserNeedsSetupToken(t *testing.T) { t.Fatalf("right token: status = %d, want 200", code) } - // Once an account exists the token plays no part: the second user is - // governed by registration mode, not the setup token. - if _, err := h.pool.Exec(context.Background(), - `UPDATE registration_settings SET mode = 'open' WHERE id = true`); err != nil { - t.Fatalf("open mode: %v", err) - } - t.Cleanup(func() { - _, _ = h.pool.Exec(context.Background(), - `UPDATE registration_settings SET mode = 'invite_only' WHERE id = true`) - }) - if code := register(`{"username":"second","password":"abcd1234"}`); code != http.StatusOK { - t.Errorf("second user without token: status = %d, want 200", code) + // Once an account exists the setup token opens nothing: the second + // account needs an invite, and there is no way to register without one. + if code := register(`{"username":"second","password":"abcd1234","setup_token":"` + token.Value() + `"}`); code != http.StatusBadRequest { + t.Errorf("second user with the setup token and no invite: status = %d, want 400", code) } } @@ -346,3 +209,115 @@ func TestSetupToken_MatchesOnlyItself(t *testing.T) { t.Error("a nil token must fail closed") } } + +// Sign-ups racing on one invite make exactly one account: the others are +// told the invite is used, and nothing of theirs is left behind. +func TestRegister_OneInviteMakesOneAccountUnderARace(t *testing.T) { + h, pool := testHandlers(t) + resetInvites(t, h) + admin := seedUser(t, pool, "raceadmin", "pw", true) + token := "test-invite-race" + if _, err := pool.Exec(context.Background(), + `INSERT INTO user_invites (token, invited_by, expires_at) + VALUES ($1, $2, now() + interval '24 hours')`, + token, admin.ID, + ); err != nil { + t.Fatalf("seed invite: %v", err) + } + + const N = 5 + codes := make([]int, N) + var wg sync.WaitGroup + for i := 0; i < N; i++ { + wg.Add(1) + go func(idx int) { + defer wg.Done() + body := `{"username":"inviterace` + string(rune('A'+idx)) + `","password":"abcd1234","invite_token":"` + token + `"}` + req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) + rec := httptest.NewRecorder() + h.handleRegister(rec, req) + codes[idx] = rec.Code + }(i) + } + wg.Wait() + + ok := 0 + for _, c := range codes { + switch c { + case http.StatusOK: + ok++ + case http.StatusBadRequest: + default: + t.Errorf("unexpected status %d", c) + } + } + if ok != 1 { + t.Fatalf("%d sign-ups succeeded on one invite, want exactly 1 (codes %v)", ok, codes) + } + var made int + if err := pool.QueryRow(context.Background(), + `SELECT count(*) FROM users WHERE username LIKE 'inviterace%'`).Scan(&made); err != nil { + t.Fatalf("count: %v", err) + } + if made != 1 { + t.Fatalf("%d accounts exist after the race, want 1", made) + } +} + +// Once an account exists, an invite is the only way in: a sign-up without +// one, or with a token that was never issued, is refused and creates no +// account. A valid invite makes an ordinary (non-admin) account and is +// marked redeemed. +func TestRegister_AfterTheFirstAccountAnInviteIsTheOnlyWayIn(t *testing.T) { + h, pool := testHandlers(t) + resetInvites(t, h) + // Exactly one account, so the first sign-up below is the second account: + // accounts other tests made through sign-up survive dbtest's reset. + if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { + t.Fatalf("reset users: %v", err) + } + admin := seedUser(t, pool, "admin1", "pw", true) + const token = "test-invite-abc123" + if _, err := pool.Exec(context.Background(), + `INSERT INTO user_invites (token, invited_by, expires_at) + VALUES ($1, $2, now() + interval '24 hours')`, token, admin.ID); err != nil { + t.Fatalf("seed invite: %v", err) + } + + for _, tc := range []struct { + username, inviteToken string + status int + }{ + {"noinvite", "", http.StatusBadRequest}, + {"badinvite", "nonexistent-token", http.StatusBadRequest}, + {"invitee", token, http.StatusOK}, + } { + body := `{"username":"` + tc.username + `","password":"abcd1234","invite_token":"` + tc.inviteToken + `"}` + rec := httptest.NewRecorder() + h.handleRegister(rec, httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body)))) + if rec.Code != tc.status { + t.Errorf("%s: status %d, want %d; body=%s", tc.username, rec.Code, tc.status, rec.Body.String()) + } + var accounts, admins int + if err := pool.QueryRow(context.Background(), + `SELECT count(*), count(*) FILTER (WHERE is_admin) FROM users WHERE username = $1`, + tc.username).Scan(&accounts, &admins); err != nil { + t.Fatalf("count accounts: %v", err) + } + wantAccounts := 0 + if tc.status == http.StatusOK { + wantAccounts = 1 + } + if accounts != wantAccounts || admins != 0 { + t.Errorf("%s: %d accounts (%d admin), want %d (0 admin)", tc.username, accounts, admins, wantAccounts) + } + } + var redeemed bool + if err := pool.QueryRow(context.Background(), + `SELECT redeemed_at IS NOT NULL FROM user_invites WHERE token = $1`, token).Scan(&redeemed); err != nil { + t.Fatalf("read invite: %v", err) + } + if !redeemed { + t.Errorf("the invite was not marked redeemed") + } +} diff --git a/internal/api/auth_reset.go b/internal/api/auth_reset.go index 00196349..ddc63856 100644 --- a/internal/api/auth_reset.go +++ b/internal/api/auth_reset.go @@ -6,12 +6,11 @@ import ( "net/http" "github.com/jackc/pgx/v5" - "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) type resetPasswordReq struct { @@ -34,8 +33,7 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.BadRequest("invalid_body", "")) return } - if len(req.NewPassword) < minPasswordLength { - writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars")) + if !checkNewPassword(w, req.NewPassword) { return } if req.Token == "" { @@ -89,7 +87,7 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) { // claim, the token is "burned" but the password isn't reset — // user has to request another. That's acceptable; bcrypt and // UPDATE rarely fail in healthy systems. - hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) + hash, err := hashPassword(req.NewPassword) if err != nil { h.logger.Error("reset password: hash failed", "err", err) writeErr(w, apierror.Internal(err)) @@ -104,12 +102,15 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) { return } - // End every session the account has. Whoever needed a reset isn't signed - // in anywhere they rely on, and whoever may have learned the old password - // must not stay signed in on it. + // End every session the account has, and its Subsonic apps' access. + // Whoever needed a reset isn't signed in anywhere they rely on, and + // whoever may have learned the old password must not stay signed in on it. if _, err := q.DeleteSessionsForUser(r.Context(), reset.UserID); err != nil { h.logger.Error("reset password: revoke sessions failed", "err", err) } + if err := h.signOutSubsonicApps(r.Context(), reset.UserID); err != nil { + h.logger.Error("reset password: sign out subsonic apps failed", "err", err) + } audit.WriteOrLog(r.Context(), h.pool, h.logger, reset.UserID, reset.UserID, audit.ActionPasswordResetByEmail, nil) diff --git a/internal/api/auth_reset_test.go b/internal/api/auth_reset_test.go index 7b0bf31c..ab6a2c8f 100644 --- a/internal/api/auth_reset_test.go +++ b/internal/api/auth_reset_test.go @@ -5,7 +5,6 @@ import ( "context" "net/http" "net/http/httptest" - "os" "testing" "time" @@ -14,9 +13,6 @@ import ( ) func TestResetPassword_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "resetuser", "oldpw1234", false) @@ -61,9 +57,6 @@ func TestResetPassword_Happy(t *testing.T) { } func TestResetPassword_AlreadyUsed_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "alreadyused", "pw", false) @@ -87,9 +80,6 @@ func TestResetPassword_AlreadyUsed_400(t *testing.T) { } func TestResetPassword_Expired_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "expiredreset", "pw", false) @@ -113,9 +103,6 @@ func TestResetPassword_Expired_400(t *testing.T) { } func TestResetPassword_PasswordTooShort_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) body := `{"token":"any-token","new_password":"abc"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/reset-password", @@ -128,9 +115,6 @@ func TestResetPassword_PasswordTooShort_400(t *testing.T) { } func TestResetPassword_BogusToken_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) body := `{"token":"bogus-token","new_password":"abcd1234"}` @@ -143,3 +127,27 @@ func TestResetPassword_BogusToken_400(t *testing.T) { t.Errorf("status = %d, want 400 (invalid_token for bogus)", rec.Code) } } + +// A reset ends Subsonic apps' access too: they sign in with the API key or +// the Subsonic password, which whoever had the account could have made. +func TestResetPassword_SignsOutSubsonicApps(t *testing.T) { + h, pool := testHandlers(t) + user := seedUser(t, pool, "resetsubsonic", "oldpw1234", false) + giveSubsonicPassword(t, h, user) + before, _ := subsonicCredentials(t, h, user) + + token := "test-reset-token-subsonic" + if _, err := pool.Exec(context.Background(), + `INSERT INTO password_resets (token, user_id, expires_at) + VALUES ($1, $2, $3)`, token, user.ID, time.Now().Add(time.Hour), + ); err != nil { + t.Fatalf("seed: %v", err) + } + body := `{"token":"` + token + `","new_password":"newpassword1"}` + rec := httptest.NewRecorder() + h.handleResetPassword(rec, httptest.NewRequest(http.MethodPost, "/api/auth/reset-password", bytes.NewReader([]byte(body)))) + if rec.Code != http.StatusNoContent { + t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String()) + } + assertSubsonicSignedOut(t, h, user, before) +} diff --git a/internal/api/auth_restore.go b/internal/api/auth_restore.go new file mode 100644 index 00000000..6b896fb2 --- /dev/null +++ b/internal/api/auth_restore.go @@ -0,0 +1,94 @@ +package api + +import ( + "errors" + "net/http" + + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" +) + +// SetupTokenHeader carries the setup token on a restore upload, whose body is +// the backup file itself. +const SetupTokenHeader = "X-Setup-Token" + +type restoreResp struct { + // Accounts is how many accounts came back; everyone signs in with the + // password they had. + Accounts int64 `json:"accounts"` + // Restarting says the server restarts now to load the restored settings. + // The scan at its start finds each music file and fills in what the + // backup leaves out. + Restarting bool `json:"restarting"` +} + +// handleRestore implements POST /api/auth/restore: a new server, with no +// accounts yet, loads a backup file sent as the request body. It asks for the +// setup token from the server log, as creating the first account does, since +// the backup's admins become this server's admins. A library the server's +// first scan found is replaced by the backup's. +// +// Then the server restarts. Settings are read once, at boot, so the restored +// ones (the library folders among them) take effect the same way they do +// after `minstrel restore`, and the startup scan finds each file at its path. +// +// 200 restored · 400 not_a_backup · 403 setup_token_invalid · +// 409 not_empty (accounts already) · 409 newer_backup +func (h *handlers) handleRestore(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + q := dbq.New(h.pool) + n, err := q.CountUsers(ctx) + if err != nil { + writeErrWithLog(w, h.logger, "restore: count users", apierror.Internal(err)) + return + } + if n > 0 { + writeErr(w, apierror.Conflict("not_empty", "this server already has accounts; a backup restores into a new one")) + return + } + if h.requireSetupToken && !h.setupToken.Matches(r.Header.Get(SetupTokenHeader)) { + h.logger.Warn("restore: needs the setup token", "setup_token", h.setupToken.Value()) + writeErr(w, apierror.Forbidden("setup_token_invalid", "the setup token from the server log is required to restore a backup")) + return + } + + manifest, contents, err := backup.Read(r.Body) + if err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + writeErr(w, &apierror.Error{Status: http.StatusRequestEntityTooLarge, Code: "too_large", Message: "the file is larger than a backup can be"}) + return + } + writeErr(w, apierror.BadRequest("not_a_backup", "that file isn't a Minstrel backup")) + return + } + switch err := backup.Restore(ctx, h.pool, contents); { + case errors.Is(err, backup.ErrNotEmpty): + writeErr(w, apierror.Conflict("not_empty", "this server already has accounts; a backup restores into a new one")) + return + case errors.Is(err, backup.ErrNewerSchema): + writeErr(w, apierror.Conflict("newer_backup", "the backup was made by a newer Minstrel; update this server first")) + return + case errors.Is(err, backup.ErrNotABackup): + writeErr(w, apierror.BadRequest("not_a_backup", "that file isn't a Minstrel backup")) + return + case err != nil: + writeErrWithLog(w, h.logger, "restore: load the backup", apierror.Internal(err)) + return + } + + out := restoreResp{} + if out.Accounts, err = q.CountUsers(ctx); err != nil { + h.logger.Warn("restore: count restored accounts", "err", err) + } + h.logger.Info("restored a backup", "made_at", manifest.CreatedAt, "build", manifest.Build, + "schema", manifest.Schema, "accounts", out.Accounts) + out.Restarting = h.restart != nil + writeJSON(w, http.StatusOK, out) + if h.restart != nil { + // The server drains this request before it stops, so the answer + // reaches the browser first. + h.restart() + } +} diff --git a/internal/api/auth_restore_test.go b/internal/api/auth_restore_test.go new file mode 100644 index 00000000..89ce9cd3 --- /dev/null +++ b/internal/api/auth_restore_test.go @@ -0,0 +1,98 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/dbtest" +) + +// A new server takes a backup only with the setup token from its log, only +// while it has no accounts, and only a file that is a backup; then the +// backup's accounts sign in again. +func TestRestore_ANewServerTakesABackupWithTheSetupToken(t *testing.T) { + h, pool := testHandlers(t) + ctx := context.Background() + truncateLibrary(t, pool) + resetUsers(t, h) + seedUser(t, pool, "restored", "abcd1234", true) + c, err := backup.Snapshot(ctx, pool) + if err != nil { + t.Fatal(err) + } + var file bytes.Buffer + if _, err := backup.Write(&file, c, time.Now(), "test"); err != nil { + t.Fatal(err) + } + resetUsers(t, h) + + token, err := auth.NewSetupToken() + if err != nil { + t.Fatal(err) + } + h.setupToken = token + h.requireSetupToken = true + restarts := 0 + h.restart = func() { restarts++ } + restore := func(setupToken string, body []byte) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/api/auth/restore", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/x-tar") + if setupToken != "" { + req.Header.Set(SetupTokenHeader, setupToken) + } + rec := httptest.NewRecorder() + h.handleRestore(rec, req) + return rec + } + + if w := restore("", file.Bytes()); w.Code != http.StatusForbidden { + t.Errorf("no setup token: status = %d, want 403", w.Code) + } + if w := restore("wrong", file.Bytes()); w.Code != http.StatusForbidden { + t.Errorf("a wrong setup token: status = %d, want 403", w.Code) + } + if w := restore(token.Value(), []byte("not a tar file")); w.Code != http.StatusBadRequest || + !strings.Contains(w.Body.String(), "not_a_backup") { + t.Errorf("not a backup: status = %d body = %s, want 400 not_a_backup", w.Code, w.Body.String()) + } + var n int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM users").Scan(&n); err != nil || n != 0 { + t.Fatalf("a refused restore left %d accounts (%v)", n, err) + } + if restarts != 0 { + t.Errorf("a refused restore restarted the server %d times", restarts) + } + + w := restore(token.Value(), file.Bytes()) + if w.Code != http.StatusOK { + t.Fatalf("restore: status = %d body = %s", w.Code, w.Body.String()) + } + var out restoreResp + if err := json.NewDecoder(w.Body).Decode(&out); err != nil || out.Accounts != 1 || !out.Restarting { + t.Errorf("restore answered %+v (%v), want one account and a restart", out, err) + } + if restarts != 1 { + t.Errorf("the restore restarted the server %d times, want once so the restored settings load", restarts) + } + var admin bool + if err := pool.QueryRow(ctx, "SELECT is_admin FROM users WHERE username = $1", + dbtest.TestUserPrefix+"restored").Scan(&admin); err != nil || !admin { + t.Errorf("the restored admin: is_admin = %v, %v", admin, err) + } + + if w := restore(token.Value(), file.Bytes()); w.Code != http.StatusConflict || + !strings.Contains(w.Body.String(), "not_empty") { + t.Errorf("a second restore: status = %d body = %s, want 409 not_empty", w.Code, w.Body.String()) + } + if restarts != 1 { + t.Errorf("a refused second restore restarted the server (%d restarts)", restarts) + } +} diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index a09a1a0a..f2288e69 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -8,7 +8,6 @@ import ( "log/slog" "net/http" "net/http/httptest" - "os" "strings" "testing" @@ -17,22 +16,18 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/config" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" - "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" - "git.fabledsword.com/bvandeusen/minstrel/internal/quarantine" - "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings" - "git.fabledsword.com/bvandeusen/minstrel/internal/requests" - "git.fabledsword.com/bvandeusen/minstrel/internal/tracks" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/config" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/playevents" + "github.com/Fabled-Sword/minstrel/internal/playlists" + "github.com/Fabled-Sword/minstrel/internal/quarantine" + "github.com/Fabled-Sword/minstrel/internal/recsettings" + "github.com/Fabled-Sword/minstrel/internal/tracks" ) // testHandlers spins up a handlers instance against MINSTREL_TEST_DATABASE_URL. @@ -40,23 +35,8 @@ import ( // used elsewhere (scanner_test.go, etc.). func testHandlers(t *testing.T) (*handlers, *pgxpool.Pool) { t.Helper() - if testing.Short() { - t.Skip("skipping api integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) w := playevents.NewWriter(pool, logger, 30*time.Minute, 0.5, 30000) recCfg := config.RecommendationConfig{ RecentlyPlayedHours: 1, RadioSize: 50, RadioSizeMax: 200, @@ -65,13 +45,11 @@ func testHandlers(t *testing.T) (*handlers, *pgxpool.Pool) { if err != nil { t.Fatalf("recsettings: %v", err) } - requestSvc := requests.NewService(pool) - cat := catalogue.New(pool, nil, logger) quarantineSvc := quarantine.NewService(pool, "") dataDir := t.TempDir() tracksSvc := tracks.NewService(pool, logger, dataDir) playlistsSvc := playlists.NewService(pool, logger, dataDir) - h := &handlers{pool: pool, logger: logger, events: w, recCfg: recCfg, recSettings: recSettings, rng: func() float64 { return 0.5 }, requests: requestSvc, catalogue: cat, wanted: wanted.New(pool, cat, logger), quarantine: quarantineSvc, tracks: tracksSvc, playlists: playlistsSvc, dataDir: dataDir, scanner: nil, scanCfg: library.RunScanConfig{}, mailer: &mailer.FakeSender{}, notifier: notifications.New(pool, nil, nil)} + h := &handlers{pool: pool, logger: logger, events: w, recCfg: recCfg, recSettings: recSettings, rng: func() float64 { return 0.5 }, quarantine: quarantineSvc, tracks: tracksSvc, playlists: playlistsSvc, dataDir: dataDir, scanner: nil, scanCfg: library.RunScanConfig{}, mailer: &mailer.FakeSender{}, notifier: notifications.New(pool, nil, nil)} return h, pool } @@ -150,34 +128,6 @@ func TestHandleLogin_SuccessSetsCookieAndReturnsToken(t *testing.T) { } } -func TestHandleLogin_WrongPasswordReturns401(t *testing.T) { - h, pool := testHandlers(t) - seedUser(t, pool, "alice", "hunter2", false) - - body := strings.NewReader(`{"username":"test-alice","password":"wrong"}`) - req := httptest.NewRequest(http.MethodPost, "/api/auth/login", body) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - h.handleLogin(w, req) - - if w.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", w.Code) - } -} - -func TestHandleLogin_UnknownUserReturns401(t *testing.T) { - h, _ := testHandlers(t) - body := strings.NewReader(`{"username":"ghost","password":"whatever"}`) - req := httptest.NewRequest(http.MethodPost, "/api/auth/login", body) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - h.handleLogin(w, req) - - if w.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", w.Code) - } -} - // A guesser who reaches the account limit is refused with 429 before any // password check, so even the right password is turned away until the window // passes, and the response says when to come back. @@ -223,6 +173,12 @@ func TestHandleLogin_MalformedBodyReturns400(t *testing.T) { func userCtxKeyForTest() any { return auth.UserCtxKeyForTest() } +// withUser injects a user into the request context the same way RequireUser +// does. +func withUser(req *http.Request, user dbq.User) *http.Request { + return req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), user)) +} + func TestHandleLogout_DeletesSessionAndClearsCookie(t *testing.T) { h, pool := testHandlers(t) user := seedUser(t, pool, "alice", "hunter2", false) @@ -300,3 +256,28 @@ func TestHandleLogout_BearerHeaderWithTrailingWhitespaceDeletesSession(t *testin t.Error("session row still present after bearer logout with trailing whitespace") } } + +// A wrong password and an unknown username get the same 401 and the same +// body, so a failed sign-in never tells anyone whether an account exists. +func TestHandleLogin_AWrongPasswordAndAnUnknownUserLookAlike(t *testing.T) { + h, pool := testHandlers(t) + seedUser(t, pool, "alice", "hunter2", false) + + var bodies []string + for _, creds := range []string{ + `{"username":"test-alice","password":"wrong"}`, + `{"username":"ghost","password":"whatever"}`, + } { + req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(creds)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + h.handleLogin(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("%s: status %d, want 401", creds, w.Code) + } + bodies = append(bodies, w.Body.String()) + } + if bodies[0] != bodies[1] { + t.Errorf("the refusals differ: %q vs %q", bodies[0], bodies[1]) + } +} diff --git a/internal/api/cast_token.go b/internal/api/cast_token.go index 2705948c..7aad9b8e 100644 --- a/internal/api/cast_token.go +++ b/internal/api/cast_token.go @@ -6,9 +6,9 @@ import ( "strings" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) const ( diff --git a/internal/api/catalogue.go b/internal/api/catalogue.go deleted file mode 100644 index 9b883600..00000000 --- a/internal/api/catalogue.go +++ /dev/null @@ -1,284 +0,0 @@ -package api - -import ( - "context" - "errors" - "net/http" - "net/url" - "slices" - "strings" - "sync" - "time" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" -) - -// catalogueSearchLimit is how many results one search shows. -const catalogueSearchLimit = 25 - -// catalogueSearchResult is one row of GET /api/catalogue/search, read by the -// Discover page and request rows. artist_mbid and album_mbid are the parents a -// request needs: empty on an artist, the artist on an album, both on a track. -// An album is a MusicBrainz release group. -type catalogueSearchResult struct { - MBID string `json:"mbid"` - Name string `json:"name"` - SecondaryText string `json:"secondary_text"` - ImageURL string `json:"image_url"` - ArtistMBID string `json:"artist_mbid"` - AlbumMBID string `json:"album_mbid"` - InLibrary bool `json:"in_library"` - Requested bool `json:"requested"` -} - -// handleCatalogueSearch implements GET -// /api/catalogue/search?q=&kind=artist|album|track asking MusicBrainz directly. -// An unreachable MusicBrainz is a 503 the page shows as such, not an empty -// result. -func (h *handlers) handleCatalogueSearch(w http.ResponseWriter, r *http.Request) { - kind := strings.TrimSpace(r.URL.Query().Get("kind")) - switch kind { - case "artist", "album", "track": - default: - writeErr(w, apierror.BadRequest("bad_kind", "kind must be artist, album, or track")) - return - } - q := strings.TrimSpace(r.URL.Query().Get("q")) - if q == "" { - writeErr(w, apierror.BadRequest("missing_query", "q is required")) - return - } - - out, err := h.catalogueSearches.get(r.Context(), kind, q, h.searchCatalogue) - if err != nil { - switch { - case errors.Is(err, musicbrainz.ErrUnreachable), errors.Is(err, musicbrainz.ErrBadResponse): - writeErr(w, &apierror.Error{Status: 503, Code: "musicbrainz_unreachable", Message: "MusicBrainz can't be reached", Cause: err}) - case r.Context().Err() != nil: - return - default: - h.logger.Error("api: catalogue search", "kind", kind, "err", err) - writeErr(w, apierror.InternalMsg("search failed", err)) - } - return - } - - dbQ := dbq.New(h.pool) - for i := range out { - inLib, err := h.catalogueInLibrary(r.Context(), kind, out[i].MBID) - if err != nil { - writeErr(w, apierror.InternalMsg("library check failed", err)) - return - } - requested, err := dbQ.HasNonTerminalRequestForMBID(r.Context(), out[i].MBID) - if err != nil { - writeErr(w, apierror.InternalMsg("request check failed", err)) - return - } - out[i].InLibrary, out[i].Requested = inLib, requested - } - writeJSON(w, http.StatusOK, out) -} - -func (h *handlers) searchCatalogue(ctx context.Context, kind, q string) ([]catalogueSearchResult, error) { - mb := h.catalogue.MusicBrainz() - out := []catalogueSearchResult{} - switch kind { - case "artist": - artists, err := mb.SearchArtists(ctx, q, catalogueSearchLimit) - if err != nil { - return nil, err - } - for _, a := range artists { - out = append(out, catalogueSearchResult{ - MBID: a.MBID, Name: a.Name, SecondaryText: artistLine(a), - ImageURL: artistArtURL(a.MBID, a.Name), - }) - } - case "album": - groups, err := mb.SearchReleaseGroups(ctx, q, catalogueSearchLimit) - if err != nil { - return nil, err - } - for _, g := range groups { - out = append(out, catalogueSearchResult{ - MBID: g.MBID, Name: g.Title, SecondaryText: joinNonEmpty(g.ArtistCredit, g.Year(), groupType(g)), - ImageURL: groupArtURL(g), ArtistMBID: first(g.ArtistMBIDs), - }) - } - case "track": - recs, err := mb.SearchRecordings(ctx, q, catalogueSearchLimit) - if err != nil { - return nil, err - } - for _, rec := range recs { - res := catalogueSearchResult{ - MBID: rec.MBID, Name: rec.Title, - SecondaryText: joinNonEmpty(rec.ReleaseGroup.Title, rec.ArtistCredit), - ArtistMBID: first(rec.ArtistMBIDs), AlbumMBID: rec.ReleaseGroup.MBID, - } - if rec.ReleaseGroup.MBID != "" { - res.ImageURL = groupArtURL(rec.ReleaseGroup) - } - out = append(out, res) - } - } - return out, nil -} - -// catalogueSearchTTL is how long a search's MusicBrainz answer is reused. -// MusicBrainz allows a request a second, and Discover searches as the user -// types, so the same words are often asked again within moments. -const catalogueSearchTTL = 10 * time.Minute - -// catalogueSearchCacheMax bounds the cache; past it, the cache starts over. -const catalogueSearchCacheMax = 500 - -// searchCache keeps recent MusicBrainz answers by kind and query. A nil -// cache asks every time. Whether a result is held or requested is not -// cached: the handler works that out on every request. -type searchCache struct { - mu sync.Mutex - entries map[string]searchEntry - now func() time.Time -} - -type searchEntry struct { - at time.Time - results []catalogueSearchResult -} - -func newSearchCache() *searchCache { - return &searchCache{entries: map[string]searchEntry{}, now: time.Now} -} - -func (c *searchCache) get(ctx context.Context, kind, q string, - ask func(context.Context, string, string) ([]catalogueSearchResult, error), -) ([]catalogueSearchResult, error) { - if c == nil { - return ask(ctx, kind, q) - } - key := kind + "\x00" + strings.ToLower(q) - c.mu.Lock() - e, ok := c.entries[key] - c.mu.Unlock() - if ok && c.now().Sub(e.at) < catalogueSearchTTL { - return slices.Clone(e.results), nil - } - results, err := ask(ctx, kind, q) - if err != nil { - return nil, err - } - c.mu.Lock() - if len(c.entries) >= catalogueSearchCacheMax { - c.entries = map[string]searchEntry{} - } - c.entries[key] = searchEntry{at: c.now(), results: slices.Clone(results)} - c.mu.Unlock() - return results, nil -} - -// artistLine is what tells two artists of one name apart: MusicBrainz's own -// disambiguation when it has one, else the kind of artist and the country. -func artistLine(a musicbrainz.Artist) string { - if a.Disambiguation != "" { - return a.Disambiguation - } - return joinNonEmpty(a.Type, a.Country) -} - -// groupType names an album's kind the way people do: "Album", "EP", -// "Album · Live", "Single · Remix". -func groupType(g musicbrainz.ReleaseGroup) string { - return joinNonEmpty(append([]string{g.PrimaryType}, g.SecondaryTypes...)...) -} - -func joinNonEmpty(parts ...string) string { - kept := parts[:0:0] - for _, p := range parts { - if p != "" { - kept = append(kept, p) - } - } - return strings.Join(kept, " · ") -} - -func first(s []string) string { - if len(s) == 0 { - return "" - } - return s[0] -} - -// artistArtURL and groupArtURL point at Minstrel's own art endpoints. The -// names ride along for the sources that look art up by name. -func artistArtURL(mbid, name string) string { - if mbid == "" { - return "" - } - return "/api/catalogue/art/artist/" + mbid + "?" + url.Values{"name": {name}}.Encode() -} - -func groupArtURL(g musicbrainz.ReleaseGroup) string { - return "/api/catalogue/art/release-group/" + g.MBID + "?" + - url.Values{"artist": {g.ArtistCredit}, "title": {g.Title}}.Encode() -} - -// catalogueInLibrary reports whether a result is already held: an artist by -// its MBID, an album by its release group (or a release id that happens to be -// the same), a track by its recording. -func (h *handlers) catalogueInLibrary(ctx context.Context, kind, mbid string) (bool, error) { - var query string - switch kind { - case "artist": - query = `SELECT EXISTS(SELECT 1 FROM artists WHERE mbid = $1)` - case "album": - query = `SELECT EXISTS(SELECT 1 FROM albums WHERE release_group_mbid = $1 OR mbid = $1)` - case "track": - query = `SELECT EXISTS(SELECT 1 FROM tracks WHERE mbid = $1)` - default: - return false, nil - } - var exists bool - err := h.pool.QueryRow(ctx, query, mbid).Scan(&exists) - return exists, err -} - -// handleCatalogueArt implements GET /api/catalogue/art/{kind}/{mbid} for an -// artist or a release group Minstrel doesn't hold. The image comes from the -// enabled cover-art sources and is kept on disk, so the browser -// never fetches a third-party host. A 404 shows the placeholder. -func (h *handlers) handleCatalogueArt(w http.ResponseWriter, r *http.Request) { - kind, mbid := chi.URLParam(r, "kind"), chi.URLParam(r, "mbid") - if !catalogue.ValidMBID(mbid) { - writeErr(w, apierror.NotFound("art")) - return - } - var ( - body []byte - err error - ) - switch kind { - case "artist": - body, err = h.catalogueArt.Artist(r.Context(), mbid, r.URL.Query().Get("name")) - case "release-group": - body, err = h.catalogueArt.ReleaseGroup(r.Context(), mbid, r.URL.Query().Get("artist"), r.URL.Query().Get("title")) - default: - writeErr(w, apierror.NotFound("art")) - return - } - if err != nil { - if r.Context().Err() == nil { - writeErr(w, apierror.NotFound("art")) - } - return - } - w.Header().Set("Content-Type", http.DetectContentType(body)) - w.Header().Set("Cache-Control", "private, max-age=86400") - _, _ = w.Write(body) -} diff --git a/internal/api/catalogue_test.go b/internal/api/catalogue_test.go deleted file mode 100644 index 0dfdf7f6..00000000 --- a/internal/api/catalogue_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" -) - -const ( - searchArtistMBID = "a74b1b7f-71a5-4011-9441-d0b5e4122711" - searchGroupMBID = "b1392450-e666-3926-a536-22c65f834433" - searchRecMBID = "c1a0e1b2-0000-4000-8000-000000000001" -) - -// fakeMusicBrainz answers the three searches with one Radiohead result each, -// or 503 when down is set. -func fakeMusicBrainz(t *testing.T, down bool) *httptest.Server { - t.Helper() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if down { - w.WriteHeader(http.StatusServiceUnavailable) - return - } - credit := `[{"name": "Radiohead", "artist": {"id": "` + searchArtistMBID + `"}}]` - group := `{"id": "` + searchGroupMBID + `", "title": "OK Computer", "primary-type": "Album", - "first-release-date": "1997-05-21", "artist-credit": ` + credit + `}` - switch r.URL.Path { - case "/artist": - _, _ = w.Write([]byte(`{"artists": [{"id": "` + searchArtistMBID + `", "name": "Radiohead", "type": "Group", "country": "GB"}]}`)) - case "/release-group": - _, _ = w.Write([]byte(`{"release-groups": [` + group + `]}`)) - case "/recording": - _, _ = w.Write([]byte(`{"recordings": [{"id": "` + searchRecMBID + `", "title": "Karma Police", - "artist-credit": ` + credit + `, - "releases": [{"id": "r1", "status": "Official", "release-group": ` + group + `}]}]}`)) - default: - w.WriteHeader(http.StatusNotFound) - } - })) - t.Cleanup(srv.Close) - return srv -} - -func catalogueHandlers(t *testing.T, down bool) *handlers { - t.Helper() - h, pool := testHandlers(t) - resetRequests(t, h) - mb := &musicbrainz.Client{BaseURL: fakeMusicBrainz(t, down).URL, Pace: &musicbrainz.Pacer{}, Retries: -1} - h.catalogue = catalogue.New(pool, mb, h.logger) - return h -} - -func doCatalogueSearch(t *testing.T, h *handlers, q, kind string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequest(http.MethodGet, "/api/catalogue/search?"+url.Values{"q": {q}, "kind": {kind}}.Encode(), nil) - w := httptest.NewRecorder() - h.handleCatalogueSearch(w, req) - return w -} - -func decodeResults(t *testing.T, w *httptest.ResponseRecorder) []catalogueSearchResult { - t.Helper() - if w.Code != http.StatusOK { - t.Fatalf("status = %d, body = %s", w.Code, w.Body.String()) - } - var out []catalogueSearchResult - if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - return out -} - -func errorCode(t *testing.T, w *httptest.ResponseRecorder) string { - t.Helper() - var resp struct { - Error struct { - Code string `json:"code"` - } `json:"error"` - } - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - return resp.Error.Code -} - -func TestCatalogueSearch_RefusesABadKindOrNoQuery(t *testing.T) { - h := catalogueHandlers(t, false) - if w := doCatalogueSearch(t, h, "x", "playlist"); w.Code != http.StatusBadRequest || errorCode(t, w) != "bad_kind" { - t.Errorf("bad kind: %d %s", w.Code, w.Body.String()) - } - if w := doCatalogueSearch(t, h, " ", "artist"); w.Code != http.StatusBadRequest || errorCode(t, w) != "missing_query" { - t.Errorf("no query: %d %s", w.Code, w.Body.String()) - } -} - -func TestCatalogueSearch_EachKindAsksMusicBrainz(t *testing.T) { - h := catalogueHandlers(t, false) - - artists := decodeResults(t, doCatalogueSearch(t, h, "radiohead", "artist")) - if len(artists) != 1 || artists[0].MBID != searchArtistMBID || artists[0].SecondaryText != "Group · GB" { - t.Fatalf("artists = %+v", artists) - } - if artists[0].ImageURL != "/api/catalogue/art/artist/"+searchArtistMBID+"?name=Radiohead" { - t.Errorf("artist art = %q: it must be Minstrel's own endpoint", artists[0].ImageURL) - } - - albums := decodeResults(t, doCatalogueSearch(t, h, "ok computer", "album")) - if len(albums) != 1 || albums[0].MBID != searchGroupMBID || albums[0].ArtistMBID != searchArtistMBID || - albums[0].SecondaryText != "Radiohead · 1997 · Album" { - t.Fatalf("albums = %+v", albums) - } - - tracks := decodeResults(t, doCatalogueSearch(t, h, "karma police", "track")) - if len(tracks) != 1 || tracks[0].AlbumMBID != searchGroupMBID || tracks[0].ArtistMBID != searchArtistMBID || - tracks[0].SecondaryText != "OK Computer · Radiohead" { - t.Fatalf("tracks = %+v", tracks) - } -} - -func TestCatalogueSearch_MarksWhatIsHeldAndWhatIsRequested(t *testing.T) { - h := catalogueHandlers(t, false) - ctx := context.Background() - q := dbq.New(h.pool) - - artistMBID := searchArtistMBID - artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: dbtest.TestUserPrefix + "Radiohead", SortName: "Radiohead", Mbid: &artistMBID}) - if err != nil { - t.Fatal(err) - } - // The album is held under a release id; its release group is what matches. - if _, err := h.pool.Exec(ctx, - `INSERT INTO albums (title, sort_title, artist_id, mbid, release_group_mbid) VALUES ('OK Computer', 'OK Computer', $1, 'some-release-id', $2)`, - artist.ID, searchGroupMBID); err != nil { - t.Fatal(err) - } - if got := decodeResults(t, doCatalogueSearch(t, h, "radiohead", "artist")); !got[0].InLibrary { - t.Error("the artist is held") - } - if got := decodeResults(t, doCatalogueSearch(t, h, "ok computer", "album")); !got[0].InLibrary { - t.Error("the album is held, matched by release group") - } - - user := seedUser(t, h.pool, "requester", "pw", false) - track := searchRecMBID - if _, err := q.CreateRequest(ctx, dbq.CreateRequestParams{ - UserID: user.ID, Kind: dbq.RequestKindTrack, ArtistMbid: searchArtistMBID, - TrackMbid: &track, ArtistName: "Radiohead", - }); err != nil { - t.Fatal(err) - } - got := decodeResults(t, doCatalogueSearch(t, h, "karma police", "track")) - if got[0].InLibrary || !got[0].Requested { - t.Errorf("track = %+v, want requested and not held", got[0]) - } -} - -func TestCatalogueSearch_UnreachableMusicBrainzIs503(t *testing.T) { - h := catalogueHandlers(t, true) - w := doCatalogueSearch(t, h, "radiohead", "artist") - if w.Code != http.StatusServiceUnavailable || errorCode(t, w) != "musicbrainz_unreachable" { - t.Fatalf("status %d, body %s", w.Code, w.Body.String()) - } -} - -// artSource is an artist-art source with one image. -type artSource struct{ apiTestAlbumProvider } - -func (artSource) FetchArtistArt(_ context.Context, _ coverart.ArtistRef) ([]byte, []byte, error) { - return []byte("\x89PNG\r\n\x1a\nrest"), nil, nil -} - -type fakeArtSources struct{ artists []coverart.ArtistArtProvider } - -func (s fakeArtSources) EnabledArtistProviders() []coverart.ArtistArtProvider { return s.artists } -func (fakeArtSources) EnabledAlbumProviders() []coverart.AlbumCoverProvider { return nil } - -func TestCatalogueArt_ServesTheImageOrAPlaceholder404(t *testing.T) { - h := &handlers{catalogueArt: catalogue.NewArt(t.TempDir(), fakeArtSources{artists: []coverart.ArtistArtProvider{&artSource{}}})} - r := chi.NewRouter() - r.Get("/api/catalogue/art/{kind}/{mbid}", h.handleCatalogueArt) - - get := func(path string) *httptest.ResponseRecorder { - w := httptest.NewRecorder() - r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) - return w - } - if w := get("/api/catalogue/art/artist/" + searchArtistMBID + "?name=Radiohead"); w.Code != http.StatusOK || w.Header().Get("Content-Type") != "image/png" { - t.Errorf("artist: %d %q", w.Code, w.Header().Get("Content-Type")) - } - // No album source is enabled: a 404, which the page shows as its - // placeholder. - if w := get("/api/catalogue/art/release-group/" + searchGroupMBID); w.Code != http.StatusNotFound { - t.Errorf("release group with no source: %d", w.Code) - } - for _, bad := range []string{"/api/catalogue/art/artist/not-an-id", "/api/catalogue/art/label/" + searchArtistMBID} { - if w := get(bad); w.Code != http.StatusNotFound { - t.Errorf("%s: %d", bad, w.Code) - } - } -} - -func TestSuggestionArt_PointsAtMinstrelsOwnEndpoint(t *testing.T) { - views := []suggestionView{{MBID: searchArtistMBID, Name: "Sigur Rós"}, {Name: "No MBID"}} - resolveSuggestionArt(views) - if views[0].ImageURL != "/api/catalogue/art/artist/"+searchArtistMBID+"?name=Sigur+R%C3%B3s" { - t.Errorf("image_url = %q", views[0].ImageURL) - } - if views[1].ImageURL != "" { - t.Errorf("no MBID, no image: %q", views[1].ImageURL) - } -} - -func TestSearchCache_ReusesAnAnswerButNotTheFlags(t *testing.T) { - c := newSearchCache() - now := time.Now() - c.now = func() time.Time { return now } - asks := 0 - ask := func(context.Context, string, string) ([]catalogueSearchResult, error) { - asks++ - return []catalogueSearchResult{{MBID: "m"}}, nil - } - first, _ := c.get(context.Background(), "artist", "Radiohead", ask) - first[0].InLibrary = true // the handler sets flags on what it is given - again, _ := c.get(context.Background(), "artist", "radiohead", ask) - if asks != 1 { - t.Errorf("asks = %d: the same words in another case are the same search", asks) - } - if again[0].InLibrary { - t.Error("a flag set on one answer leaked into the cache") - } - if _, _ = c.get(context.Background(), "album", "radiohead", ask); asks != 2 { - t.Error("another kind is another search") - } - now = now.Add(catalogueSearchTTL + time.Second) - if _, _ = c.get(context.Background(), "artist", "radiohead", ask); asks != 3 { - t.Error("an old answer is asked again") - } - var none *searchCache - if _, _ = none.get(context.Background(), "artist", "x", ask); asks != 4 { - t.Error("a nil cache asks every time") - } -} diff --git a/internal/api/client_assets.go b/internal/api/client_assets.go index 0ce6f507..05b40b18 100644 --- a/internal/api/client_assets.go +++ b/internal/api/client_assets.go @@ -25,13 +25,13 @@ import ( "net/http" "os" "path/filepath" - "strconv" "strings" "sync" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) const ( @@ -121,8 +121,8 @@ func clientAPKAllowDownload(userID string, now time.Time) time.Duration { return 0 } -// clientVersionSidecar is the JSON written beside the bundled APK by -// release.yml. It carries three values that are deliberately separate: +// clientVersionSidecar is the JSON the release build writes beside the +// bundled APK. It carries three values that are deliberately separate: // // - Name is a LABEL for people, "YYYY.MM.DD.HHMM" from the commit's // timestamp. Two channels carrying the same code report the same name. @@ -160,6 +160,10 @@ type clientVersionResponse struct { SHA256 string `json:"sha256"` } +// errNoClientAPK answers both client endpoints when this image carries no +// Android app. +var errNoClientAPK = apierror.New(http.StatusNotFound, "no_client_apk", "no bundled client apk") + // handleClientVersion returns the bundled Android client version + a // URL to fetch the APK. 404 when no APK is bundled. func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) { @@ -169,7 +173,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) { stat, err := os.Stat(apkPath) if errors.Is(err, os.ErrNotExist) { - http.Error(w, `{"error":{"code":"no_client_apk","message":"no bundled client apk"}}`, http.StatusNotFound) + writeErr(w, errNoClientAPK) return } if err != nil { @@ -179,7 +183,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) { versionBytes, err := os.ReadFile(versionPath) if errors.Is(err, os.ErrNotExist) { - http.Error(w, `{"error":{"code":"no_client_version","message":"apk present but version file missing"}}`, http.StatusNotFound) + writeErr(w, apierror.New(http.StatusNotFound, "no_client_version", "apk present but version file missing")) return } if err != nil { @@ -198,7 +202,7 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) { return } if sidecar.Name == "" { - http.Error(w, `{"error":{"code":"bad_client_version","message":"version sidecar has no name"}}`, http.StatusInternalServerError) + writeErr(w, apierror.New(http.StatusInternalServerError, "bad_client_version", "version sidecar has no name")) return } @@ -224,20 +228,19 @@ func (h *handlers) handleClientVersion(w http.ResponseWriter, _ *http.Request) { func (h *handlers) handleClientAPK(w http.ResponseWriter, r *http.Request) { user, ok := auth.UserFromContext(r.Context()) if !ok { - http.Error(w, `{"error":{"code":"unauthenticated","message":"login required"}}`, http.StatusUnauthorized) + writeErr(w, apierror.Unauthorized("unauthenticated", "sign in to continue")) return } userID := syncpkg.FormatUUID(user.ID) if wait := clientAPKAllowDownload(userID, time.Now()); wait > 0 { - w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1)) - http.Error(w, `{"error":{"code":"rate_limited","message":"too many downloads; try again shortly"}}`, http.StatusTooManyRequests) + writeRateLimited(w, wait) return } apkPath := filepath.Join(clientAPKDir(), clientAPKFilename) f, err := os.Open(apkPath) if errors.Is(err, os.ErrNotExist) { - http.Error(w, `{"error":{"code":"no_client_apk","message":"no bundled client apk"}}`, http.StatusNotFound) + writeErr(w, errNoClientAPK) return } if err != nil { diff --git a/internal/api/client_assets_test.go b/internal/api/client_assets_test.go index eb8a77a1..9fc8ca18 100644 --- a/internal/api/client_assets_test.go +++ b/internal/api/client_assets_test.go @@ -15,8 +15,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // authedRequest builds a request with a fake user in context, mirroring @@ -211,20 +211,6 @@ func TestClientVersion_MalformedSidecarErrorsRatherThanReportingNothing(t *testi } } -func TestClientAPK_401WhenUnauthenticated(t *testing.T) { - withClientAPKDir(t) - testResetClientAPKRateLimit() - h := &handlers{logger: slog.New(slog.NewTextHandler(io.Discard, nil))} - rr := httptest.NewRecorder() - // No user in context — middleware would block in prod; handler also - // rejects defensively in case the route ever lands outside the - // authed group by accident. - h.handleClientAPK(rr, httptest.NewRequest(http.MethodGet, "/api/client/apk", nil)) - if rr.Code != http.StatusUnauthorized { - t.Errorf("want 401, got %d", rr.Code) - } -} - func TestClientAPK_404WhenMissing(t *testing.T) { withClientAPKDir(t) testResetClientAPKRateLimit() diff --git a/internal/api/convert.go b/internal/api/convert.go index a48ba868..21e1754b 100644 --- a/internal/api/convert.go +++ b/internal/api/convert.go @@ -8,7 +8,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) var errBadPaging = errors.New("invalid limit or offset") @@ -84,26 +85,41 @@ func streamURLWithExt(trackID pgtype.UUID, ext string) string { return streamURL(trackID) + "." + ext } -// artistRefFrom projects a dbq.Artist into an ArtistRef without cover. -// albumCount must be pre-computed by the caller. Used by code paths that -// don't have a representative-album lookup at hand (artist detail, search, -// liked-artists list). +// artistImageURL returns the /api relative URL of an artist's image. +func artistImageURL(artistID pgtype.UUID) string { + return "/api/artists/" + uuidToString(artistID) + "/image" +} + +// hasArtistPicture reports whether the artist-art providers fetched a +// picture for a. +func hasArtistPicture(a dbq.Artist) bool { + return a.ArtistThumbPath != nil && *a.ArtistThumbPath != "" +} + +// artistRefFrom projects a dbq.Artist into an ArtistRef. albumCount must be +// pre-computed by the caller. CoverURL is the artist's picture when one was +// fetched, and empty otherwise: these code paths (artist detail, search, +// liked-artists list) have no representative-album lookup at hand. func artistRefFrom(a dbq.Artist, albumCount int) ArtistRef { - return ArtistRef{ + ref := ArtistRef{ ID: uuidToString(a.ID), Name: a.Name, SortName: a.SortName, AlbumCount: albumCount, } + if hasArtistPicture(a) { + ref.CoverURL = artistImageURL(a.ID) + } + return ref } -// artistRefFromCovered projects a dbq.Artist into an ArtistRef with the -// derived CoverURL populated from a representative album id (nullable). -// Used by /api/home and /api/artists?sort=alpha which carry the lookup -// in the same query. +// artistRefFromCovered projects a dbq.Artist into an ArtistRef whose CoverURL +// is the artist's picture when one was fetched, or else the cover of a +// representative album id (nullable). Used by /api/home and +// /api/artists?sort=alpha, which carry the album lookup in the same query. func artistRefFromCovered(a dbq.Artist, albumCount int, coverAlbumID pgtype.UUID) ArtistRef { ref := artistRefFrom(a, albumCount) - if coverAlbumID.Valid { + if ref.CoverURL == "" && coverAlbumID.Valid { ref.CoverURL = coverURL(coverAlbumID) } return ref @@ -128,7 +144,8 @@ func albumRefFrom(a dbq.Album, artistName string, trackCount, durationSec int) A } // trackRefFrom projects a dbq.Track into a TrackRef. Parent names must be -// pre-resolved because Track only carries album_id and artist_id. +// pre-resolved because Track only carries album_id and artist_id; the track's +// own credit, when its tags name a guest, replaces artistName. func trackRefFrom(t dbq.Track, albumTitle, artistName string) TrackRef { ref := TrackRef{ ID: uuidToString(t.ID), @@ -136,7 +153,7 @@ func trackRefFrom(t dbq.Track, albumTitle, artistName string) TrackRef { AlbumID: uuidToString(t.AlbumID), AlbumTitle: albumTitle, ArtistID: uuidToString(t.ArtistID), - ArtistName: artistName, + ArtistName: db.TrackCredit(t, artistName), DurationSec: durationMsToSec(t.DurationMs), StreamURL: streamURL(t.ID), Unavailable: t.MissingSince.Valid, @@ -194,3 +211,11 @@ func nonNilStrings(in []string) []string { } return in } + +// deref is a nullable column's text, or "". +func deref(s *string) string { + if s == nil { + return "" + } + return *s +} diff --git a/internal/api/convert_test.go b/internal/api/convert_test.go index f2d0bc12..083264cd 100644 --- a/internal/api/convert_test.go +++ b/internal/api/convert_test.go @@ -6,7 +6,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func TestUUIDToString(t *testing.T) { @@ -80,12 +80,12 @@ func TestCoverURLAndStreamURL(t *testing.T) { func TestArtistRefFrom(t *testing.T) { var id pgtype.UUID _ = id.Scan("00112233-4455-6677-8899-aabbccddeeff") - a := dbq.Artist{ID: id, Name: "Beatles", SortName: "Beatles"} + a := dbq.Artist{ID: id, Name: "Copper Lanterns", SortName: "Copper Lanterns"} got := artistRefFrom(a, 7) if got.ID != "00112233-4455-6677-8899-aabbccddeeff" { t.Errorf("ID = %q", got.ID) } - if got.Name != "Beatles" || got.AlbumCount != 7 { + if got.Name != "Copper Lanterns" || got.AlbumCount != 7 { t.Errorf("ref = %+v", got) } } @@ -96,9 +96,9 @@ func TestAlbumRefFrom(t *testing.T) { _ = artID.Scan("00000000-0000-0000-0000-000000000002") var rel pgtype.Date _ = rel.Scan("1969-09-26") - a := dbq.Album{ID: aid, Title: "Abbey Road", ArtistID: artID, ReleaseDate: rel} - got := albumRefFrom(a, "Beatles", 17, 2820) - if got.Title != "Abbey Road" || got.ArtistName != "Beatles" { + a := dbq.Album{ID: aid, Title: "Harbour Street", ArtistID: artID, ReleaseDate: rel} + got := albumRefFrom(a, "Copper Lanterns", 17, 2820) + if got.Title != "Harbour Street" || got.ArtistName != "Copper Lanterns" { t.Errorf("ref = %+v", got) } if got.TrackCount != 17 || got.DurationSec != 2820 { @@ -120,12 +120,12 @@ func TestTrackRefFrom(t *testing.T) { trackNum := int32(3) discNum := int32(1) t2 := dbq.Track{ - ID: tid, Title: "Something", AlbumID: aid, ArtistID: artID, + ID: tid, Title: "Somewhere Near", AlbumID: aid, ArtistID: artID, TrackNumber: &trackNum, DiscNumber: &discNum, DurationMs: 183_000, } - got := trackRefFrom(t2, "Abbey Road", "Beatles") - if got.Title != "Something" || got.AlbumTitle != "Abbey Road" || got.ArtistName != "Beatles" { + got := trackRefFrom(t2, "Harbour Street", "Copper Lanterns") + if got.Title != "Somewhere Near" || got.AlbumTitle != "Harbour Street" || got.ArtistName != "Copper Lanterns" { t.Errorf("ref = %+v", got) } if got.TrackNumber != 3 || got.DiscNumber != 1 { diff --git a/internal/api/diagnostics.go b/internal/api/diagnostics.go index 83ec7cb2..63ef97c6 100644 --- a/internal/api/diagnostics.go +++ b/internal/api/diagnostics.go @@ -10,12 +10,12 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // validDiagnosticKinds is the COARSE category whitelist. Mirrors the -// CHECK constraint in migration 0036 — keep both in sync (per the +// CHECK constraint on diagnostic_events.kind — keep both in sync (per the // enum-CHECK-whitelist rule). The finer event discriminator + all // event-specific fields live inside each event's payload, so new event // variants do NOT require a new category here. @@ -280,13 +280,12 @@ func (h *handlers) handleAdminDebugModeToggle(w http.ResponseWriter, r *http.Req h.logger.Info("admin: debug mode toggled", "target_user", uuidToString(targetID), "enabled", req.Enabled) writeJSON(w, http.StatusOK, adminUserView{ - ID: uuidToString(updated.ID), - Username: updated.Username, - DisplayName: updated.DisplayName, - IsAdmin: updated.IsAdmin, - AutoApproveRequests: updated.AutoApproveRequests, - DebugModeEnabled: updated.DebugModeEnabled, - CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339), + ID: uuidToString(updated.ID), + Username: updated.Username, + DisplayName: updated.DisplayName, + IsAdmin: updated.IsAdmin, + DebugModeEnabled: updated.DebugModeEnabled, + CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339), }) } diff --git a/internal/api/errors.go b/internal/api/errors.go index 71b81d3c..02860a7e 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -8,35 +8,14 @@ import ( "strconv" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/apierror" ) -// errorBody / errorPayload preserve the existing wire envelope: -// -// {"error": {"code": "...", "message": "..."}} -// -// Kept separate from the Subsonic envelope so native clients don't have -// to parse two shapes. -type errorBody struct { - Error errorPayload `json:"error"` -} - -type errorPayload struct { - Code string `json:"code"` - Message string `json:"message"` -} - -// writeErr emits the failure envelope for err. If err is or wraps -// *apierror.Error, its Status/Code/Message drive the response; -// otherwise it's mapped to a 500 server_error. +// writeErr answers err in the one /api error envelope (apierror.Body). If err +// is or wraps *apierror.Error, its Status/Code/Message drive the response; +// otherwise it's a 500 server_error. func writeErr(w http.ResponseWriter, err error) { - apiErr := apierror.From(err) - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(apiErr.Status) - _ = json.NewEncoder(w).Encode(errorBody{Error: errorPayload{ - Code: apiErr.Code, - Message: apiErr.Message, - }}) + apierror.Write(w, err) } // writeRateLimited answers 429 with Retry-After in whole seconds, rounded @@ -67,12 +46,3 @@ func writeJSON(w http.ResponseWriter, status int, body any) { w.WriteHeader(status) _ = json.NewEncoder(w).Encode(body) } - -// writeAdminJSONErr writes a flat {"error":""} JSON response. This -// mirrors the shape the RequireAdmin middleware uses and that the spec -// defines for /api/admin/* errors. -func writeAdminJSONErr(w http.ResponseWriter, status int, code string) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(map[string]string{"error": code}) -} diff --git a/internal/api/errors_test.go b/internal/api/errors_test.go deleted file mode 100644 index 8cc627c5..00000000 --- a/internal/api/errors_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package api - -import ( - "encoding/json" - "errors" - "fmt" - "net/http/httptest" - "testing" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" -) - -func decodeEnvelope(t *testing.T, body []byte) errorBody { - t.Helper() - var env errorBody - if err := json.Unmarshal(body, &env); err != nil { - t.Fatalf("decode envelope: %v (body=%s)", err, string(body)) - } - return env -} - -func TestWriteErr_APIError(t *testing.T) { - rec := httptest.NewRecorder() - writeErr(rec, apierror.NotFound("track")) - - if rec.Code != 404 { - t.Fatalf("status: want 404, got %d", rec.Code) - } - env := decodeEnvelope(t, rec.Body.Bytes()) - if env.Error.Code != "track_not_found" { - t.Errorf("code: want track_not_found, got %q", env.Error.Code) - } - if env.Error.Message != "track not found" { - t.Errorf("message: want %q, got %q", "track not found", env.Error.Message) - } -} - -func TestWriteErr_Sentinel(t *testing.T) { - rec := httptest.NewRecorder() - writeErr(rec, apierror.ErrUnauthorized) - - if rec.Code != 401 { - t.Fatalf("status: want 401, got %d", rec.Code) - } - env := decodeEnvelope(t, rec.Body.Bytes()) - if env.Error.Code != "unauthorized" { - t.Errorf("code: want unauthorized, got %q", env.Error.Code) - } - if env.Error.Message != "authentication required" { - t.Errorf("message: want %q, got %q", "authentication required", env.Error.Message) - } -} - -func TestWriteErr_PlainError(t *testing.T) { - rec := httptest.NewRecorder() - writeErr(rec, errors.New("boom")) - - if rec.Code != 500 { - t.Fatalf("status: want 500, got %d", rec.Code) - } - env := decodeEnvelope(t, rec.Body.Bytes()) - if env.Error.Code != "server_error" { - t.Errorf("code: want server_error, got %q", env.Error.Code) - } - if env.Error.Message != "internal server error" { - t.Errorf("message: want %q, got %q", "internal server error", env.Error.Message) - } -} - -func TestWriteErr_WrappedAPIError(t *testing.T) { - rec := httptest.NewRecorder() - writeErr(rec, fmt.Errorf("ctx: %w", apierror.BadRequest("bad", "no good"))) - - if rec.Code != 400 { - t.Fatalf("status: want 400, got %d", rec.Code) - } - env := decodeEnvelope(t, rec.Body.Bytes()) - if env.Error.Code != "bad" { - t.Errorf("code: want bad, got %q", env.Error.Code) - } - if env.Error.Message != "no good" { - t.Errorf("message: want %q, got %q", "no good", env.Error.Message) - } -} - -func TestWriteErr_EnvelopeShape(t *testing.T) { - rec := httptest.NewRecorder() - writeErr(rec, apierror.BadRequest("x", "y")) - - var raw map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil { - t.Fatalf("decode raw: %v", err) - } - if len(raw) != 1 { - t.Fatalf("top-level keys: want 1, got %d (%v)", len(raw), raw) - } - inner, ok := raw["error"].(map[string]any) - if !ok { - t.Fatalf("error: want object, got %T", raw["error"]) - } - if len(inner) != 2 { - t.Fatalf("inner keys: want 2, got %d (%v)", len(inner), inner) - } - if _, ok := inner["code"]; !ok { - t.Errorf("inner.code missing") - } - if _, ok := inner["message"]; !ok { - t.Errorf("inner.message missing") - } -} - -func TestWriteErr_ContentType(t *testing.T) { - rec := httptest.NewRecorder() - writeErr(rec, apierror.BadRequest("x", "y")) - - if got := rec.Header().Get("Content-Type"); got != "application/json" { - t.Errorf("Content-Type: want application/json, got %q", got) - } -} diff --git a/internal/api/events.go b/internal/api/events.go index 5946d78b..0fa605b5 100644 --- a/internal/api/events.go +++ b/internal/api/events.go @@ -9,8 +9,9 @@ import ( "github.com/jackc/pgx/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/playevents" ) type eventRequest struct { @@ -59,26 +60,6 @@ type playStartedResponse struct { SessionID string `json:"session_id"` } -// eventFutureSkew is the tolerated client-clock drift into the future -// before a timestamp is treated as bogus and replaced with now. -const eventFutureSkew = 5 * time.Minute - -// clampEventTime bounds a client-supplied event timestamp to sanity: -// no earlier than the account's creation (offline replays can -// legitimately be days old, but no play can predate the user) and no -// later than now + a small skew allowance. An unbounded client clock would -// let a skewed device write arbitrarily old plays, poisoning Rediscover's -// "not played in 6 months" ordering. -func clampEventTime(at, userCreatedAt, now time.Time) time.Time { - if at.Before(userCreatedAt) { - return userCreatedAt - } - if at.After(now.Add(eventFutureSkew)) { - return now - } - return at -} - type okResponse struct { OK bool `json:"ok"` } @@ -100,7 +81,7 @@ func (h *handlers) handleEvents(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.BadRequest("bad_request", "invalid `at` timestamp")) return } - at = clampEventTime(parsed.UTC(), user.CreatedAt.Time, time.Now().UTC()) + at = playevents.ClampClientTime(parsed.UTC(), user.CreatedAt.Time, time.Now().UTC()) } clientID := "" if req.ClientID != nil { diff --git a/internal/api/events_publish.go b/internal/api/events_publish.go index 40eadb46..45d1d06d 100644 --- a/internal/api/events_publish.go +++ b/internal/api/events_publish.go @@ -6,8 +6,7 @@ package api import ( - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" + "github.com/Fabled-Sword/minstrel/internal/eventbus" "github.com/jackc/pgx/v5/pgtype" ) @@ -19,32 +18,7 @@ func (h *handlers) publishLikeEvent(userID, entityID pgtype.UUID, entityType str if h.eventbus == nil { return } - kind := "track.liked" - if !liked { - kind = "track.unliked" - } - if entityType == "album" { - if liked { - kind = "album.liked" - } else { - kind = "album.unliked" - } - } - if entityType == "artist" { - if liked { - kind = "artist.liked" - } else { - kind = "artist.unliked" - } - } - h.eventbus.Publish(eventbus.Event{ - Kind: kind, - UserID: uuidToString(userID), - Data: map[string]any{ - "entity_type": entityType, - "entity_id": uuidToString(entityID), - }, - }) + h.eventbus.Publish(eventbus.LikeChanged(uuidToString(userID), entityType, uuidToString(entityID), liked)) } // publishQuarantineEvent broadcasts a quarantine action. User-side @@ -70,24 +44,6 @@ func (h *handlers) publishQuarantineEvent(kind string, userID, trackID pgtype.UU }) } -// publishPlaylistEvent broadcasts a playlist mutation to the owner so -// their other clients invalidate the affected playlist (and playlist list) -// providers. Public-playlist subscribers are out of scope here — they'd -// need a separate "playlists.public_updated" broadcast, deferred until -// the multi-user case is exercised. -func (h *handlers) publishPlaylistEvent(kind string, ownerID, playlistID pgtype.UUID) { - if h.eventbus == nil { - return - } - h.eventbus.Publish(eventbus.Event{ - Kind: kind, - UserID: uuidToString(ownerID), - Data: map[string]any{ - "playlist_id": uuidToString(playlistID), - }, - }) -} - // publishSystemRebuilt notifies the owner's clients that their system // playlists (and You-might-like rows) were regenerated, so they invalidate // the home / system-playlist providers and a stale active queue can re-pull. @@ -102,23 +58,3 @@ func (h *handlers) publishSystemRebuilt(userID pgtype.UUID) { Data: map[string]any{}, }) } - -// publishRequestStatusChanged broadcasts a request status flip to -// the request's original requester so their /requests page reflects the -// new state without manual refresh. Admin actors (approve / reject) still -// route to the requester's user_id, not the admin's — the original user -// is who needs to see the update. -func (h *handlers) publishRequestStatusChanged(row dbq.Request) { - if h.eventbus == nil { - return - } - h.eventbus.Publish(eventbus.Event{ - Kind: "request.status_changed", - UserID: uuidToString(row.UserID), - Data: map[string]any{ - "request_id": uuidToString(row.ID), - "status": string(row.Status), - "kind": string(row.Kind), - }, - }) -} diff --git a/internal/api/events_stream.go b/internal/api/events_stream.go index f9fccf8f..b8d45905 100644 --- a/internal/api/events_stream.go +++ b/internal/api/events_stream.go @@ -1,7 +1,7 @@ // Live event stream — Server-Sent Events at GET /api/events/stream. // // The web app and the Android app subscribe to be notified of state changes -// elsewhere in the system (likes, request status flips, quarantine +// elsewhere in the system (likes, quarantine // resolutions, scan progress, playlist mutations) so static screens // can invalidate cached data without explicit user action. // @@ -28,8 +28,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/eventbus" ) // userUUIDString renders a pgtype.UUID in canonical 8-4-4-4-12 form so @@ -57,13 +58,13 @@ const ( func (h *handlers) handleEventsStream(w http.ResponseWriter, r *http.Request) { user, ok := auth.UserFromContext(r.Context()) if !ok { - http.Error(w, "unauthorized", http.StatusUnauthorized) + writeErr(w, apierror.ErrUnauthorized) return } flusher, ok := w.(http.Flusher) if !ok { - http.Error(w, "streaming unsupported", http.StatusInternalServerError) + writeErr(w, apierror.InternalMsg("streaming unsupported", nil)) return } diff --git a/internal/api/events_test.go b/internal/api/events_test.go index 98e52e87..5f93feee 100644 --- a/internal/api/events_test.go +++ b/internal/api/events_test.go @@ -9,7 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // callEvents invokes h.handleEvents directly, injecting `user` via the same @@ -28,8 +28,8 @@ func TestHandleEvents_PlayStartedReturnsIDs(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "Beatles") - album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) + artist := seedArtist(t, pool, "Copper Lanterns") + album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) body, _ := json.Marshal(map[string]any{ @@ -56,8 +56,8 @@ func TestHandleEvents_PlayEndedClosesRow(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "Beatles") - album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) + artist := seedArtist(t, pool, "Copper Lanterns") + album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) startedID := postPlayStartedHelper(t, h, user, track.ID) diff --git a/internal/api/file_remove_error.go b/internal/api/file_remove_error.go index f9cfb670..6c740d8b 100644 --- a/internal/api/file_remove_error.go +++ b/internal/api/file_remove_error.go @@ -6,8 +6,8 @@ import ( "log/slog" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/library" ) // fileRemoveAPIError answers a delete that could not reach the track's file. diff --git a/internal/api/file_remove_error_test.go b/internal/api/file_remove_error_test.go index f0925865..db8da3cc 100644 --- a/internal/api/file_remove_error_test.go +++ b/internal/api/file_remove_error_test.go @@ -9,13 +9,13 @@ import ( "syscall" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/library" ) -const removeTestPath = "/music/Moe Shop/WWW (2020)/01 - WWW.mp3" +const removeTestPath = "/music/Mochi Shop/XYZ (2020)/01 - XYZ.mp3" // removeFailure builds the error a delete service returns when the file would -// not go, wrapped the way quarantine.DeleteFile and tracks.RemoveTrack +// not go, wrapped the way quarantine.DeleteFile and quarantine.RemoveFile // wrap it — the mapping has to see through that. func removeFailure(errno syscall.Errno) error { return fmt.Errorf("delete file: %w", &library.FileRemoveError{ @@ -35,7 +35,7 @@ func TestFileRemoveAPIError(t *testing.T) { { name: "read-only mount", errno: syscall.EROFS, wantStatus: http.StatusConflict, wantCode: "library_not_writable", - wantIn: []string{"uid 1000, gid 1000", "/music/Moe Shop/WWW (2020)", "read-only file system", "Nothing was deleted"}, + wantIn: []string{"uid 1000, gid 1000", "/music/Mochi Shop/XYZ (2020)", "read-only file system", "Nothing was deleted"}, }, { name: "permission denied", errno: syscall.EACCES, @@ -77,7 +77,7 @@ func TestFileRemoveAPIError(t *testing.T) { // plain "contains the directory" check could never catch that regression. func TestFileRemoveAPIError_NotWritableNamesTheDirectoryNotTheFile(t *testing.T) { apiErr, _ := fileRemoveAPIError(removeFailure(syscall.EROFS)) - if strings.Contains(apiErr.Message, "01 - WWW.mp3") { + if strings.Contains(apiErr.Message, "01 - XYZ.mp3") { t.Fatalf("message names the file rather than its directory: %q", apiErr.Message) } } diff --git a/internal/api/home.go b/internal/api/home.go index 22014c84..00efb0cc 100644 --- a/internal/api/home.go +++ b/internal/api/home.go @@ -3,9 +3,9 @@ package api import ( "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/recommendation" ) // handleGetHome implements GET /api/home. Returns five sections in one diff --git a/internal/api/home_test.go b/internal/api/home_test.go index 123161b5..07831f37 100644 --- a/internal/api/home_test.go +++ b/internal/api/home_test.go @@ -9,7 +9,7 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func newHomeRouter(h *handlers) chi.Router { diff --git a/internal/api/leveled_stream.go b/internal/api/leveled_stream.go index 30e9fb3b..db740030 100644 --- a/internal/api/leveled_stream.go +++ b/internal/api/leveled_stream.go @@ -15,10 +15,10 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // The leveled stream: a track rendered with the user's loudness diff --git a/internal/api/leveled_stream_test.go b/internal/api/leveled_stream_test.go index 9bab2feb..ad7ff179 100644 --- a/internal/api/leveled_stream_test.go +++ b/internal/api/leveled_stream_test.go @@ -15,8 +15,8 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) func TestLeveledStreamToken(t *testing.T) { @@ -81,7 +81,7 @@ func TestCastStreamToken_Leveled(t *testing.T) { } h.leveled = r user := seedUser(t, pool, "lev", "pw", false) - track, _ := seedTrackForRemoveTest(t, h, "lev", "", "") + track, _ := seedTrackOnDiskWithMBIDs(t, h, "lev", "", "") trackID := uuidToString(track.ID) lufs, peak := float32(-12.5), float32(-1) if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{ diff --git a/internal/api/library.go b/internal/api/library.go index 685bf952..04e7e9b6 100644 --- a/internal/api/library.go +++ b/internal/api/library.go @@ -8,9 +8,10 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // handleGetTrack implements GET /api/tracks/{id}. Resolves parent album + @@ -75,10 +76,16 @@ func (h *handlers) handleGetAlbum(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("lookup failed", err)) return } + // Each track is named by its own artist: on a compilation or a track + // with a guest, that is not the album's. + names, err := db.TrackArtistNames(r.Context(), q, album.ID) + if err != nil { + h.logger.Warn("api: album track artists failed; naming the album artist", "err", err) + } refs := make([]TrackRef, 0, len(tracks)) durSec := 0 for _, t := range tracks { - ref := trackRefFrom(t, album.Title, artistName) + ref := trackRefFrom(t, album.Title, names.For(t.ArtistID, artistName)) refs = append(refs, ref) durSec += ref.DurationSec } @@ -133,6 +140,12 @@ func (h *handlers) handleGetArtist(w http.ResponseWriter, r *http.Request) { Albums: refs, Genres: nonNilStrings(genres), } + // An artist with albums always gets the image route: it serves the + // artist's picture, or else their newest album cover, so the detail + // header and Subsonic apps show the same image. + if len(rows) > 0 { + detail.CoverURL = artistImageURL(artist.ID) + } if artist.Mbid != nil { detail.MBID = *artist.Mbid } diff --git a/internal/api/library_albums.go b/internal/api/library_albums.go index e57f0e8b..9f9f0b78 100644 --- a/internal/api/library_albums.go +++ b/internal/api/library_albums.go @@ -8,8 +8,8 @@ import ( "strconv" "strings" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // Widest plausible bounds for an open-ended year filter. A missing year_from diff --git a/internal/api/library_albums_test.go b/internal/api/library_albums_test.go index 95def123..59556f9a 100644 --- a/internal/api/library_albums_test.go +++ b/internal/api/library_albums_test.go @@ -9,7 +9,7 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func newLibraryAlbumsRouter(h *handlers) chi.Router { diff --git a/internal/api/library_browse.go b/internal/api/library_browse.go index ce65632e..83be442e 100644 --- a/internal/api/library_browse.go +++ b/internal/api/library_browse.go @@ -3,8 +3,8 @@ package api import ( "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // genreCount is one row of the genre browse index. diff --git a/internal/api/library_browse_test.go b/internal/api/library_browse_test.go index 9d8988fe..4a69c458 100644 --- a/internal/api/library_browse_test.go +++ b/internal/api/library_browse_test.go @@ -10,7 +10,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // parseYearFilter is pure, so this runs in the fast lane rather than waiting diff --git a/internal/api/library_fixtures_test.go b/internal/api/library_fixtures_test.go index 2a8c6f16..32457016 100644 --- a/internal/api/library_fixtures_test.go +++ b/internal/api/library_fixtures_test.go @@ -11,7 +11,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // truncateLibrary clears the music tables between tests. Sessions/users are @@ -187,3 +187,50 @@ func seedTrackWithFile(t *testing.T, pool *pgxpool.Pool, albumID, artistID pgtyp } return tr, dir } + +// seedTrackOnDiskWithMBIDs creates a fresh artist+album+track on disk and +// returns the track row. The mbids are set on the track and album when +// non-empty. +func seedTrackOnDiskWithMBIDs(t *testing.T, h *handlers, unique, trackMbid, albumMbid string) (dbq.Track, string) { + t.Helper() + artist := seedArtist(t, h.pool, "RemoveTest Artist "+unique) + dir := t.TempDir() + path := filepath.Join(dir, "track-"+unique+".mp3") + if err := os.WriteFile(path, []byte("audio"), 0o644); err != nil { + t.Fatalf("write file: %v", err) + } + q := dbq.New(h.pool) + var albumMbidPtr *string + if albumMbid != "" { + albumMbidPtr = &albumMbid + } + album, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{ + Title: "RemoveTest Album " + unique, + SortTitle: "RemoveTest Album " + unique, + ArtistID: artist.ID, + Mbid: albumMbidPtr, + }) + if err != nil { + t.Fatalf("UpsertAlbum: %v", err) + } + one := int32(1) + var trackMbidPtr *string + if trackMbid != "" { + trackMbidPtr = &trackMbid + } + tr, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{ + Title: "RemoveTest Track " + unique, + AlbumID: album.ID, + ArtistID: artist.ID, + TrackNumber: &one, + DurationMs: 30000, + FilePath: path, + FileSize: 5, + FileFormat: "mp3", + Mbid: trackMbidPtr, + }) + if err != nil { + t.Fatalf("UpsertTrack: %v", err) + } + return tr, path +} diff --git a/internal/api/library_sync.go b/internal/api/library_sync.go index 932d7b93..d0b59613 100644 --- a/internal/api/library_sync.go +++ b/internal/api/library_sync.go @@ -8,10 +8,10 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // SyncBatchLimit caps the number of change rows returned per call. @@ -36,11 +36,12 @@ type syncResponse struct { // Responses: // - 204 No Content — no changes since cursor // - 200 OK — JSON syncResponse with upserts, deletes, new cursor -// - 410 Gone — cursor older than oldest log row; client must reset +// - 410 Gone — the client must reset its cursor to 0: the cursor is +// older than a delete the log has dropped, or past anything this server +// has handed out // - 401 / 500 — standard envelope errors func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { + if _, ok := requireUser(w, r); !ok { return } ctx := r.Context() @@ -52,16 +53,17 @@ func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { q := dbq.New(h.pool) - // 410 path: if the requested cursor is older than the oldest row, - // tell the client to reset. (No compaction job in this slice; the - // path exists for future compaction support.) + // The log keeps every entity's latest change, so a client syncing from + // 0 gets the whole library. It drops deletes older than its retention, + // and a cursor below the newest dropped one may have missed it: the + // client resets and syncs again from 0. if since > 0 { - minCursor, err := q.GetMinLibraryChangeCursor(ctx) + trimmed, err := q.GetLibraryChangesTrimmedThrough(ctx) if err != nil { - writeErrWithLog(w, h.logger, "library_sync: GetMinLibraryChangeCursor", err) + writeErrWithLog(w, h.logger, "library_sync: GetLibraryChangesTrimmedThrough", err) return } - if minCursor > 0 && since+1 < minCursor { + if since < trimmed { writeErr(w, &apierror.Error{ Status: http.StatusGone, Code: "cursor_too_old", @@ -69,6 +71,23 @@ func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { }) return } + // A cursor past anything this server has handed out comes from a + // server restored from an older backup: the changes between the + // backup and the cursor are gone, and the ones made from here on would + // reuse those ids. The app resets the same way. + lastCursor, err := q.GetLastIssuedLibraryChangeCursor(ctx) + if err != nil { + writeErrWithLog(w, h.logger, "library_sync: GetLastIssuedLibraryChangeCursor", err) + return + } + if since > lastCursor { + writeErr(w, &apierror.Error{ + Status: http.StatusGone, + Code: "cursor_ahead", + Message: "this server holds no changes up to that cursor; reset client cursor to 0 and resync", + }) + return + } } changes, err := q.GetLibraryChangesSince(ctx, dbq.GetLibraryChangesSinceParams{ @@ -101,7 +120,7 @@ func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { } } - upserts, err := h.hydrateUpserts(ctx, q, user.ID, upsertIDs) + upserts, err := h.hydrateUpserts(ctx, q, upsertIDs) if err != nil { writeErrWithLog(w, h.logger, "library_sync: hydrateUpserts", err) return @@ -121,16 +140,11 @@ func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { } // hydrateUpserts loads the current row payloads for each upserted id, -// keyed by entity type (string form). Returns json.RawMessage values so -// each entity's full sqlc row shape passes through unchanged. -// -// Per-user entities (likes, playlists, playlist_tracks) are scoped to -// userID — the change log is global but each user only sees rows that -// concern them. +// keyed by entity type (string form). The log covers the shared library +// only (artists, albums, tracks), so every caller sees the same rows. func (h *handlers) hydrateUpserts( ctx context.Context, q *dbq.Queries, - userID pgtype.UUID, ids map[syncpkg.EntityType][]string, ) (map[string][]json.RawMessage, error) { out := map[string][]json.RawMessage{} @@ -177,73 +191,9 @@ func (h *handlers) hydrateUpserts( } } - userIDStr := syncpkg.FormatUUID(userID) - - if rows := ids[syncpkg.EntityLikeTrack]; len(rows) > 0 { - out["like_track"] = scopedLikeRows(rows, userIDStr, "track_id") - } - if rows := ids[syncpkg.EntityLikeAlbum]; len(rows) > 0 { - out["like_album"] = scopedLikeRows(rows, userIDStr, "album_id") - } - if rows := ids[syncpkg.EntityLikeArtist]; len(rows) > 0 { - out["like_artist"] = scopedLikeRows(rows, userIDStr, "artist_id") - } - - if rows := ids[syncpkg.EntityPlaylist]; len(rows) > 0 { - uuids := stringsToUUIDs(rows) - playlists, err := q.GetPlaylistsByIDs(ctx, uuids) - if err != nil { - return nil, err - } - for _, p := range playlists { - // Filter: only return playlists owned by this user OR public ones - if syncpkg.FormatUUID(p.UserID) != userIDStr && !p.IsPublic { - continue - } - b, _ := json.Marshal(toPlaylistSyncView(p)) - out["playlist"] = append(out["playlist"], b) - } - } - if rows := ids[syncpkg.EntityPlaylistTrack]; len(rows) > 0 { - // playlist_track ids are ":" — we don't know - // playlist ownership here without a JOIN. Pass through; client - // reconciles against its locally-cached playlists. - var msgs []json.RawMessage - for _, id := range rows { - parts := splitOnce(id, ":") - if len(parts) != 2 { - continue - } - b, _ := json.Marshal(map[string]string{ - "playlist_id": parts[0], - "track_id": parts[1], - }) - msgs = append(msgs, b) - } - out["playlist_track"] = msgs - } return out, nil } -// scopedLikeRows filters composite-key like rows to those owned by userID -// and emits {user_id, } JSON shapes. entityKey is "track_id", -// "album_id", or "artist_id" depending on the like table. -func scopedLikeRows(rows []string, userIDStr, entityKey string) []json.RawMessage { - var msgs []json.RawMessage - for _, id := range rows { - parts := splitOnce(id, ":") - if len(parts) != 2 || parts[0] != userIDStr { - continue - } - b, _ := json.Marshal(map[string]string{ - "user_id": parts[0], - entityKey: parts[1], - }) - msgs = append(msgs, b) - } - return msgs -} - // stringsToUUIDs parses each string as a pgtype.UUID. Invalid entries // are skipped silently — they can't have come from a valid scan/mutation. func stringsToUUIDs(strs []string) []pgtype.UUID { @@ -257,14 +207,3 @@ func stringsToUUIDs(strs []string) []pgtype.UUID { } return out } - -// splitOnce returns [before, after] split at the first occurrence of sep, -// or [s] if sep doesn't appear. Used for composite-key parsing. -func splitOnce(s, sep string) []string { - for i := 0; i+len(sep) <= len(s); i++ { - if s[i:i+len(sep)] == sep { - return []string{s[:i], s[i+len(sep):]} - } - } - return []string{s} -} diff --git a/internal/api/library_sync_test.go b/internal/api/library_sync_test.go index 4539a4a4..22d927da 100644 --- a/internal/api/library_sync_test.go +++ b/internal/api/library_sync_test.go @@ -6,11 +6,12 @@ import ( "net/http" "net/http/httptest" "strconv" + "strings" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/sync" ) func callLibrarySync(h *handlers, user dbq.User, since string) *httptest.ResponseRecorder { @@ -52,7 +53,7 @@ func TestLibrarySync_AfterArtistUpsert_ReturnsHydratedPayload(t *testing.T) { var artistID string if err := tx.QueryRow(ctx, `INSERT INTO artists (name, sort_name) VALUES ($1, $2) RETURNING id::text`, - "Boards of Canada", "Boards of Canada", + "Fields of Ontario", "Fields of Ontario", ).Scan(&artistID); err != nil { t.Fatalf("insert artist: %v", err) } @@ -145,62 +146,84 @@ func TestLibrarySync_DeleteIsReflected(t *testing.T) { } } -func TestLibrarySync_LikeRowScopedToUser(t *testing.T) { +// Pure unit tests below — run even with -short. + +// A server restored from an older backup has handed out fewer cursors than an +// app remembers; the app is told to reset rather than wait for ids it would +// then skip. A compacted log is not that: the cursor the server handed out +// still counts. +func TestLibrarySync_ACursorPastTheServersLastChangeIsReset(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) u := seedUser(t, pool, "alice", "x", false) - other := seedUser(t, pool, "bob", "x", false) - // Two like_track rows: one for u, one for other. u's call should - // see only their own row. ctx := context.Background() - tx, _ := pool.Begin(ctx) - _ = sync.LogChange(ctx, tx, sync.EntityLikeTrack, - sync.EncodeLikeID(sync.FormatUUID(u.ID), "11111111-1111-1111-1111-111111111111"), - sync.OpUpsert) - _ = sync.LogChange(ctx, tx, sync.EntityLikeTrack, - sync.EncodeLikeID(sync.FormatUUID(other.ID), "22222222-2222-2222-2222-222222222222"), - sync.OpUpsert) - _ = tx.Commit(ctx) + var artistID string + if err := pool.QueryRow(ctx, + `INSERT INTO artists (name, sort_name) VALUES ('A', 'A') RETURNING id::text`).Scan(&artistID); err != nil { + t.Fatal(err) + } + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if err := sync.LogChange(ctx, tx, sync.EntityArtist, artistID, sync.OpUpsert); err != nil { + t.Fatal(err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatal(err) + } + var last int64 + if err := pool.QueryRow(ctx, `SELECT max(id) FROM library_changes`).Scan(&last); err != nil { + t.Fatal(err) + } - w := callLibrarySync(h, u, "0") - if w.Code != http.StatusOK { - t.Fatalf("status = %d body = %s", w.Code, w.Body.String()) + w := callLibrarySync(h, u, strconv.FormatInt(last+50, 10)) + if w.Code != http.StatusGone || !strings.Contains(w.Body.String(), "cursor_ahead") { + t.Errorf("a cursor past the last change: status = %d body = %s, want 410 cursor_ahead", w.Code, w.Body.String()) } - var body struct { - Upserts map[string][]json.RawMessage `json:"upserts"` + + // The compactor trims every row; the app's cursor is still one this + // server handed out. + if _, err := pool.Exec(ctx, `DELETE FROM library_changes`); err != nil { + t.Fatal(err) } - if err := json.NewDecoder(w.Body).Decode(&body); err != nil { - t.Fatalf("decode: %v", err) - } - got := body.Upserts["like_track"] - if len(got) != 1 { - t.Fatalf("expected 1 like row scoped to alice, got %d", len(got)) + if w := callLibrarySync(h, u, strconv.FormatInt(last, 10)); w.Code != http.StatusNoContent { + t.Errorf("the last cursor after compaction: status = %d body = %s, want 204", w.Code, w.Body.String()) } } -// Pure unit tests below — run even with -short. +// An app is sent back to 0 only when its cursor is below a delete the log has +// dropped, which it may have missed. A cursor at that delete has seen it, and +// one between dropped and kept rows replays what is still there. +func TestLibrarySync_ACursorBelowADroppedDeleteIsReset(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + u := seedUser(t, pool, "alice", "x", false) + ctx := context.Background() -func TestSplitOnce(t *testing.T) { - cases := []struct { - in, sep string - want []string - }{ - {"a:b", ":", []string{"a", "b"}}, - {"a:b:c", ":", []string{"a", "b:c"}}, - {"abc", ":", []string{"abc"}}, - {":x", ":", []string{"", "x"}}, + for i := 0; i < 5; i++ { + if _, err := pool.Exec(ctx, `INSERT INTO library_changes (entity_type, entity_id, op) VALUES ('artist', $1, 'upsert')`, + strconv.Itoa(i)); err != nil { + t.Fatal(err) + } } - for _, c := range cases { - got := splitOnce(c.in, c.sep) - if len(got) != len(c.want) { - t.Errorf("splitOnce(%q,%q): len got=%d want=%d", c.in, c.sep, len(got), len(c.want)) - continue - } - for i := range got { - if got[i] != c.want[i] { - t.Errorf("splitOnce(%q,%q)[%d] = %q want %q", c.in, c.sep, i, got[i], c.want[i]) - } - } + var dropped int64 + if err := pool.QueryRow(ctx, `SELECT min(id) + 2 FROM library_changes`).Scan(&dropped); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE library_changes_trimmed SET through = $1`, dropped); err != nil { + t.Fatal(err) + } + + if w := callLibrarySync(h, u, strconv.FormatInt(dropped-1, 10)); w.Code != http.StatusGone || + !strings.Contains(w.Body.String(), "cursor_too_old") { + t.Errorf("a cursor below the dropped delete: status = %d body = %s, want 410 cursor_too_old", w.Code, w.Body.String()) + } + if w := callLibrarySync(h, u, strconv.FormatInt(dropped, 10)); w.Code != http.StatusOK { + t.Errorf("a cursor at the dropped delete: status = %d body = %s, want 200", w.Code, w.Body.String()) + } + if w := callLibrarySync(h, u, "0"); w.Code != http.StatusOK { + t.Errorf("a sync from 0: status = %d body = %s, want 200", w.Code, w.Body.String()) } } diff --git a/internal/api/library_sync_views.go b/internal/api/library_sync_views.go index f3cbd994..1fe8a29e 100644 --- a/internal/api/library_sync_views.go +++ b/internal/api/library_sync_views.go @@ -17,9 +17,9 @@ package api // failure is a missing value at runtime, not an error at parse time. import ( - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) type artistSyncView struct { @@ -124,29 +124,3 @@ func toTrackSyncView(t dbq.Track, g library.ReplayGain) trackSyncView { TrackPeak: g.TrackPeak, } } - -type playlistSyncView struct { - ID string `json:"id"` - UserID string `json:"user_id"` - Name string `json:"name"` - Description string `json:"description"` - IsPublic bool `json:"is_public"` - CoverPath *string `json:"cover_path"` - TrackCount int32 `json:"track_count"` - DurationSec int32 `json:"duration_sec"` - SystemVariant *string `json:"system_variant"` -} - -func toPlaylistSyncView(p dbq.Playlist) playlistSyncView { - return playlistSyncView{ - ID: syncpkg.FormatUUID(p.ID), - UserID: syncpkg.FormatUUID(p.UserID), - Name: p.Name, - Description: p.Description, - IsPublic: p.IsPublic, - CoverPath: p.CoverPath, - TrackCount: p.TrackCount, - DurationSec: p.DurationSec, - SystemVariant: p.SystemVariant, - } -} diff --git a/internal/api/library_sync_views_test.go b/internal/api/library_sync_views_test.go index 0000d109..781e0ff7 100644 --- a/internal/api/library_sync_views_test.go +++ b/internal/api/library_sync_views_test.go @@ -7,8 +7,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // These tests pin the wire-format keys for /api/library/sync upserts. @@ -41,7 +41,7 @@ func assertJSONKeys(t *testing.T, label string, b []byte, want []string) { } func TestArtistSyncView_WireKeys(t *testing.T) { - a := dbq.Artist{ID: validUUID, Name: "Aphex Twin", SortName: "Aphex Twin"} + a := dbq.Artist{ID: validUUID, Name: "Apex Sibling", SortName: "Apex Sibling"} b, err := json.Marshal(toArtistSyncView(a)) if err != nil { t.Fatal(err) @@ -53,7 +53,7 @@ func TestArtistSyncView_WireKeys(t *testing.T) { } func TestAlbumSyncView_WireKeys(t *testing.T) { - a := dbq.Album{ID: validUUID, ArtistID: validUUID, Title: "Drukqs", SortTitle: "Drukqs"} + a := dbq.Album{ID: validUUID, ArtistID: validUUID, Title: "Drumkits", SortTitle: "Drumkits"} b, err := json.Marshal(toAlbumSyncView(a, library.ReplayGain{})) if err != nil { t.Fatal(err) @@ -67,7 +67,7 @@ func TestAlbumSyncView_WireKeys(t *testing.T) { func TestTrackSyncView_WireKeys(t *testing.T) { tr := dbq.Track{ ID: validUUID, AlbumID: validUUID, ArtistID: validUUID, - Title: "Avril 14th", DurationMs: 121_000, + Title: "Juin 21st", DurationMs: 121_000, FilePath: "x", FileFormat: "flac", } b, err := json.Marshal(toTrackSyncView(tr, library.ReplayGain{})) @@ -123,27 +123,3 @@ func TestSyncViews_CarryReplayGain(t *testing.T) { t.Errorf("unmeasured track_gain = %v (present %v), want an explicit null", v, ok) } } - -func TestPlaylistSyncView_WireKeys(t *testing.T) { - variant := "discover" - p := dbq.Playlist{ - ID: validUUID, UserID: validUUID, Name: "Test", - IsPublic: true, TrackCount: 5, DurationSec: 600, - SystemVariant: &variant, - } - b, err := json.Marshal(toPlaylistSyncView(p)) - if err != nil { - t.Fatal(err) - } - assertJSONKeys(t, "playlist", b, []string{ - "id", "user_id", "name", "description", - "is_public", "cover_path", "track_count", - "duration_sec", "system_variant", - }) - // Sanity: system_variant carries the value, not just present. - var m map[string]any - _ = json.Unmarshal(b, &m) - if got := m["system_variant"]; got != "discover" { - t.Errorf("system_variant: want 'discover', got %v", got) - } -} diff --git a/internal/api/library_test.go b/internal/api/library_test.go index ec40a475..ca65cf08 100644 --- a/internal/api/library_test.go +++ b/internal/api/library_test.go @@ -3,20 +3,14 @@ package api import ( "context" "encoding/json" - "io" - "log/slog" "net/http" "net/http/httptest" "testing" - "time" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/config" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" - "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // newLibraryRouter builds a test-only chi router with the library handlers @@ -37,6 +31,7 @@ func newLibraryRouter(h *handlers) chi.Router { r.Get("/api/artists/{id}", h.handleGetArtist) r.Get("/api/albums/{id}", h.handleGetAlbum) r.Get("/api/albums/{id}/cover", h.handleGetCover) + r.Get("/api/artists/{id}/image", h.handleGetArtistImage) r.Get("/api/tracks/{id}", h.handleGetTrack) r.With(injectFakeUserForTest).Get("/api/tracks/{id}/stream", h.handleGetStream) r.Get("/api/search", h.handleSearch) @@ -58,9 +53,9 @@ func injectFakeUserForTest(next http.Handler) http.Handler { func TestHandleGetTrack_HappyPath(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - artist := seedArtist(t, pool, "Beatles") - album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) - track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) + artist := seedArtist(t, pool, "Copper Lanterns") + album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) + track := seedTrack(t, pool, album.ID, artist.ID, "Somewhere Near", 3, 183_000) req := httptest.NewRequest(http.MethodGet, "/api/tracks/"+uuidToString(track.ID), nil) w := httptest.NewRecorder() @@ -73,7 +68,7 @@ func TestHandleGetTrack_HappyPath(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { t.Fatalf("decode: %v body=%s", err, w.Body.String()) } - if got.Title != "Something" || got.AlbumTitle != "Abbey Road" || got.ArtistName != "Beatles" { + if got.Title != "Somewhere Near" || got.AlbumTitle != "Harbour Street" || got.ArtistName != "Copper Lanterns" { t.Errorf("ref = %+v", got) } if got.TrackNumber != 3 || got.DurationSec != 183 { @@ -85,35 +80,13 @@ func TestHandleGetTrack_HappyPath(t *testing.T) { } } -func TestHandleGetTrack_BadUUID(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/tracks/not-a-uuid", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - -func TestHandleGetTrack_NotFound(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - req := httptest.NewRequest(http.MethodGet, - "/api/tracks/00000000-0000-0000-0000-000000000001", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", w.Code) - } -} - func TestHandleGetAlbum_HappyPath(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - artist := seedArtist(t, pool, "Beatles") - album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) - seedTrack(t, pool, album.ID, artist.ID, "Come Together", 1, 259_000) - seedTrack(t, pool, album.ID, artist.ID, "Something", 2, 183_000) + artist := seedArtist(t, pool, "Copper Lanterns") + album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) + seedTrack(t, pool, album.ID, artist.ID, "Come Along", 1, 259_000) + seedTrack(t, pool, album.ID, artist.ID, "Somewhere Near", 2, 183_000) req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil) w := httptest.NewRecorder() @@ -126,13 +99,13 @@ func TestHandleGetAlbum_HappyPath(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { t.Fatalf("decode: %v body=%s", err, w.Body.String()) } - if got.Title != "Abbey Road" || got.ArtistName != "Beatles" || got.Year != 1969 { + if got.Title != "Harbour Street" || got.ArtistName != "Copper Lanterns" || got.Year != 1969 { t.Errorf("album = %+v", got) } if len(got.Tracks) != 2 { t.Fatalf("tracks len = %d, want 2", len(got.Tracks)) } - if got.Tracks[0].Title != "Come Together" || got.Tracks[1].Title != "Something" { + if got.Tracks[0].Title != "Come Along" || got.Tracks[1].Title != "Somewhere Near" { t.Errorf("tracks = %+v", got.Tracks) } if got.TrackCount != 2 || got.DurationSec != 442 { // 259 + 183 @@ -148,10 +121,38 @@ func TestHandleGetAlbum_HappyPath(t *testing.T) { } } +func TestHandleGetAlbum_EachTrackNamesItsOwnArtist(t *testing.T) { + h, pool := testHandlers(t) + truncateLibrary(t, pool) + various := seedArtist(t, pool, "Various Artists") + first := seedArtist(t, pool, "Harbour Choir") + guest := seedArtist(t, pool, "Ruby Lane") + album := seedAlbum(t, pool, various.ID, "Sunday Morning Static", 2024) + seedTrack(t, pool, album.ID, first.ID, "Low Light", 1, 200_000) + seedTrack(t, pool, album.ID, guest.ID, "Saltlines", 2, 200_000) + + req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil) + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d body = %s", w.Code, w.Body.String()) + } + var got AlbumDetail + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v body=%s", err, w.Body.String()) + } + if got.ArtistName != "Various Artists" { + t.Errorf("album artist = %q, want Various Artists", got.ArtistName) + } + if len(got.Tracks) != 2 || got.Tracks[0].ArtistName != "Harbour Choir" || got.Tracks[1].ArtistName != "Ruby Lane" { + t.Errorf("track artists = %+v, want each track's own artist, not the album's", got.Tracks) + } +} + func TestHandleGetAlbum_NoTracks(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - artist := seedArtist(t, pool, "Beatles") + artist := seedArtist(t, pool, "Copper Lanterns") album := seedAlbum(t, pool, artist.ID, "Empty", 0) req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil) @@ -176,36 +177,14 @@ func TestHandleGetAlbum_NoTracks(t *testing.T) { } } -func TestHandleGetAlbum_BadUUID(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/albums/not-a-uuid", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - -func TestHandleGetAlbum_NotFound(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - req := httptest.NewRequest(http.MethodGet, - "/api/albums/00000000-0000-0000-0000-000000000001", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", w.Code) - } -} - func TestHandleGetArtist_HappyPath(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - artist := seedArtist(t, pool, "Beatles") - album1 := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) - album2 := seedAlbum(t, pool, artist.ID, "Let It Be", 1970) - seedTrack(t, pool, album1.ID, artist.ID, "Something", 3, 183_000) - seedTrack(t, pool, album2.ID, artist.ID, "Get Back", 1, 189_000) + artist := seedArtist(t, pool, "Copper Lanterns") + album1 := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) + album2 := seedAlbum(t, pool, artist.ID, "Let It Ride", 1970) + seedTrack(t, pool, album1.ID, artist.ID, "Somewhere Near", 3, 183_000) + seedTrack(t, pool, album2.ID, artist.ID, "Get Going", 1, 189_000) req := httptest.NewRequest(http.MethodGet, "/api/artists/"+uuidToString(artist.ID), nil) w := httptest.NewRecorder() @@ -218,7 +197,7 @@ func TestHandleGetArtist_HappyPath(t *testing.T) { if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { t.Fatalf("decode: %v body=%s", err, w.Body.String()) } - if got.Name != "Beatles" { + if got.Name != "Copper Lanterns" { t.Errorf("name = %q", got.Name) } if got.AlbumCount != 2 { @@ -227,13 +206,13 @@ func TestHandleGetArtist_HappyPath(t *testing.T) { if len(got.Albums) != 2 { t.Fatalf("albums len = %d, want 2", len(got.Albums)) } - // ListAlbumsByArtist orders by release_date then sort_title; Abbey Road + // ListAlbumsByArtist orders by release_date then sort_title; Harbour Street // (1969) first. - if got.Albums[0].Title != "Abbey Road" { - t.Errorf("first album = %q, want Abbey Road", got.Albums[0].Title) + if got.Albums[0].Title != "Harbour Street" { + t.Errorf("first album = %q, want Harbour Street", got.Albums[0].Title) } for _, a := range got.Albums { - if a.ArtistName != "Beatles" { + if a.ArtistName != "Copper Lanterns" { t.Errorf("album.artist_name = %q", a.ArtistName) } if a.CoverURL == "" { @@ -267,34 +246,12 @@ func TestHandleGetArtist_NoAlbums(t *testing.T) { } } -func TestHandleGetArtist_BadUUID(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/artists/not-a-uuid", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - -func TestHandleGetArtist_NotFound(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - req := httptest.NewRequest(http.MethodGet, - "/api/artists/00000000-0000-0000-0000-000000000001", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", w.Code) - } -} - func TestHandleListArtists_DefaultAlpha(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - seedArtist(t, pool, "Beatles") - seedArtist(t, pool, "ABBA") - seedArtist(t, pool, "Zeppelin") + seedArtist(t, pool, "Copper Lanterns") + seedArtist(t, pool, "ABAB") + seedArtist(t, pool, "Zephyrine") req := httptest.NewRequest(http.MethodGet, "/api/artists", nil) w := httptest.NewRecorder() @@ -316,7 +273,7 @@ func TestHandleListArtists_DefaultAlpha(t *testing.T) { if len(got.Items) != 3 { t.Fatalf("items len = %d", len(got.Items)) } - if got.Items[0].Name != "ABBA" || got.Items[2].Name != "Zeppelin" { + if got.Items[0].Name != "ABAB" || got.Items[2].Name != "Zephyrine" { t.Errorf("alpha order wrong: %q, %q, %q", got.Items[0].Name, got.Items[1].Name, got.Items[2].Name) } } @@ -390,35 +347,6 @@ func TestHandleListArtists_Pagination(t *testing.T) { } } -func TestHandleListArtists_LimitClamped(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - seedArtist(t, pool, "One") - - req := httptest.NewRequest(http.MethodGet, "/api/artists?limit=9999", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - - if w.Code != http.StatusOK { - t.Fatalf("status = %d", w.Code) - } - var got Page[ArtistRef] - _ = json.Unmarshal(w.Body.Bytes(), &got) - if got.Limit != 200 { - t.Errorf("limit = %d, want 200 (max clamp)", got.Limit) - } -} - -func TestHandleListArtists_LimitNonNumeric(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/artists?limit=abc", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - func TestHandleListArtists_AlbumCount(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) @@ -458,52 +386,6 @@ func TestHandleListArtists_EmptyDB(t *testing.T) { } } -// TestRoutesRegisteredInMount verifies the production Mount() wires every -// library route. We hit each path through the real Mount (no RequireUser -// stripped — we expect 401 from the middleware, which is fine — that -// proves the route reached the authenticated group). -func TestRoutesRegisteredInMount(t *testing.T) { - h, _ := testHandlers(t) - r := chi.NewRouter() - w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), - 30*time.Minute, 0.5, 30000) - Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.requests, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, nil) - - paths := []string{ - "/api/artists", - "/api/artists/00000000-0000-0000-0000-000000000001", - "/api/albums/00000000-0000-0000-0000-000000000001", - "/api/albums/00000000-0000-0000-0000-000000000001/cover", - "/api/tracks/00000000-0000-0000-0000-000000000001", - "/api/tracks/00000000-0000-0000-0000-000000000001/stream", - "/api/search?q=x", - // Browse indexes. - "/api/library/genres", - "/api/library/years", - // Admin surfaces for the missing-file lifecycle. Both must - // 401 at the middleware rather than 404 — they live inside the - // admin group, so reaching the auth check is what proves they are - // wired. - "/api/admin/library/missing", - "/api/admin/library/reacquisition", - "/api/admin/library/fingerprints", - "/api/admin/library/fingerprint-settings", - "/api/admin/library/duplicates", - } - for _, p := range paths { - req := httptest.NewRequest(http.MethodGet, p, nil) - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - // Unauthenticated → 401. What we must NOT see is 404 (route missing). - if w.Code == http.StatusNotFound { - t.Errorf("path %s returned 404 — route not registered", p) - } - if w.Code != http.StatusUnauthorized { - t.Errorf("path %s status = %d, want 401 (unauth)", p, w.Code) - } - } -} - func TestGetArtistTracks_HappyPath(t *testing.T) { h, pool := testHandlers(t) user := seedUser(t, pool, "alice", "pw", false) @@ -585,21 +467,3 @@ func TestGetArtistTracks_HonorsQuarantine(t *testing.T) { t.Errorf("len = %d, want 0 (quarantined)", len(got)) } } - -func TestGetArtistTracks_NotFound(t *testing.T) { - h, pool := testHandlers(t) - user := seedUser(t, pool, "alice", "pw", false) - - r := chi.NewRouter() - r.Get("/api/artists/{id}/tracks", h.handleGetArtistTracks) - // Random UUID — no such artist exists. - req := httptest.NewRequest(http.MethodGet, "/api/artists/00000000-0000-0000-0000-000000000000/tracks", nil) - req = withUser(req, user) - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - - if w.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", w.Code) - } - _ = pool -} diff --git a/internal/api/likes.go b/internal/api/likes.go index 955ea06a..abcd44db 100644 --- a/internal/api/likes.go +++ b/internal/api/likes.go @@ -8,24 +8,12 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/eventbus" + "github.com/Fabled-Sword/minstrel/internal/playevents" ) -// logLikeChange writes a library_changes row for a like / unlike. Best- -// effort: a failure here means the next sync may miss the row, but the -// HTTP response still succeeds. Cheap consequence — the user's other -// device sees the like once it manually pulls, or once a later like/unlike -// on the same entity emits a fresh log row. -func (h *handlers) logLikeChange(r *http.Request, et syncpkg.EntityType, userID, entityID pgtype.UUID, op syncpkg.Op) { - if err := syncpkg.LogChange(r.Context(), h.pool, et, - syncpkg.EncodeLikeID(syncpkg.FormatUUID(userID), syncpkg.FormatUUID(entityID)), op); err != nil { - h.logger.Warn("api: LogChange like", "kind", et, "user", userID, "entity", entityID, "err", err) - } -} - type likedIDsResponse struct { TrackIDs []string `json:"track_ids"` AlbumIDs []string `json:"album_ids"` @@ -62,23 +50,18 @@ func (h *handlers) handleLikeTrack(w http.ResponseWriter, r *http.Request) { } // The like is on the song: every copy it reached changes on // the client too. - for _, t := range withTrack(id, liked) { - h.logLikeChange(r, syncpkg.EntityLikeTrack, user.ID, t, syncpkg.OpUpsert) + changed := eventbus.LedBy(id, liked) + for _, t := range changed { h.publishLikeEvent(user.ID, t, "track", true) } - w.WriteHeader(http.StatusNoContent) + writeJSON(w, http.StatusOK, trackLikeView{TrackIDs: uuidsToStrings(changed)}) } -// withTrack is the tracks a like or unlike changed, led by the one asked for, -// which is reported even when it was already in that state. -func withTrack(id pgtype.UUID, changed []pgtype.UUID) []pgtype.UUID { - out := []pgtype.UUID{id} - for _, t := range changed { - if t != id { - out = append(out, t) - } - } - return out +// trackLikeView answers a track like or unlike: the copies of the song it +// changed, the one asked for first, so the client can mark them all at once +// rather than only the copy that was tapped. +type trackLikeView struct { + TrackIDs []string `json:"track_ids"` } func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) { @@ -101,11 +84,11 @@ func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) { h.logger.Error("api: soft-delete contextual_likes", "err", err) // Don't fail the response — soft-delete is best-effort. } - for _, t := range withTrack(id, unliked) { - h.logLikeChange(r, syncpkg.EntityLikeTrack, user.ID, t, syncpkg.OpDelete) + changed := eventbus.LedBy(id, unliked) + for _, t := range changed { h.publishLikeEvent(user.ID, t, "track", false) } - w.WriteHeader(http.StatusNoContent) + writeJSON(w, http.StatusOK, trackLikeView{TrackIDs: uuidsToStrings(changed)}) } func (h *handlers) handleLikeAlbum(w http.ResponseWriter, r *http.Request) { @@ -132,7 +115,6 @@ func (h *handlers) handleLikeAlbum(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("insert failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeAlbum, user.ID, id, syncpkg.OpUpsert) h.publishLikeEvent(user.ID, id, "album", true) w.WriteHeader(http.StatusNoContent) } @@ -151,7 +133,6 @@ func (h *handlers) handleUnlikeAlbum(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("delete failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeAlbum, user.ID, id, syncpkg.OpDelete) h.publishLikeEvent(user.ID, id, "album", false) w.WriteHeader(http.StatusNoContent) } @@ -180,7 +161,6 @@ func (h *handlers) handleLikeArtist(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("insert failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeArtist, user.ID, id, syncpkg.OpUpsert) h.publishLikeEvent(user.ID, id, "artist", true) w.WriteHeader(http.StatusNoContent) } @@ -199,7 +179,6 @@ func (h *handlers) handleUnlikeArtist(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("delete failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeArtist, user.ID, id, syncpkg.OpDelete) h.publishLikeEvent(user.ID, id, "artist", false) w.WriteHeader(http.StatusNoContent) } diff --git a/internal/api/likes_test.go b/internal/api/likes_test.go index d5f44657..95b20eee 100644 --- a/internal/api/likes_test.go +++ b/internal/api/likes_test.go @@ -5,11 +5,12 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "slices" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func callLike(h *handlers, user dbq.User, method, path string) *httptest.ResponseRecorder { @@ -37,60 +38,33 @@ func likesRouter(h *handlers) http.Handler { return r } -func TestLikeTrack_Idempotent(t *testing.T) { +// A like is on the song, so its answer names every copy it reached, and an +// unlike every copy it cleared, the tapped one first. +func TestLikeTrack_AnswersEveryCopyOfTheSong(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "Beatles") - album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) - track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) - - w := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)) - if w.Code != http.StatusNoContent { - t.Fatalf("first like: status = %d body=%s", w.Code, w.Body.String()) + artist := seedArtist(t, pool, "Copper Lanterns") + album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) + best := seedAlbum(t, pool, artist.ID, "Best Of", 1975) + first := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) + // seedTrack files each title at its own path, so the compilation copy + // gets a title of its own; song_id is what makes it the same song. + copied := seedTrack(t, pool, best.ID, artist.ID, "Something (Best Of)", 1, 183_000) + if _, err := pool.Exec(context.Background(), "UPDATE tracks SET song_id = $1 WHERE id = $2", first.ID, copied.ID); err != nil { + t.Fatal(err) } - w = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)) - if w.Code != http.StatusNoContent { - t.Errorf("second like (idempotent): status = %d", w.Code) - } - var count int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM general_likes WHERE user_id=$1", user.ID).Scan(&count) - if count != 1 { - t.Errorf("rows = %d, want 1", count) - } -} + want := []string{uuidToString(copied.ID), uuidToString(first.ID)} -func TestLikeTrack_BadUUIDIs400(t *testing.T) { - h, pool := testHandlers(t) - user := seedUser(t, pool, "alice", "x", false) - w := callLike(h, user, http.MethodPost, "/api/likes/tracks/not-a-uuid") - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d", w.Code) - } -} - -func TestLikeTrack_UnknownTrackIs404(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - w := callLike(h, user, http.MethodPost, "/api/likes/tracks/00000000-0000-0000-0000-000000000000") - if w.Code != http.StatusNotFound { - t.Errorf("status = %d", w.Code) - } -} - -func TestUnlikeTrack_IdempotentEvenWhenAbsent(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "Beatles") - album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) - track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) - - w := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(track.ID)) - if w.Code != http.StatusNoContent { - t.Errorf("status = %d", w.Code) + for _, method := range []string{http.MethodPost, http.MethodDelete} { + w := callLike(h, user, method, "/api/likes/tracks/"+uuidToString(copied.ID)) + var got trackLikeView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("%s: decode %q: %v", method, w.Body.String(), err) + } + if !slices.Equal(got.TrackIDs, want) { + t.Errorf("%s: track_ids = %v, want %v", method, got.TrackIDs, want) + } } } @@ -217,7 +191,7 @@ func TestLikeTrack_DuringOpenPlayEvent_WritesContextualLike(t *testing.T) { // Like the OTHER track. With an open play_event for `playing`, // the contextual_likes row should reference `other` and the playing // track's session vector. - if r := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)); r.Code != http.StatusNoContent { + if r := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)); r.Code != http.StatusOK { t.Fatalf("like: %d", r.Code) } var count int @@ -236,7 +210,7 @@ func TestLikeTrack_NoOpenPlayEvent_NoContextualLike(t *testing.T) { album := seedAlbum(t, pool, artist.ID, "X", 1990) track := seedTrack(t, pool, album.ID, artist.ID, "T", 1, 100_000) - if r := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)); r.Code != http.StatusNoContent { + if r := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)); r.Code != http.StatusOK { t.Fatalf("like: %d", r.Code) } var count int @@ -247,86 +221,52 @@ func TestLikeTrack_NoOpenPlayEvent_NoContextualLike(t *testing.T) { } } -func TestLikeTrack_RepeatedLike_NoDuplicate(t *testing.T) { +// Liking and unliking a track can be repeated safely. Unliking a track that +// was never liked is fine. A second like adds no row. An unlike removes the +// like and closes, but keeps, the contextual like written during the open +// play. Liking again opens a new contextual like, so the history grows. +func TestLikeTrack_LikeAndUnlikeRepeatSafelyAndKeepTheHistory(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) user := seedUser(t, pool, "alice", "x", false) artist := seedArtist(t, pool, "X") album := seedAlbum(t, pool, artist.ID, "X", 1990) playing := seedTrack(t, pool, album.ID, artist.ID, "Playing", 1, 100_000) - other := seedTrack(t, pool, album.ID, artist.ID, "Other", 2, 100_000) + liked := seedTrack(t, pool, album.ID, artist.ID, "Liked", 2, 100_000) + path := "/api/likes/tracks/" + uuidToString(liked.ID) - // Open play. + count := func(query string) int { + t.Helper() + var n int + if err := pool.QueryRow(context.Background(), query, user.ID, liked.ID).Scan(&n); err != nil { + t.Fatalf("%s: %v", query, err) + } + return n + } + const ( + general = "SELECT count(*) FROM general_likes WHERE user_id=$1 AND track_id=$2" + ctxAll = "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2" + ctxOpen = "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2 AND deleted_at IS NULL" + ) _ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`)) - // First like — captures. - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - // Second like — :execrows=0, no contextual write. - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - var count int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&count) - if count != 1 { - t.Errorf("contextual_likes count = %d, want 1 (no duplicate from idempotent re-like)", count) - } -} - -func TestUnlikeTrack_SoftDeletesContextualLikes(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "X") - album := seedAlbum(t, pool, artist.ID, "X", 1990) - playing := seedTrack(t, pool, album.ID, artist.ID, "P", 1, 100_000) - other := seedTrack(t, pool, album.ID, artist.ID, "O", 2, 100_000) - - _ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`)) - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - if r := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(other.ID)); r.Code != http.StatusNoContent { - t.Fatalf("unlike: %d", r.Code) - } - // general_likes deleted. - var glCount int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM general_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&glCount) - if glCount != 0 { - t.Errorf("general_likes count = %d, want 0", glCount) - } - // contextual_likes row exists but deleted_at is set. - var deletedAtValid bool - _ = pool.QueryRow(context.Background(), - "SELECT deleted_at IS NOT NULL FROM contextual_likes WHERE user_id=$1 AND track_id=$2 LIMIT 1", - user.ID, other.ID).Scan(&deletedAtValid) - if !deletedAtValid { - t.Errorf("deleted_at not set after unlike") - } -} - -func TestLikeUnlikeRelike_HistoryAccumulates(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "X") - album := seedAlbum(t, pool, artist.ID, "X", 1990) - playing := seedTrack(t, pool, album.ID, artist.ID, "P", 1, 100_000) - other := seedTrack(t, pool, album.ID, artist.ID, "O", 2, 100_000) - - _ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`)) - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - _ = callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(other.ID)) - // Re-like in same session — new row should be inserted. - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - - var total, active int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&total) - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2 AND deleted_at IS NULL", - user.ID, other.ID).Scan(&active) - if total != 2 { - t.Errorf("total = %d, want 2 (history accumulates)", total) - } - if active != 1 { - t.Errorf("active = %d, want 1", active) + for _, step := range []struct { + method string + general, ctxAll, ctxOpen int + }{ + {http.MethodDelete, 0, 0, 0}, + {http.MethodPost, 1, 1, 1}, + {http.MethodPost, 1, 1, 1}, + {http.MethodDelete, 0, 1, 0}, + {http.MethodPost, 1, 2, 1}, + } { + if w := callLike(h, user, step.method, path); w.Code != http.StatusOK { + t.Fatalf("%s: status %d body=%s", step.method, w.Code, w.Body.String()) + } + g, a, o := count(general), count(ctxAll), count(ctxOpen) + if g != step.general || a != step.ctxAll || o != step.ctxOpen { + t.Fatalf("after %s: likes=%d contextual=%d open=%d, want %d %d %d", + step.method, g, a, o, step.general, step.ctxAll, step.ctxOpen) + } } } diff --git a/internal/api/listenbrainz.go b/internal/api/listenbrainz.go index 571b5a71..8ab40930 100644 --- a/internal/api/listenbrainz.go +++ b/internal/api/listenbrainz.go @@ -9,8 +9,9 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/secret" ) // LBStatus is the GET response body and the PUT response body. Token is @@ -53,10 +54,11 @@ func (h *handlers) handlePutListenBrainz(w http.ResponseWriter, r *http.Request) q := dbq.New(h.pool) if body.Token != nil { - t := *body.Token - var tokenPtr *string - if t != "" { - tokenPtr = &t + tokenPtr, err := secret.SealPtr(secret.ListenBrainzToken.Purpose(), user.ID.String(), body.Token) + if err != nil { + h.logger.Error("api: seal listenbrainz token", "err", err) + writeErr(w, apierror.InternalMsg("update failed", err)) + return } if err := q.SetListenBrainzToken(r.Context(), dbq.SetListenBrainzTokenParams{ ID: user.ID, ListenbrainzToken: tokenPtr, diff --git a/internal/api/listenbrainz_test.go b/internal/api/listenbrainz_test.go index 5029fbb6..6d8d9961 100644 --- a/internal/api/listenbrainz_test.go +++ b/internal/api/listenbrainz_test.go @@ -8,8 +8,8 @@ import ( "net/http/httptest" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) type lbStatusJSON struct { diff --git a/internal/api/main_test.go b/internal/api/main_test.go new file mode 100644 index 00000000..8cc0cd7b --- /dev/null +++ b/internal/api/main_test.go @@ -0,0 +1,26 @@ +package api + +import ( + "os" + "testing" + + "golang.org/x/crypto/bcrypt" +) + +// serverPasswordCost is the cost the server hashes stored passwords at, +// taken before TestMain lowers it. +var serverPasswordCost = passwordCost + +// The tests hash passwords at bcrypt's lowest cost: what they check is which +// password is stored and who is signed out, not how slow a guess is. +func TestMain(m *testing.M) { + passwordCost = bcrypt.MinCost + os.Exit(m.Run()) +} + +// Lowering the cost for the tests must not hide a weaker one in the server. +func TestPasswordCost_StoredPasswordsUseAtLeastBcryptsDefault(t *testing.T) { + if serverPasswordCost < bcrypt.DefaultCost { + t.Errorf("passwords are stored at bcrypt cost %d, want at least %d", serverPasswordCost, bcrypt.DefaultCost) + } +} diff --git a/internal/api/me.go b/internal/api/me.go index 231626ac..df5e28dd 100644 --- a/internal/api/me.go +++ b/internal/api/me.go @@ -4,8 +4,8 @@ import ( "errors" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" ) // handleGetMe returns the authenticated user's profile shape — id, diff --git a/internal/api/me_history.go b/internal/api/me_history.go index 0520a386..38efa8fa 100644 --- a/internal/api/me_history.go +++ b/internal/api/me_history.go @@ -4,8 +4,8 @@ import ( "encoding/json" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // handleGetMyHistory implements GET /api/me/history?limit=&offset=. diff --git a/internal/api/me_history_test.go b/internal/api/me_history_test.go index 57bcfeb7..65c7defa 100644 --- a/internal/api/me_history_test.go +++ b/internal/api/me_history_test.go @@ -12,7 +12,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // newHistoryRouter mounts ONLY /api/me/history, injecting the user directly diff --git a/internal/api/me_normalization.go b/internal/api/me_normalization.go index 0b1f9061..a0a4434f 100644 --- a/internal/api/me_normalization.go +++ b/internal/api/me_normalization.go @@ -5,9 +5,9 @@ import ( "errors" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // GET /api/me/normalization returns the caller's loudness-normalization diff --git a/internal/api/me_normalization_test.go b/internal/api/me_normalization_test.go index 0058dfab..1fe010e1 100644 --- a/internal/api/me_normalization_test.go +++ b/internal/api/me_normalization_test.go @@ -9,7 +9,7 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/library" ) func TestMyNormalization_GetPut(t *testing.T) { diff --git a/internal/api/me_notifications.go b/internal/api/me_notifications.go index 48d078e5..77f4c0ab 100644 --- a/internal/api/me_notifications.go +++ b/internal/api/me_notifications.go @@ -12,10 +12,10 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) // The notifications inbox. Rows are written by internal/notifications; diff --git a/internal/api/me_notifications_test.go b/internal/api/me_notifications_test.go index 1839b3ab..e9f2d200 100644 --- a/internal/api/me_notifications_test.go +++ b/internal/api/me_notifications_test.go @@ -12,8 +12,8 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) func notificationsRouter(h *handlers) chi.Router { @@ -44,8 +44,9 @@ func notifyN(t *testing.T, pool *pgxpool.Pool, user dbq.User, n int) { t.Helper() nt := notifications.New(pool, nil, nil) for i := 0; i < n; i++ { - if err := nt.Notify(context.Background(), notifications.KindRequestCompleted, - notifications.ToUser(user.ID), notifications.Payload{Name: "Album", AlbumID: "al-1"}.Map()); err != nil { + p := notifications.Payload{Count: 1, Albums: []notifications.Arrival{{Artist: "Artist", Title: "Album", AlbumID: "al-1"}}} + if err := nt.Notify(context.Background(), notifications.KindNewMusic, + notifications.ToUser(user.ID), p.Map()); err != nil { t.Fatalf("notify: %v", err) } } @@ -67,7 +68,7 @@ func TestMyNotifications_ListRendersPagesAndCounts(t *testing.T) { t.Fatalf("first page = %d items, unread %d, next %q; want 2, 3, a cursor", len(page.Items), page.UnreadCount, page.NextBefore) } first := page.Items[0] - if first.Title != "Now in your library" || first.Body != "Album has arrived." || first.Link != "/albums/al-1" || first.ReadAt != nil { + if first.Title != "New album" || first.Body != "Artist – Album is in the library." || first.Link != "/albums/al-1" || first.ReadAt != nil { t.Errorf("rendered item = %+v", first) } @@ -199,27 +200,24 @@ func TestMyNotificationSettings_DefaultsRoundTripAndAdminKinds(t *testing.T) { } // A partial change touches only what it names. - body := `{"kinds":[{"kind":"request_completed","email":false}]}` + body := `{"kinds":[{"kind":"new_music","phone":true}]}` if code := callAs(t, r, user, http.MethodPut, "/api/me/notification-settings", body, &s); code != http.StatusOK { t.Fatalf("put = %d", code) } for _, k := range s.Kinds { - if k.Kind == notifications.KindRequestCompleted && (k.Email || !k.Inbox || !k.Phone) { - t.Errorf("after PUT request_completed = %+v, want inbox+phone on, email off", k) - } - if k.Kind == notifications.KindRequestApproved && !k.Email { - t.Errorf("an untouched kind changed: %+v", k) + if k.Kind == notifications.KindNewMusic && (!k.Phone || !k.Inbox || !k.Email) { + t.Errorf("after PUT new_music = %+v, want phone on and inbox, email left on", k) } } // A non-admin can't set an admin kind; nothing in the batch is applied. - bad := `{"kinds":[{"kind":"request_approved","inbox":false},{"kind":"tracks_missing","inbox":false}]}` + bad := `{"kinds":[{"kind":"new_music","inbox":false},{"kind":"tracks_missing","inbox":false}]}` if code := callAs(t, r, user, http.MethodPut, "/api/me/notification-settings", bad, nil); code != http.StatusBadRequest { t.Errorf("non-admin setting an admin kind = %d, want 400", code) } callAs(t, r, user, http.MethodGet, "/api/me/notification-settings", "", &s) for _, k := range s.Kinds { - if k.Kind == notifications.KindRequestApproved && !k.Inbox { + if k.Kind == notifications.KindNewMusic && !k.Inbox { t.Error("a refused batch was partly applied") } } diff --git a/internal/api/me_password.go b/internal/api/me_password.go index 22c9afe1..ae6c03a9 100644 --- a/internal/api/me_password.go +++ b/internal/api/me_password.go @@ -6,15 +6,20 @@ import ( "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) type changePasswordReq struct { CurrentPassword string `json:"current_password"` NewPassword string `json:"new_password"` + // SignOutSubsonic also ends the account's Subsonic apps' access, for + // someone changing a password they think another person knows. It is a + // choice here, unlike on a reset, because it signs out the owner's own + // apps too: they make a new key or Subsonic password in Settings. + SignOutSubsonic bool `json:"sign_out_subsonic"` } // handleChangePassword implements PUT /api/me/password. Self-service: @@ -30,8 +35,7 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request) writeErr(w, apierror.BadRequest("invalid_body", "")) return } - if len(req.NewPassword) < minPasswordLength { - writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars")) + if !checkNewPassword(w, req.NewPassword) { return } @@ -47,7 +51,7 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request) return } - hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) + hash, err := hashPassword(req.NewPassword) if err != nil { h.logger.Error("change password: hash failed", "err", err) writeErr(w, apierror.Internal(err)) @@ -75,7 +79,17 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request) } } - audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionPasswordChangeSelf, nil) + var auditMeta map[string]any + if req.SignOutSubsonic { + if err := h.signOutSubsonicApps(r.Context(), user.ID); err != nil { + h.logger.Error("change password: sign out subsonic apps failed", "err", err) + writeErr(w, apierror.Internal(err)) + return + } + auditMeta = map[string]any{"signed_out_subsonic": true} + } + + audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionPasswordChangeSelf, auditMeta) w.WriteHeader(http.StatusNoContent) } diff --git a/internal/api/me_password_test.go b/internal/api/me_password_test.go index 2723b030..eedf19dc 100644 --- a/internal/api/me_password_test.go +++ b/internal/api/me_password_test.go @@ -5,7 +5,6 @@ import ( "context" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -19,9 +18,6 @@ func newMePasswordRouter(h *handlers) chi.Router { } func TestChangePassword_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "chpw1", "oldpassword1", false) @@ -47,9 +43,6 @@ func TestChangePassword_Happy(t *testing.T) { } func TestChangePassword_WrongCurrent_401(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "chpw2", "correctpw1", false) @@ -65,9 +58,6 @@ func TestChangePassword_WrongCurrent_401(t *testing.T) { } func TestChangePassword_TooShort_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "chpw3", "somepassword1", false) @@ -81,3 +71,30 @@ func TestChangePassword_TooShort_400(t *testing.T) { t.Errorf("status = %d, want 400 (password_too_short)", rec.Code) } } + +// A change keeps Subsonic apps signed in unless the person asks for them to +// be signed out as well. +func TestChangePassword_SignsOutSubsonicAppsOnlyWhenAsked(t *testing.T) { + h, pool := testHandlers(t) + user := seedUser(t, pool, "chpwsub", "oldpassword1", false) + giveSubsonicPassword(t, h, user) + before, _ := subsonicCredentials(t, h, user) + + change := func(body string) { + t.Helper() + req := httptest.NewRequest(http.MethodPut, "/api/me/password", bytes.NewReader([]byte(body))) + rec := httptest.NewRecorder() + newMePasswordRouter(h).ServeHTTP(rec, withUser(req, user)) + if rec.Code != http.StatusNoContent { + t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String()) + } + } + + change(`{"current_password":"oldpassword1","new_password":"newpassword1"}`) + if after, hasPassword := subsonicCredentials(t, h, user); after != before || !hasPassword { + t.Fatal("a plain password change signed out Subsonic apps") + } + + change(`{"current_password":"newpassword1","new_password":"newpassword2","sign_out_subsonic":true}`) + assertSubsonicSignedOut(t, h, user, before) +} diff --git a/internal/api/me_profile.go b/internal/api/me_profile.go index aa7e021b..b3dbf53b 100644 --- a/internal/api/me_profile.go +++ b/internal/api/me_profile.go @@ -2,16 +2,13 @@ package api import ( "encoding/json" - "errors" "net/http" "regexp" "strings" - "github.com/jackc/pgerrcode" - "github.com/jackc/pgx/v5/pgconn" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // emailRe is a simple format check. We don't try to validate @@ -109,9 +106,8 @@ func (h *handlers) handleUpdateMyProfile(w http.ResponseWriter, r *http.Request) Email: email, }) if err != nil { - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation { - writeErr(w, apierror.Conflict("email_taken", "")) + if db.IsUniqueViolation(err) { + writeErr(w, apierror.Conflict("email_taken", "email is already in use")) return } h.logger.Error("update profile: update failed", "err", err) diff --git a/internal/api/me_profile_test.go b/internal/api/me_profile_test.go index b2f26330..88517dab 100644 --- a/internal/api/me_profile_test.go +++ b/internal/api/me_profile_test.go @@ -3,10 +3,8 @@ package api import ( "bytes" "context" - "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -18,187 +16,51 @@ func newMeProfileRouter(h *handlers) chi.Router { return r } -func TestUpdateProfile_DisplayNameOnly(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } +// A profile update changes only the fields it sends: an empty display name +// clears it, an email is stored lowercased, and an invalid email or one +// another account holds is refused with the profile unchanged. +func TestUpdateProfile_ChangesOnlyTheFieldsSent(t *testing.T) { h, pool := testHandlers(t) - user := seedUser(t, pool, "prof1", "pw", false) - - body := `{"display_name":"My Name"}` - req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body))) - req = withUser(req, user) - rec := httptest.NewRecorder() - newMeProfileRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - var resp meProfileResp - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.DisplayName == nil || *resp.DisplayName != "My Name" { - t.Errorf("display_name = %v, want 'My Name'", resp.DisplayName) - } -} - -func TestUpdateProfile_EmailOnly_Lowercased(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - user := seedUser(t, pool, "prof2", "pw", false) - - body := `{"email":"User@Example.COM"}` - req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body))) - req = withUser(req, user) - rec := httptest.NewRecorder() - newMeProfileRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - - // Verify DB row is lowercased. - var email *string - if err := pool.QueryRow(context.Background(), - "SELECT email FROM users WHERE id = $1", user.ID).Scan(&email); err != nil { - t.Fatalf("read email: %v", err) - } - if email == nil || *email != "user@example.com" { - t.Errorf("DB email = %v, want 'user@example.com'", email) - } -} - -func TestUpdateProfile_BothFields(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - user := seedUser(t, pool, "prof3", "pw", false) - - body := `{"display_name":"Both Fields","email":"both@example.com"}` - req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body))) - req = withUser(req, user) - rec := httptest.NewRecorder() - newMeProfileRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - var resp meProfileResp - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.DisplayName == nil || *resp.DisplayName != "Both Fields" { - t.Errorf("display_name = %v, want 'Both Fields'", resp.DisplayName) - } - if resp.Email == nil || *resp.Email != "both@example.com" { - t.Errorf("email = %v, want 'both@example.com'", resp.Email) - } -} - -func TestUpdateProfile_EmptyBody_NoOp(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - user := seedUser(t, pool, "prof4", "pw", false) - - body := `{}` - req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body))) - req = withUser(req, user) - rec := httptest.NewRecorder() - newMeProfileRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200 (no-op); body=%s", rec.Code, rec.Body.String()) - } - var resp meProfileResp - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - // Neither field should have been set (seeded without them). - if resp.DisplayName != nil { - t.Errorf("display_name = %v, want nil (no-op)", resp.DisplayName) - } -} - -func TestUpdateProfile_InvalidEmail_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - user := seedUser(t, pool, "prof5", "pw", false) - - body := `{"email":"notanemail"}` - req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body))) - req = withUser(req, user) - rec := httptest.NewRecorder() - newMeProfileRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400 (email_invalid)", rec.Code) - } -} - -func TestUpdateProfile_EmailTaken_409(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - other := seedUser(t, pool, "prof6other", "pw", false) - user := seedUser(t, pool, "prof6user", "pw", false) - - // Give the other user an email directly. + other := seedUser(t, pool, "profother", "pw", false) if _, err := pool.Exec(context.Background(), "UPDATE users SET email = 'taken@example.com' WHERE id = $1", other.ID); err != nil { - t.Fatalf("setup email: %v", err) + t.Fatalf("give the other account an email: %v", err) } + user := seedUser(t, pool, "prof", "pw", false) - body := `{"email":"taken@example.com"}` - req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body))) - req = withUser(req, user) - rec := httptest.NewRecorder() - newMeProfileRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusConflict { - t.Errorf("status = %d, want 409 (email_taken)", rec.Code) + str := func(s string) *string { return &s } + for _, step := range []struct { + body string + status int + wantName, wantMail *string // the stored profile after the request + }{ + {`{"display_name":"My Name"}`, http.StatusOK, str("My Name"), nil}, + {`{"email":"User@Example.COM"}`, http.StatusOK, str("My Name"), str("user@example.com")}, + {`{}`, http.StatusOK, str("My Name"), str("user@example.com")}, + {`{"display_name":"Both","email":"both@example.com"}`, http.StatusOK, str("Both"), str("both@example.com")}, + {`{"display_name":""}`, http.StatusOK, nil, str("both@example.com")}, + {`{"email":"notanemail"}`, http.StatusBadRequest, nil, str("both@example.com")}, + {`{"email":"taken@example.com"}`, http.StatusConflict, nil, str("both@example.com")}, + } { + req := withUser(httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(step.body))), user) + rec := httptest.NewRecorder() + newMeProfileRouter(h).ServeHTTP(rec, req) + if rec.Code != step.status { + t.Fatalf("%s: status %d, want %d; body=%s", step.body, rec.Code, step.status, rec.Body.String()) + } + var name, mail *string + if err := pool.QueryRow(context.Background(), + "SELECT display_name, email FROM users WHERE id = $1", user.ID).Scan(&name, &mail); err != nil { + t.Fatalf("read profile: %v", err) + } + if !sameOptional(name, step.wantName) || !sameOptional(mail, step.wantMail) { + t.Errorf("after %s: profile = (%q, %q), want (%q, %q)", + step.body, deref(name), deref(mail), deref(step.wantName), deref(step.wantMail)) + } } } -func TestUpdateProfile_ClearDisplayName(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - user := seedUser(t, pool, "prof7", "pw", false) - - // First, set a display name. - if _, err := pool.Exec(context.Background(), - "UPDATE users SET display_name = 'Will Be Cleared' WHERE id = $1", user.ID); err != nil { - t.Fatalf("setup display_name: %v", err) - } - - // Clear it by sending empty string. - body := `{"display_name":""}` - req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body))) - req = withUser(req, user) - rec := httptest.NewRecorder() - newMeProfileRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - - // DB should now have NULL display_name. - var dn *string - if err := pool.QueryRow(context.Background(), - "SELECT display_name FROM users WHERE id = $1", user.ID).Scan(&dn); err != nil { - t.Fatalf("read display_name: %v", err) - } - if dn != nil { - t.Errorf("display_name = %v, want nil (cleared)", dn) - } +// sameOptional reports whether two optional strings are both unset or equal. +func sameOptional(a, b *string) bool { + return (a == nil && b == nil) || (a != nil && b != nil && *a == *b) } diff --git a/internal/api/me_recommendation_metrics.go b/internal/api/me_recommendation_metrics.go index ae2a796e..ef3eee3d 100644 --- a/internal/api/me_recommendation_metrics.go +++ b/internal/api/me_recommendation_metrics.go @@ -6,8 +6,8 @@ import ( "strconv" "strings" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) const ( @@ -66,8 +66,9 @@ type surfaceGroup struct { type recommendationMetricsResp struct { WindowDays int `json:"window_days"` // Baseline is the control group: plays the user picked manually - // (source IS NULL). Surfaces are judged as deltas against it; nil - // when the window holds no manual plays. + // (isManualSource: no source, search or the Liked list). Surfaces are + // judged as deltas against it; nil when the window holds no manual + // plays. Baseline *surfaceMetric `json:"baseline"` Groups []surfaceGroup `json:"groups"` } @@ -79,6 +80,19 @@ type recFamily struct { intent string } +// isManualSource reports whether a play's source marks a manual pick: the +// listener chose the song, with no recommendation between them and it. These +// make the baseline every surface is judged against. +// +// The play-source vocabulary both clients send is: a system mix's variant +// ("for_you", "discover", …), "radio:", "album:", +// "artist:", "artist-top:", "home:
", "offline:", +// "history", "library_shuffle", "search", "liked", or none. The web keeps +// it in web/src/lib/player/playSource.ts. +func isManualSource(src string) bool { + return src == "" || src == "search" || src == "liked" +} + // bucketRecSource maps a raw client-stamped source string to its stable // family. One-off sources (album:, radio:) collapse into // their family so the table stays readable at any library size. @@ -88,6 +102,8 @@ func bucketRecSource(src string) recFamily { return recFamily{"for_you", "For You", intentGoTo} case src == "songs_like_artist": return recFamily{"songs_like_artist", "Songs like…", intentGoTo} + case src == "genre_mix": + return recFamily{"genre_mix", "Genre mixes", intentGoTo} case src == "radio" || strings.HasPrefix(src, "radio:"): return recFamily{"radio", "Radio", intentGoTo} case src == "discover": @@ -104,8 +120,12 @@ func bucketRecSource(src string) recFamily { return recFamily{"first_listens", "First listens", intentDiscovery} case strings.HasPrefix(src, "album:"): return recFamily{"direct_album", "Album plays", intentDirect} - case strings.HasPrefix(src, "artist:"): + case strings.HasPrefix(src, "artist:") || strings.HasPrefix(src, "artist-top:"): return recFamily{"direct_artist", "Artist plays", intentDirect} + case src == "library_shuffle": + // Shuffling the whole library: the random baseline the + // recommendations exist to beat, shown beside them. + return recFamily{"library_shuffle", "Library shuffle", intentDirect} case strings.HasPrefix(src, "offline:"): return recFamily{"offline", "Offline pools", intentDirect} case strings.HasPrefix(src, "home:"): @@ -211,7 +231,7 @@ func (h *handlers) handleGetRecommendationMetrics(w http.ResponseWriter, r *http } // pickKindLabels is the display vocabulary for play_events.pick_kind -// values (mirrors the CHECK in migration 0041). Every system mix that +// values (mirrors the CHECK on play_events.pick_kind). Every system mix that // stamps provenance gets its breakdown from this one map — adding a // stamping mix needs no metrics change. var pickKindLabels = map[string]string{ @@ -285,7 +305,7 @@ func bucketMetricsResponse( families := map[string]*familyAccum{} picks := map[string]map[string]*familyAccum{} for _, row := range rows { - if row.Source == nil || *row.Source == "" { + if row.Source == nil || isManualSource(*row.Source) { baseline.add(row) continue } diff --git a/internal/api/me_recommendation_metrics_test.go b/internal/api/me_recommendation_metrics_test.go index 4199fb5b..f96a5629 100644 --- a/internal/api/me_recommendation_metrics_test.go +++ b/internal/api/me_recommendation_metrics_test.go @@ -5,14 +5,13 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "time" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func newMetricsRouter(h *handlers) chi.Router { @@ -39,16 +38,6 @@ func seedSourcedPlay( } } -func TestRecommendationMetrics_NoSession401(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/me/recommendation-metrics", nil) - rec := httptest.NewRecorder() - newMetricsRouter(h).ServeHTTP(rec, req) - if rec.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", rec.Code) - } -} - // findSurface returns the named family from any group, or nil. func findSurface(resp recommendationMetricsResp, key string) *surfaceMetric { for _, g := range resp.Groups { @@ -211,9 +200,6 @@ func TestBucketMetricsResponse_DiscoverBucketBreakdown(t *testing.T) { } func TestRecommendationMetrics_BucketsWithBaseline(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "metrics", "pw", false) artist := seedArtist(t, pool, "MetricArtist") @@ -279,3 +265,30 @@ func TestRecommendationMetrics_BucketsWithBaseline(t *testing.T) { t.Errorf("radio family = %+v, want plays=1 (collapsed from radio:)", radio) } } + +// Both clients' sources land on the same surfaces: search and Liked-list +// plays are manual picks in the baseline, library shuffle is its own row, +// and an artist's top songs count as artist plays, not Other. +func TestBucketMetricsResponse_SharedSourceVocabulary(t *testing.T) { + src := func(s string) *string { return &s } + rows := []dbq.RecommendationSourceMetricsForUserRow{ + {Source: nil, Plays: 10, Skips: 1, CompletionN: 10, AvgCompletion: 0.9}, + {Source: src("search"), Plays: 5, Skips: 1, CompletionN: 5, AvgCompletion: 0.8}, + {Source: src("liked"), Plays: 5, Skips: 0, CompletionN: 5, AvgCompletion: 1}, + {Source: src("library_shuffle"), Plays: 4, Skips: 2, CompletionN: 4, AvgCompletion: 0.5}, + {Source: src("artist-top:abcd"), Plays: 3, Skips: 0, CompletionN: 3, AvgCompletion: 1}, + } + resp := bucketMetricsResponse(recMetricsDefaultDays, rows) + if resp.Baseline == nil || resp.Baseline.Plays != 20 { + t.Fatalf("baseline = %+v, want the 20 manual, search and liked plays", resp.Baseline) + } + if s := findSurface(resp, "library_shuffle"); s == nil || s.Plays != 4 { + t.Errorf("library_shuffle = %+v, want its own row of 4", s) + } + if s := findSurface(resp, "direct_artist"); s == nil || s.Plays != 3 { + t.Errorf("direct_artist = %+v, want the 3 top-song plays", s) + } + if s := findSurface(resp, "other"); s != nil { + t.Errorf("other = %+v, want none: every source here has a surface", s) + } +} diff --git a/internal/api/me_sessions.go b/internal/api/me_sessions.go index e2f2f508..be37c25f 100644 --- a/internal/api/me_sessions.go +++ b/internal/api/me_sessions.go @@ -7,10 +7,10 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // errNoCurrentSession means the request authenticated but the middleware diff --git a/internal/api/me_sessions_test.go b/internal/api/me_sessions_test.go index 5473e608..58936b0b 100644 --- a/internal/api/me_sessions_test.go +++ b/internal/api/me_sessions_test.go @@ -11,8 +11,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // seedSession inserts a session for userID and returns its id. diff --git a/internal/api/me_subsonic_password.go b/internal/api/me_subsonic_password.go index 6a0009fe..42bd8c84 100644 --- a/internal/api/me_subsonic_password.go +++ b/internal/api/me_subsonic_password.go @@ -1,18 +1,24 @@ package api import ( + "context" "crypto/rand" "encoding/base64" "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/secret" ) // The Subsonic password is for clients that sign in with Subsonic's t/s // scheme (md5 of the password plus a salt). Checking that needs the password -// itself, so it is stored readable (migration 0003). That is why Minstrel +// itself, so it is stored readable (users.subsonic_password). That is why Minstrel // generates it rather than letting the user choose one: a generated value // can never be a login password reused from somewhere else, so a leaked // users table gives up access to this server's /rest API and nothing more. @@ -51,9 +57,15 @@ func (h *handlers) handleGenerateMySubsonicPassword(w http.ResponseWriter, r *ht return } pw := base64.RawURLEncoding.EncodeToString(b) + sealed, err := secret.Seal(secret.SubsonicPassword.Purpose(), user.ID.String(), pw) + if err != nil { + h.logger.Error("generate subsonic password: seal failed", "err", err) + writeErr(w, apierror.Internal(err)) + return + } if err := dbq.New(h.pool).SetSubsonicPassword(r.Context(), dbq.SetSubsonicPasswordParams{ ID: user.ID, - SubsonicPassword: &pw, + SubsonicPassword: &sealed, }); err != nil { h.logger.Error("generate subsonic password: update failed", "err", err) writeErr(w, apierror.Internal(err)) @@ -81,3 +93,27 @@ func (h *handlers) handleClearMySubsonicPassword(w http.ResponseWriter, r *http. audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionSubsonicPasswordClear, nil) w.WriteHeader(http.StatusNoContent) } + +// signOutSubsonicApps ends every Subsonic app's access to the account: the +// API key is replaced with one nobody holds and the Subsonic password is +// cleared. The owner makes new ones in Settings to sign their apps back in. +// +// A Subsonic app signs in with one of these, never with the login password, +// and anyone signed in to the account can make either. So ending sessions +// on a password reset doesn't shut out whoever had the account; this does. +func (h *handlers) signOutSubsonicApps(ctx context.Context, userID pgtype.UUID) error { + unheld, err := auth.MintSessionToken() + if err != nil { + return err + } + return pgx.BeginFunc(ctx, h.pool, func(tx pgx.Tx) error { + q := dbq.New(tx) + if err := q.RegenerateApiToken(ctx, dbq.RegenerateApiTokenParams{ + ID: userID, + ApiTokenHash: auth.HashAPIToken(unheld), + }); err != nil { + return err + } + return q.SetSubsonicPassword(ctx, dbq.SetSubsonicPasswordParams{ID: userID, SubsonicPassword: nil}) + }) +} diff --git a/internal/api/me_subsonic_password_test.go b/internal/api/me_subsonic_password_test.go index f908cab1..83e37623 100644 --- a/internal/api/me_subsonic_password_test.go +++ b/internal/api/me_subsonic_password_test.go @@ -5,12 +5,12 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/secret" ) func newMeSubsonicPasswordRouter(h *handlers) chi.Router { @@ -21,6 +21,8 @@ func newMeSubsonicPasswordRouter(h *handlers) chi.Router { return r } +// readSubsonicPassword returns the stored Subsonic password opened. It fails +// the test if the column holds the password in the clear. func readSubsonicPassword(t *testing.T, h *handlers, user dbq.User) *string { t.Helper() var pw *string @@ -28,13 +30,20 @@ func readSubsonicPassword(t *testing.T, h *handlers, user dbq.User) *string { "SELECT subsonic_password FROM users WHERE id = $1", user.ID).Scan(&pw); err != nil { t.Fatalf("read subsonic_password: %v", err) } - return pw + if pw == nil { + return nil + } + if !secret.IsSealed(*pw) { + t.Fatalf("subsonic_password is stored in the clear") + } + plain, err := secret.Open(secret.SubsonicPassword.Purpose(), user.ID.String(), *pw) + if err != nil { + t.Fatalf("open subsonic_password: %v", err) + } + return &plain } func TestSubsonicPassword_GenerateIsRandomAndNotTheLoginPassword(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "sspw1", "login-pw", false) router := newMeSubsonicPasswordRouter(h) @@ -74,9 +83,6 @@ func TestSubsonicPassword_GenerateIsRandomAndNotTheLoginPassword(t *testing.T) { } func TestSubsonicPassword_StatusAndClear(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "sspw2", "login-pw", false) router := newMeSubsonicPasswordRouter(h) @@ -130,3 +136,39 @@ func TestSubsonicPassword_StatusAndClear(t *testing.T) { t.Errorf("stored after clear = %q, want NULL", *got) } } + +// subsonicCredentials reads what a Subsonic app signs in with: the API key's +// hash and whether a Subsonic password is set. +func subsonicCredentials(t *testing.T, h *handlers, user dbq.User) (apiKeyHash string, hasPassword bool) { + t.Helper() + var pw *string + if err := h.pool.QueryRow(context.Background(), + "SELECT api_token_hash, subsonic_password FROM users WHERE id = $1", user.ID).Scan(&apiKeyHash, &pw); err != nil { + t.Fatalf("read subsonic credentials: %v", err) + } + return apiKeyHash, pw != nil +} + +// giveSubsonicPassword stores a Subsonic password for user, as Settings does. +func giveSubsonicPassword(t *testing.T, h *handlers, user dbq.User) { + t.Helper() + req := withUser(httptest.NewRequest(http.MethodPost, "/api/me/subsonic-password", nil), user) + rec := httptest.NewRecorder() + newMeSubsonicPasswordRouter(h).ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("generate subsonic password: %d %s", rec.Code, rec.Body.String()) + } +} + +// assertSubsonicSignedOut fails unless the API key has changed from before and +// no Subsonic password is left. +func assertSubsonicSignedOut(t *testing.T, h *handlers, user dbq.User, before string) { + t.Helper() + after, hasPassword := subsonicCredentials(t, h, user) + if after == before { + t.Error("the API key still works after the reset") + } + if hasPassword { + t.Error("the Subsonic password still works after the reset") + } +} diff --git a/internal/api/me_system_playlists.go b/internal/api/me_system_playlists.go index a4c3cde4..dcccfcba 100644 --- a/internal/api/me_system_playlists.go +++ b/internal/api/me_system_playlists.go @@ -6,8 +6,8 @@ import ( "github.com/jackc/pgx/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // systemPlaylistsStatusResp is the wire shape for the home page's placeholder diff --git a/internal/api/me_system_playlists_test.go b/internal/api/me_system_playlists_test.go index 4e594b40..6e59f9a9 100644 --- a/internal/api/me_system_playlists_test.go +++ b/internal/api/me_system_playlists_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -19,20 +18,7 @@ func newMeSystemPlaylistsRouter(h *handlers) chi.Router { return r } -func TestMeSystemPlaylistsStatus_NoSession401(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/me/system-playlists-status", nil) - rec := httptest.NewRecorder() - newMeSystemPlaylistsRouter(h).ServeHTTP(rec, req) - if rec.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", rec.Code) - } -} - func TestMeSystemPlaylistsStatus_NoRowReturnsDefault(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "alice", "pw", false) req := httptest.NewRequest(http.MethodGet, "/api/me/system-playlists-status", nil) @@ -58,9 +44,6 @@ func TestMeSystemPlaylistsStatus_NoRowReturnsDefault(t *testing.T) { } func TestMeSystemPlaylistsStatus_RowReturnsValues(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "bob", "pw", false) errMsg := "fetch failed" diff --git a/internal/api/me_test.go b/internal/api/me_test.go index 680b9827..5071a3a3 100644 --- a/internal/api/me_test.go +++ b/internal/api/me_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func TestHandleGetMe_ReturnsAuthenticatedUser(t *testing.T) { diff --git a/internal/api/me_timezone.go b/internal/api/me_timezone.go index edd316c8..313b3c01 100644 --- a/internal/api/me_timezone.go +++ b/internal/api/me_timezone.go @@ -11,9 +11,9 @@ import ( "net/http" "time" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // putTimezoneBody is the JSON body for PUT /api/me/timezone. diff --git a/internal/api/me_timezone_test.go b/internal/api/me_timezone_test.go index 576f694c..b7897e9c 100644 --- a/internal/api/me_timezone_test.go +++ b/internal/api/me_timezone_test.go @@ -6,12 +6,11 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func newMeTimezoneRouter(h *handlers) chi.Router { @@ -21,9 +20,6 @@ func newMeTimezoneRouter(h *handlers) chi.Router { } func TestPutTimezone_ValidIANA(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "tz1", "irrelevant1", false) @@ -52,9 +48,6 @@ func TestPutTimezone_ValidIANA(t *testing.T) { } func TestPutTimezone_InvalidIANA(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "tz2", "irrelevant1", false) @@ -85,9 +78,6 @@ func TestPutTimezone_InvalidIANA(t *testing.T) { } func TestPutTimezone_EmptyTimezone(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "tz3", "irrelevant1", false) diff --git a/internal/api/me_token.go b/internal/api/me_token.go index 37d5e9a6..99dbbdfc 100644 --- a/internal/api/me_token.go +++ b/internal/api/me_token.go @@ -3,10 +3,10 @@ package api import ( "net/http" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) type apiTokenResp struct { diff --git a/internal/api/me_token_test.go b/internal/api/me_token_test.go index a7ba9e1d..673b9d7e 100644 --- a/internal/api/me_token_test.go +++ b/internal/api/me_token_test.go @@ -5,10 +5,9 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/auth" "github.com/go-chi/chi/v5" ) @@ -19,9 +18,6 @@ func newMeTokenRouter(h *handlers) chi.Router { } func TestRegenerateAPIToken_IssuesNewToken(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "tok2", "pw", false) oldHash := user.ApiTokenHash diff --git a/internal/api/media.go b/internal/api/media.go index 4a577a05..f437dee4 100644 --- a/internal/api/media.go +++ b/internal/api/media.go @@ -16,10 +16,10 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // resolveAlbumCoverPath delegates to coverart.ResolveAlbumPath; kept as a @@ -63,22 +63,6 @@ func audioContentType(format string) string { return "application/octet-stream" } -// imageContentType maps a file extension to a MIME type for cover art. -// Unknown extensions fall back to octet-stream. -func imageContentType(path string) string { - switch strings.ToLower(filepath.Ext(path)) { - case ".jpg", ".jpeg": - return "image/jpeg" - case ".png": - return "image/png" - case ".webp": - return "image/webp" - case ".gif": - return "image/gif" - } - return "application/octet-stream" -} - // handleGetCover implements GET /api/albums/{id}/cover. Resolves the cover // path (explicit column, else sidecar next to first track), then delegates // byte-serving to http.ServeContent so clients get Range / If-Modified-Since @@ -90,17 +74,37 @@ func (h *handlers) handleGetCover(w http.ResponseWriter, r *http.Request) { writeErr(w, apiErr) return } - path := resolveAlbumCoverPath(r.Context(), q, album) + h.serveArt(w, r, resolveAlbumCoverPath(r.Context(), q, album)) +} + +// handleGetArtistImage implements GET /api/artists/{id}/image: the picture +// the artist-art providers fetched, or else the cover of the artist's most +// recently added album that has one (coverart.ResolveArtistPath). Subsonic +// apps get the same image from getCoverArt. +func (h *handlers) handleGetArtistImage(w http.ResponseWriter, r *http.Request) { + q := dbq.New(h.pool) + artist, apiErr := resolveByID(r, "id", q.GetArtistByID, "artist") + if apiErr != nil { + writeErr(w, apiErr) + return + } + h.serveArt(w, r, coverart.ResolveArtistPath(r.Context(), q, artist)) +} + +// serveArt serves the image file at path, or 404 when path is "" or the +// file is gone. http.ServeContent gives clients Range, If-Modified-Since and +// ETag handling. +func (h *handlers) serveArt(w http.ResponseWriter, r *http.Request, path string) { if path == "" { writeErr(w, &apierror.Error{Status: 404, Code: "not_found", Message: "cover not found"}) return } f, err := os.Open(path) if err != nil { - // resolveAlbumCoverPath saw the file a moment ago; if it vanished - // between stat and open, treat it the same as no-art — the user - // experience (404) matches, and 500 would misleadingly imply a server - // bug rather than a filesystem race. + // The resolver saw the file a moment ago; if it vanished between + // stat and open, treat it the same as no art: the user experience + // (404) matches, and 500 would misleadingly imply a server bug + // rather than a filesystem race. writeErr(w, &apierror.Error{Status: 404, Code: "not_found", Message: "cover not found"}) return } @@ -111,9 +115,9 @@ func (h *handlers) handleGetCover(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("server error", err)) return } - w.Header().Set("Content-Type", imageContentType(path)) - // Cover bytes change rarely (cover-source enrichment, manual rescan, - // rare MBID-driven re-fetch). One-day max-age + must-revalidate means + w.Header().Set("Content-Type", coverart.ImageContentType(path)) + // Art changes rarely (cover-source enrichment, manual rescan, rare + // MBID-driven re-fetch). One-day max-age + must-revalidate means // clients skip the conditional GET for the bulk of a session, but // stale art clears within 24h after a re-scan. ServeContent below // still emits Last-Modified for the conditional path when needed. diff --git a/internal/api/media_test.go b/internal/api/media_test.go index 050c2196..07d42632 100644 --- a/internal/api/media_test.go +++ b/internal/api/media_test.go @@ -10,11 +10,9 @@ import ( "path/filepath" "testing" - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func TestAudioContentType(t *testing.T) { @@ -37,24 +35,6 @@ func TestAudioContentType(t *testing.T) { } } -func TestImageContentType(t *testing.T) { - cases := map[string]string{ - "/a/cover.jpg": "image/jpeg", - "/a/cover.JPG": "image/jpeg", - "/a/cover.jpeg": "image/jpeg", - "/a/cover.png": "image/png", - "/a/cover.webp": "image/webp", - "/a/cover.gif": "image/gif", - "/a/cover.bmp": "application/octet-stream", - "/a/cover": "application/octet-stream", - } - for in, want := range cases { - if got := imageContentType(in); got != want { - t.Errorf("imageContentType(%q) = %q, want %q", in, got, want) - } - } -} - func TestFindSidecarCover_PrefersCoverOverFolder(t *testing.T) { dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "cover.jpg"), []byte("c"), 0o644); err != nil { @@ -87,72 +67,6 @@ func TestFindSidecarCover_NoneFound(t *testing.T) { } } -func TestResolveAlbumCoverPath_ExplicitPresent(t *testing.T) { - _, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - - dir := t.TempDir() - explicit := filepath.Join(dir, "explicit.jpg") - if err := os.WriteFile(explicit, []byte("e"), 0o644); err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(context.Background(), - `UPDATE albums SET cover_art_path = $1 WHERE id = $2`, explicit, album.ID); err != nil { - t.Fatalf("UPDATE albums: %v", err) - } - got := resolveAlbumCoverPath(context.Background(), dbq.New(pool), fetchAlbum(t, pool, album.ID)) - if got != explicit { - t.Errorf("got %q, want %q", got, explicit) - } -} - -func TestResolveAlbumCoverPath_ExplicitMissingFallsThroughToSidecar(t *testing.T) { - _, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - - _, dir := seedTrackWithFile(t, pool, album.ID, artist.ID, "t", []byte("audio"), "mp3") - sidecar := filepath.Join(dir, "cover.jpg") - if err := os.WriteFile(sidecar, []byte("s"), 0o644); err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(context.Background(), - `UPDATE albums SET cover_art_path = $1 WHERE id = $2`, - filepath.Join(dir, "does-not-exist.jpg"), album.ID); err != nil { - t.Fatalf("UPDATE albums: %v", err) - } - - got := resolveAlbumCoverPath(context.Background(), dbq.New(pool), fetchAlbum(t, pool, album.ID)) - if got != sidecar { - t.Errorf("got %q, want %q", got, sidecar) - } -} - -func TestResolveAlbumCoverPath_NoArt(t *testing.T) { - _, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - seedTrack(t, pool, album.ID, artist.ID, "t", 1, 1000) - got := resolveAlbumCoverPath(context.Background(), dbq.New(pool), album) - if got != "" { - t.Errorf("got %q, want empty string", got) - } -} - -// fetchAlbum reloads the album row so tests see updates made via raw SQL. -func fetchAlbum(t *testing.T, pool *pgxpool.Pool, id pgtype.UUID) dbq.Album { - t.Helper() - a, err := dbq.New(pool).GetAlbumByID(context.Background(), id) - if err != nil { - t.Fatalf("GetAlbumByID: %v", err) - } - return a -} - func TestHandleGetCover_SidecarHappyPath(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) @@ -255,40 +169,13 @@ func TestHandleGetCover_NoArt(t *testing.T) { if w.Code != http.StatusNotFound { t.Fatalf("status = %d", w.Code) } - var body errorBody + var body apierror.Body _ = json.Unmarshal(w.Body.Bytes(), &body) if body.Error.Code != "not_found" || body.Error.Message != "cover not found" { t.Errorf("error body = %+v", body) } } -func TestHandleGetCover_BadUUID(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/albums/not-a-uuid/cover", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - -func TestHandleGetCover_UnknownAlbum(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - req := httptest.NewRequest(http.MethodGet, - "/api/albums/00000000-0000-0000-0000-000000000001/cover", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusNotFound { - t.Fatalf("status = %d", w.Code) - } - var body errorBody - _ = json.Unmarshal(w.Body.Bytes(), &body) - if body.Error.Message != "album not found" { - t.Errorf("message = %q, want \"album not found\"", body.Error.Message) - } -} - // deterministicBytes returns n bytes whose values cycle 0..255. Using a // fixed pattern (not crypto/rand) makes assertions easy and the test // reproducible. @@ -329,30 +216,6 @@ func TestHandleGetStream_HappyPath(t *testing.T) { } } -func TestHandleGetStream_RangeFromStart(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - body := deterministicBytes(32 * 1024) - track, _ := seedTrackWithFile(t, pool, album.ID, artist.ID, "t", body, "mp3") - - req := httptest.NewRequest(http.MethodGet, "/api/tracks/"+uuidToString(track.ID)+"/stream", nil) - req.Header.Set("Range", "bytes=0-99") - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - - if w.Code != http.StatusPartialContent { - t.Fatalf("status = %d, want 206", w.Code) - } - if cr := w.Header().Get("Content-Range"); cr != "bytes 0-99/32768" { - t.Errorf("Content-Range = %q", cr) - } - if got := w.Body.Bytes(); !bytes.Equal(got, body[:100]) { - t.Errorf("body mismatch: len=%d, want 100", len(got)) - } -} - func TestHandleGetStream_RangeFromMiddleToEnd(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) @@ -402,33 +265,6 @@ func TestHandleGetStream_IfModifiedSinceReturns304(t *testing.T) { } } -func TestHandleGetStream_BadUUID(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/tracks/not-a-uuid/stream", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - -func TestHandleGetStream_UnknownTrack(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - req := httptest.NewRequest(http.MethodGet, - "/api/tracks/00000000-0000-0000-0000-000000000001/stream", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusNotFound { - t.Fatalf("status = %d", w.Code) - } - var body errorBody - _ = json.Unmarshal(w.Body.Bytes(), &body) - if body.Error.Message != "track not found" { - t.Errorf("message = %q, want \"track not found\"", body.Error.Message) - } -} - func TestHandleGetStream_VanishedFile(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) @@ -456,7 +292,7 @@ func TestHandleGetStream_VanishedFile(t *testing.T) { if w.Code != http.StatusNotFound { t.Fatalf("status = %d", w.Code) } - var body errorBody + var body apierror.Body _ = json.Unmarshal(w.Body.Bytes(), &body) if body.Error.Message != "track file not found" { t.Errorf("message = %q, want \"track file not found\"", body.Error.Message) diff --git a/internal/api/metrics_significance_test.go b/internal/api/metrics_significance_test.go index f07e33f9..5c3a6499 100644 --- a/internal/api/metrics_significance_test.go +++ b/internal/api/metrics_significance_test.go @@ -15,11 +15,11 @@ func TestProportionDelta_ReproducesTheDiscoverCase(t *testing.T) { if math.Abs(d.DeltaPP-(-13.3)) > 0.1 { t.Errorf("DeltaPP = %.2f, want ≈ -13.3", d.DeltaPP) } - // This is the assertion the whole task exists for: at these sample sizes + // The assertion that matters most: at these sample sizes // the margin swallows the difference. if d.Distinguishable { t.Errorf("13.3pp on n=59/70 reported as distinguishable (margin %.2f) — "+ - "this is exactly the false confidence #2495 set out to remove", d.MarginPP) + "a gap this small at these sample sizes is noise, not a finding", d.MarginPP) } if d.MarginPP <= 13.3 { t.Errorf("MarginPP = %.2f, expected it to exceed the 13.3pp delta", d.MarginPP) diff --git a/internal/api/notify_producers.go b/internal/api/notify_producers.go index 3cd2e5fc..bb5e4275 100644 --- a/internal/api/notify_producers.go +++ b/internal/api/notify_producers.go @@ -5,10 +5,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - "git.fabledsword.com/bvandeusen/minstrel/internal/requests" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) // Helpers for the handlers that produce notifications. Every call is @@ -23,25 +21,6 @@ func userLabel(u dbq.User) string { return u.Username } -func requestPayload(row dbq.Request) notifications.Payload { - return notifications.Payload{ - RequestID: uuidToString(row.ID), - RequestKind: string(row.Kind), - Name: requests.DisplayName(row), - } -} - -// notifyRequestDecided tells the requester an admin approved or declined -// their request. An admin deciding their own request needs no notice. -func (h *handlers) notifyRequestDecided(ctx context.Context, kind notifications.Kind, admin dbq.User, row dbq.Request, reason string) { - if row.UserID == admin.ID { - return - } - p := requestPayload(row) - p.Reason = reason - h.notifier.NotifyLogged(ctx, kind, notifications.ToUser(row.UserID), p.Map()) -} - // quarantineReasonLabel is a flag reason as the flag popover words it, in // lower case to sit inside a sentence ("flagged X: bad rip"). func quarantineReasonLabel(reason string) string { @@ -68,7 +47,7 @@ func (h *handlers) trackLabel(ctx context.Context, trackID pgtype.UUID) string { return "" } if a, aerr := q.GetArtistByID(ctx, t.ArtistID); aerr == nil { - return library.TrackLabel(a.Name, t.Title) + return notifications.TrackLabel(a.Name, t.Title) } return t.Title } diff --git a/internal/api/notify_producers_test.go b/internal/api/notify_producers_test.go index bee25be8..11b8ef39 100644 --- a/internal/api/notify_producers_test.go +++ b/internal/api/notify_producers_test.go @@ -11,8 +11,8 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) // inboxItem is one thing the notifier left for one user: kind and decoded @@ -53,99 +53,6 @@ func wantInbox(t *testing.T, who string, got []inboxItem, kinds ...notifications } } -func TestNotify_NewRequestReachesOtherAdminsOnce(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "np-alice", "pw", false) - admin := seedUser(t, pool, "np-admin", "pw", true) - selfAdmin := seedUser(t, pool, "np-self", "pw", true) - - rv := createArtistRequest(t, h, alice, "np-mbid-1", "Pending Band") - // The same request again dedups into the first and is not announced twice. - createArtistRequest(t, h, alice, "np-mbid-1", "Pending Band") - - got := inboxOf(t, pool, admin) - wantInbox(t, "admin", got, notifications.KindRequestPending) - if got[0].Payload.RequestID != uuidToString(rv.ID) || got[0].Payload.Name != "Pending Band" || got[0].Payload.Actor != alice.Username { - t.Errorf("pending payload = %+v", got[0].Payload) - } - wantInbox(t, "requester", inboxOf(t, pool, alice)) - - // An admin's own request goes to the other admins, never back to them. - createArtistRequest(t, h, selfAdmin, "np-mbid-2", "Own Band") - wantInbox(t, "self-admin", inboxOf(t, pool, selfAdmin), notifications.KindRequestPending) - if n := len(inboxOf(t, pool, admin)); n != 2 { - t.Errorf("admin inbox = %d, want 2 (alice's and the self-admin's)", n) - } -} - -func TestNotify_AutoApprovedRequestWaitsOnNobody(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, h.pool, "np-auto", "pw", false) - admin := seedUser(t, h.pool, "np-auto-admin", "pw", true) - if _, err := h.pool.Exec(context.Background(), - "UPDATE users SET auto_approve_requests = true WHERE id = $1", alice.ID); err != nil { - t.Fatalf("set auto_approve: %v", err) - } - alice, err := dbq.New(h.pool).GetUserByID(context.Background(), alice.ID) - if err != nil { - t.Fatalf("reload user: %v", err) - } - - rv := createArtistRequest(t, h, alice, "np-auto-mbid", "Auto Band") - if rv.Status != "approved" { - t.Fatalf("status = %q, want approved — the stub should accept the add", rv.Status) - } - wantInbox(t, "admin", inboxOf(t, h.pool, admin)) - wantInbox(t, "requester", inboxOf(t, h.pool, alice)) -} - -func TestNotify_DecisionsReachTheRequester(t *testing.T) { - h, _ := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, h.pool, "np-dec-alice", "pw", false) - admin := seedUser(t, h.pool, "np-dec-admin", "pw", true) - - approved := seedPendingArtistRequest(t, h, alice, "np-dec-1", "Yes Band") - rejected := seedPendingArtistRequest(t, h, alice, "np-dec-2", "No Band") - own := seedPendingArtistRequest(t, h, admin, "np-dec-3", "Own Band") - - for _, c := range []struct { - id string - verb string - body []byte - }{ - {uuidToString(approved.ID), "approve", nil}, - {uuidToString(rejected.ID), "reject", []byte(`{"notes":"Only a live bootleg exists"}`)}, - {uuidToString(own.ID), "approve", nil}, - } { - w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+c.id+"/"+c.verb, c.body, admin) - if w.Code != http.StatusOK { - t.Fatalf("%s %s: status = %d; body = %s", c.verb, c.id, w.Code, w.Body.String()) - } - } - - got := inboxOf(t, h.pool, alice) - wantInbox(t, "requester", got, notifications.KindRequestRejected, notifications.KindRequestApproved) - if got[0].Payload.Name != "No Band" || got[0].Payload.Reason != "Only a live bootleg exists" { - t.Errorf("rejected payload = %+v", got[0].Payload) - } - if got[1].Payload.Name != "Yes Band" || got[1].Payload.Reason != "" { - t.Errorf("approved payload = %+v", got[1].Payload) - } - // The admin decided their own request: no notice. alice's two pending - // notices are all the admin holds. - for _, it := range inboxOf(t, h.pool, admin) { - if it.Kind != string(notifications.KindRequestPending) { - t.Errorf("admin inbox holds %q, want only request_pending", it.Kind) - } - } -} - func TestNotify_FlagReachesAdminsButNotTheFlagger(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) diff --git a/internal/api/playback_errors.go b/internal/api/playback_errors.go index 99296522..9c28ffeb 100644 --- a/internal/api/playback_errors.go +++ b/internal/api/playback_errors.go @@ -9,12 +9,12 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) -// Valid `kind` values. Mirrors the CHECK constraint in migration 0032 +// Valid `kind` values. Mirrors playback_errors_kind_check // — keep both lists in sync if you add a kind here, otherwise inserts // pass the handler whitelist and trip the DB constraint instead. var validPlaybackErrorKinds = map[string]struct{}{ @@ -23,16 +23,15 @@ var validPlaybackErrorKinds = map[string]struct{}{ "stalled": {}, } -// Valid `resolution` values. Hidden / deleted / requested are stamped -// automatically when the admin clicks the matching action from the -// inbox; fixed / ignored are operator-driven (no action taken on the -// track itself). Mirrors the CHECK constraint in migration 0032. +// Valid `resolution` values. Hidden / deleted are stamped automatically +// when the admin clicks the matching action from the inbox; fixed / +// ignored are operator-driven (no action taken on the track itself). +// Mirrors the playback_errors_resolution_check constraint. var validPlaybackErrorResolutions = map[string]struct{}{ - "hidden": {}, - "deleted": {}, - "requested": {}, - "fixed": {}, - "ignored": {}, + "hidden": {}, + "deleted": {}, + "fixed": {}, + "ignored": {}, } // reportPlaybackErrorRequest is the body of POST /api/playback-errors. @@ -147,7 +146,7 @@ func (h *handlers) handleListAdminPlaybackErrors(w http.ResponseWriter, r *http. }) if err != nil { h.logger.Error("admin: list playback_errors", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } out := make([]adminPlaybackErrorView, 0, len(rows)) @@ -182,21 +181,21 @@ func (h *handlers) handleListAdminPlaybackErrors(w http.ResponseWriter, r *http. func (h *handlers) handleResolvePlaybackError(w http.ResponseWriter, r *http.Request) { admin, ok := auth.UserFromContext(r.Context()) if !ok { - writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") + writeErr(w, apierror.ErrUnauthorized) return } id, ok := parseUUID(chi.URLParam(r, "id")) if !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + writeErr(w, apierror.BadRequest("invalid_id", "invalid id")) return } var req resolvePlaybackErrorRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeAdminJSONErr(w, http.StatusBadRequest, "bad_request") + writeErr(w, apierror.BadRequest("bad_request", "invalid JSON body")) return } if _, ok := validPlaybackErrorResolutions[req.Resolution]; !ok { - writeAdminJSONErr(w, http.StatusBadRequest, "invalid_resolution") + writeErr(w, apierror.BadRequest("invalid_resolution", "unknown resolution")) return } resolution := req.Resolution @@ -207,11 +206,11 @@ func (h *handlers) handleResolvePlaybackError(w http.ResponseWriter, r *http.Req }) if err != nil { if errors.Is(err, pgx.ErrNoRows) { - writeAdminJSONErr(w, http.StatusNotFound, "not_found") + writeErr(w, apierror.ErrNotFound) return } h.logger.Error("admin: resolve playback_error", "err", err) - writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + writeErr(w, apierror.Internal(err)) return } writeJSON(w, http.StatusOK, map[string]string{"id": uuidToString(row.ID)}) diff --git a/internal/api/playlists.go b/internal/api/playlists.go index a1b22da7..2a78e799 100644 --- a/internal/api/playlists.go +++ b/internal/api/playlists.go @@ -4,7 +4,9 @@ import ( "context" "errors" "fmt" + "io/fs" "net/http" + "os" "path/filepath" "strconv" "strings" @@ -14,9 +16,10 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" + "github.com/Fabled-Sword/minstrel/internal/playlists" ) // playlistRowView is the wire shape for a playlist header. Mirrors @@ -39,10 +42,20 @@ type playlistRowView struct { Refreshable bool `json:"refreshable"` SeedArtistID *string `json:"seed_artist_id,omitempty"` CoverURL string `json:"cover_url,omitempty"` - TrackCount int32 `json:"track_count"` - DurationSec int32 `json:"duration_sec"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` + // CoverAlbumIDs are up to six distinct albums with cover art, in + // track order (each album's art is /api/albums/{id}/cover). A shelf + // of playlist tiles gives each tile the first of its albums no tile + // before it already shows, so no cover repeats along the shelf. + // Omitted when the playlist has none. + CoverAlbumIDs []string `json:"cover_album_ids,omitempty"` + // ShelfRank is a system mix's place on its Home shelf, 1 first: genre + // mixes are numbered by how much the user listens to each genre. + // Omitted (0) for playlists the client orders itself. + ShelfRank int32 `json:"shelf_rank,omitempty"` + TrackCount int32 `json:"track_count"` + DurationSec int32 `json:"duration_sec"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` } // playlistTrackView is one row of a playlist's track list on the wire. @@ -164,16 +177,18 @@ func (h *handlers) maybeKickBackgroundBuild(ctx context.Context, userID pgtype.U if !stale || run.InFlight { return } - go func() { - bgCtx := context.Background() - if err := playlists.BuildSystemPlaylists(bgCtx, h.pool, h.logger, userID, time.Now(), h.dataDir); err != nil { + go periodic.Safe(context.Background(), h.logger, "lazy system playlist build", func(ctx context.Context) { + if err := playlists.BuildSystemPlaylists(ctx, h.pool, h.logger, userID, time.Now(), h.dataDir); err != nil { h.logger.Warn("lazy system playlist build failed", "user_id", "redacted", "err", err) } - }() + }) } +// createPlaylistBody's ID is optional: a client that makes a playlist +// offline picks its id, so a retry of the same create finds the same list. type createPlaylistBody struct { + ID string `json:"id,omitempty"` Name string `json:"name"` Description string `json:"description"` IsPublic bool `json:"is_public"` @@ -190,12 +205,19 @@ func (h *handlers) handleCreatePlaylist(w http.ResponseWriter, r *http.Request) if !decodeBody(w, r, &body) { return } - row, err := h.playlists.Create(r.Context(), caller.ID, body.Name, body.Description, body.IsPublic) + var id pgtype.UUID + if body.ID != "" { + var ok bool + if id, ok = parseUUID(body.ID); !ok { + writeErr(w, apierror.BadRequest("bad_request", "invalid playlist id")) + return + } + } + row, err := h.playlists.CreateWithID(r.Context(), caller.ID, id, body.Name, body.Description, body.IsPublic) if err != nil { h.writePlaylistErr(w, err, "create") return } - h.publishPlaylistEvent("playlist.created", caller.ID, row.ID) writeJSON(w, http.StatusOK, playlistRowToView(row)) } @@ -251,7 +273,6 @@ func (h *handlers) handleUpdatePlaylist(w http.ResponseWriter, r *http.Request) h.writePlaylistErr(w, err, "update") return } - h.publishPlaylistEvent("playlist.updated", caller.ID, playlistID) writeJSON(w, http.StatusOK, playlistRowToView(row)) } @@ -270,12 +291,15 @@ func (h *handlers) handleDeletePlaylist(w http.ResponseWriter, r *http.Request) h.writePlaylistErr(w, err, "delete") return } - h.publishPlaylistEvent("playlist.deleted", caller.ID, playlistID) w.WriteHeader(http.StatusNoContent) } type appendTracksBody struct { TrackIDs []string `json:"track_ids"` + // RequestID names this append, so a client that sends it again (a + // queued write replayed after its reply was lost) adds nothing more. + // Optional: without it, every send appends. + RequestID string `json:"request_id"` } // handleAppendTracks implements POST /api/playlists/{id}/tracks. Owner @@ -294,20 +318,21 @@ func (h *handlers) handleAppendTracks(w http.ResponseWriter, r *http.Request) { if !decodeBody(w, r, &body) { return } - trackIDs := make([]pgtype.UUID, 0, len(body.TrackIDs)) - for _, s := range body.TrackIDs { - u, ok := parseUUID(s) - if !ok { - writeErr(w, apierror.BadRequest("bad_request", fmt.Sprintf("invalid track id %q", s))) + trackIDs, ok := parseTrackIDs(w, body.TrackIDs) + if !ok { + return + } + var requestID pgtype.UUID + if body.RequestID != "" { + if requestID, ok = parseUUID(body.RequestID); !ok { + writeErr(w, apierror.BadRequest("bad_request", fmt.Sprintf("invalid request id %q", body.RequestID))) return } - trackIDs = append(trackIDs, u) } - if err := h.playlists.AppendTracks(r.Context(), caller.ID, playlistID, trackIDs); err != nil { + if err := h.playlists.AppendTracksOnce(r.Context(), caller.ID, playlistID, trackIDs, requestID); err != nil { h.writePlaylistErr(w, err, "append tracks") return } - h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID) detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID) if err != nil { h.writePlaylistErr(w, err, "get-after-append") @@ -334,11 +359,19 @@ func (h *handlers) handleRemovePlaylistTrack(w http.ResponseWriter, r *http.Requ writeErr(w, apierror.BadRequest("bad_request", "invalid position")) return } - if err := h.playlists.RemoveTrack(r.Context(), caller.ID, playlistID, int32(pos64)); err != nil { + // track_id, when sent, names the song the caller expects at position; + // if another song is there now, nothing is removed (409). + var expect pgtype.UUID + if raw := r.URL.Query().Get("track_id"); raw != "" { + if expect, ok = parseUUID(raw); !ok { + writeErr(w, apierror.BadRequest("bad_request", "invalid track id")) + return + } + } + if err := h.playlists.RemoveTrack(r.Context(), caller.ID, playlistID, int32(pos64), expect); err != nil { h.writePlaylistErr(w, err, "remove track") return } - h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID) detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID) if err != nil { h.writePlaylistErr(w, err, "get-after-remove") @@ -347,8 +380,13 @@ func (h *handlers) handleRemovePlaylistTrack(w http.ResponseWriter, r *http.Requ writeJSON(w, http.StatusOK, playlistDetailToView(detail)) } +// reorderTracksBody carries the new order one of two ways: +// ordered_positions, a permutation of every position, or track_ids, the +// songs in their new order (see playlists.Service.ReorderTracks), which a +// client can safely send again. type reorderTracksBody struct { - OrderedPositions []int32 `json:"ordered_positions"` + OrderedPositions []int32 `json:"ordered_positions"` + TrackIDs []string `json:"track_ids"` } // handleReorderPlaylist implements PUT /api/playlists/{id}/tracks. Owner @@ -367,11 +405,20 @@ func (h *handlers) handleReorderPlaylist(w http.ResponseWriter, r *http.Request) if !decodeBody(w, r, &body) { return } - if err := h.playlists.Reorder(r.Context(), caller.ID, playlistID, body.OrderedPositions); err != nil { + var err error + if body.TrackIDs != nil { + trackIDs, ok := parseTrackIDs(w, body.TrackIDs) + if !ok { + return + } + err = h.playlists.ReorderTracks(r.Context(), caller.ID, playlistID, trackIDs) + } else { + err = h.playlists.Reorder(r.Context(), caller.ID, playlistID, body.OrderedPositions) + } + if err != nil { h.writePlaylistErr(w, err, "reorder") return } - h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID) detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID) if err != nil { h.writePlaylistErr(w, err, "get-after-reorder") @@ -380,6 +427,21 @@ func (h *handlers) handleReorderPlaylist(w http.ResponseWriter, r *http.Request) writeJSON(w, http.StatusOK, playlistDetailToView(detail)) } +// parseTrackIDs parses a body's track ids, or answers 400 naming the first +// one that isn't an id and returns false. +func parseTrackIDs(w http.ResponseWriter, raw []string) ([]pgtype.UUID, bool) { + out := make([]pgtype.UUID, 0, len(raw)) + for _, s := range raw { + u, ok := parseUUID(s) + if !ok { + writeErr(w, apierror.BadRequest("bad_request", fmt.Sprintf("invalid track id %q", s))) + return nil, false + } + out = append(out, u) + } + return out, true +} + // handleGetPlaylistCover serves the cached collage from disk. The // playlist visibility check (owner-or-public) runs in the service Get // call before we look at cover_path, so we don't leak the existence of @@ -403,6 +465,17 @@ func (h *handlers) handleGetPlaylistCover(w http.ResponseWriter, r *http.Request return } full := filepath.Join(h.dataDir, *detail.CoverPath) + if _, err := os.Stat(full); errors.Is(err, fs.ErrNotExist) { + // The row names a collage the data directory no longer holds (it + // was lost or moved without the database). Draw it again rather + // than answer with a broken image. + rel, gerr := playlists.GenerateCollage(r.Context(), h.pool, playlistID, h.dataDir) + if gerr != nil || rel == "" { + writeErr(w, &apierror.Error{Status: 404, Code: "not_found", Message: "no cover"}) + return + } + full = filepath.Join(h.dataDir, rel) + } // Playlist collages recompute when the playlist's tracks change // (system playlists re-rendered on rebuild, user playlists when // modified). 5 minutes is short enough for normal edits to feel @@ -425,6 +498,8 @@ func (h *handlers) writePlaylistErr(w http.ResponseWriter, err error, op string) writeErr(w, apierror.Forbidden("system_playlist_readonly", "system-generated playlists cannot be edited")) case errors.Is(err, playlists.ErrInvalidInput): writeErr(w, apierror.BadRequest("bad_request", err.Error())) + case errors.Is(err, playlists.ErrListChanged): + writeErr(w, apierror.Conflict("list_changed", "the playlist has changed; reload it and try again")) case errors.Is(err, playlists.ErrTrackNotFound): writeErr(w, apierror.BadRequest("bad_request", "one of the supplied track ids does not exist")) default: @@ -447,6 +522,7 @@ func playlistRowToView(r *playlists.PlaylistRow) playlistRowView { Kind: r.Kind, SystemVariant: r.SystemVariant, Refreshable: r.SystemVariant != nil && playlists.RefreshableSystemKind(*r.SystemVariant), + ShelfRank: r.ShelfRank, TrackCount: r.TrackCount, DurationSec: r.DurationSec, CreatedAt: formatTimestamp(r.CreatedAt), @@ -459,6 +535,9 @@ func playlistRowToView(r *playlists.PlaylistRow) playlistRowView { if r.CoverPath != nil && *r.CoverPath != "" { v.CoverURL = "/api/playlists/" + v.ID + "/cover" } + for _, id := range r.CoverAlbumIDs { + v.CoverAlbumIDs = append(v.CoverAlbumIDs, uuidToString(id)) + } return v } diff --git a/internal/api/playlists_system_shuffle.go b/internal/api/playlists_system_shuffle.go index a1315c93..cd16071a 100644 --- a/internal/api/playlists_system_shuffle.go +++ b/internal/api/playlists_system_shuffle.go @@ -9,9 +9,9 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/playlists" ) // Generic registry-driven system-playlist endpoints. {kind} is the raw diff --git a/internal/api/playlists_system_test.go b/internal/api/playlists_system_test.go index 7664fbf4..b4cd52f2 100644 --- a/internal/api/playlists_system_test.go +++ b/internal/api/playlists_system_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -26,9 +25,6 @@ func newSystemPlaylistRouter(h *handlers) chi.Router { } func TestSystemRefresh_ForYou_Returns200(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "sysforyou", "pw", false) @@ -53,9 +49,6 @@ func TestSystemRefresh_ForYou_Returns200(t *testing.T) { } func TestSystemRefresh_Discover_Returns200(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "sysdiscover", "pw", false) @@ -79,9 +72,6 @@ func TestSystemRefresh_Discover_Returns200(t *testing.T) { // A non-singleton (songs_like_artist) or unknown kind isn't // addressable by the generic endpoints → 404, not a build. func TestSystemRefresh_NonSingletonKind_Returns404(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) user := seedUser(t, pool, "sysbadkind", "pw", false) @@ -95,18 +85,3 @@ func TestSystemRefresh_NonSingletonKind_Returns404(t *testing.T) { } } } - -func TestSystemRefresh_NoAuth_Returns401(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, _ := testHandlers(t) - - req := httptest.NewRequest(http.MethodPost, "/api/playlists/system/for_you/refresh", nil) - rec := httptest.NewRecorder() - newSystemPlaylistRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", rec.Code) - } -} diff --git a/internal/api/playlists_test.go b/internal/api/playlists_test.go index 0930a2e3..6c27ef17 100644 --- a/internal/api/playlists_test.go +++ b/internal/api/playlists_test.go @@ -6,19 +6,22 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "reflect" + "sort" "strings" "testing" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // newPlaylistsRouter mounts the 9 playlist routes for an in-test chi // instance. RequireUser is NOT applied — tests inject the user into // context manually so we exercise the handler-owned auth defense -// directly. Mirrors the pattern from newAdminTracksRouter. +// directly. func newPlaylistsRouter(h *handlers) chi.Router { r := chi.NewRouter() r.Get("/api/playlists", h.handleListPlaylists) @@ -63,29 +66,6 @@ func seedSimpleTrack(t *testing.T, pool *pgxpool.Pool, title, artist string) dbq return seedTrack(t, pool, al.ID, a.ID, title, 1, 1000) } -// TestPlaylists_NoSession401 verifies the handler-owned defensive 401 -// path on each route. Real traffic hits RequireUser upstream, but the -// handler also defends against routing misconfigurations. -func TestPlaylists_NoSession401(t *testing.T) { - h, _ := testHandlers(t) - r := newPlaylistsRouter(h) - - req := httptest.NewRequest(http.MethodGet, "/api/playlists", nil) - w := httptest.NewRecorder() - // Note: NO user in context. - r.ServeHTTP(w, req) - if w.Code != http.StatusUnauthorized { - t.Fatalf("status = %d, want 401; body = %s", w.Code, w.Body.String()) - } - var env errorBody - if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if env.Error.Code != "unauthenticated" { - t.Errorf("error.code = %q, want unauthenticated", env.Error.Code) - } -} - // TestPlaylists_CreateThenGet exercises the happy-path end-to-end: // POST creates a row, the response carries the id, GET round-trips // the same fields. @@ -147,7 +127,7 @@ func TestPlaylists_CreateEmptyName400(t *testing.T) { if w.Code != http.StatusBadRequest { t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) } - var env errorBody + var env apierror.Body if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { t.Fatalf("decode: %v", err) } @@ -180,7 +160,7 @@ func TestPlaylists_PatchOwnerOnly(t *testing.T) { if pw.Code != http.StatusForbidden { t.Fatalf("non-owner patch status = %d, want 403; body = %s", pw.Code, pw.Body.String()) } - var env errorBody + var env apierror.Body if err := json.Unmarshal(pw.Body.Bytes(), &env); err != nil { t.Fatalf("decode: %v", err) } @@ -189,20 +169,6 @@ func TestPlaylists_PatchOwnerOnly(t *testing.T) { } } -// TestPlaylists_GetNotFound verifies a well-formed UUID with no row -// surfaces as 404 not_found. -func TestPlaylists_GetNotFound(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "pw", false) - - missing := "00000000-0000-0000-0000-000000000099" - w := doPlaylistsReq(h, user, http.MethodGet, "/api/playlists/"+missing, nil) - if w.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String()) - } -} - // TestPlaylists_ListSplitsOwnedAndPublic verifies the response carries // owned vs. public buckets correctly. Alice owns one private + one // public; Bob sees only Alice's public. @@ -396,19 +362,6 @@ func TestPlaylists_DeleteOwnerOnly(t *testing.T) { } } -// TestPlaylists_BadUUID400 verifies a malformed playlist id returns -// bad_request rather than reaching the service layer. -func TestPlaylists_BadUUID400(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "pw", false) - - w := doPlaylistsReq(h, user, http.MethodGet, "/api/playlists/not-a-uuid", nil) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - // TestPlaylists_AppendInvalidTrackUUID400 verifies a malformed track id // in the append body returns bad_request before reaching the DB. func TestPlaylists_AppendInvalidTrackUUID400(t *testing.T) { @@ -455,53 +408,14 @@ func TestPlaylists_CoverNoneReturns404(t *testing.T) { } } -// TestListPlaylists_KindFilterDefaultsToUser verifies that an absent ?kind= -// parameter defaults to "user" and excludes system-kind playlists. -func TestListPlaylists_KindFilterDefaultsToUser(t *testing.T) { +// The playlist list filters by kind: the person's own playlists by default, +// the system mixes with kind=system, both with kind=all, and any other kind +// is a 400. +func TestListPlaylists_FiltersByKind(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - u := seedUser(t, pool, "klistdefault", "pw", false) - - // Create one user-kind playlist via the service. - userPL, err := h.playlists.Create(context.Background(), u.ID, "My PL", "", false) - if err != nil { - t.Fatalf("create user playlist: %v", err) - } - // Insert a system-kind playlist directly via SQL. - if _, err := pool.Exec(context.Background(), ` - INSERT INTO playlists (user_id, name, description, is_public, kind, system_variant) - VALUES ($1, 'For You', '', false, 'system', 'for_you') - `, u.ID); err != nil { - t.Fatalf("seed system playlist: %v", err) - } - - w := doPlaylistsReq(h, u, "GET", "/api/playlists", nil) - if w.Code != http.StatusOK { - t.Fatalf("status: got %d, want 200; body=%s", w.Code, w.Body.String()) - } - var resp listPlaylistsResponse - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if len(resp.Owned) != 1 { - t.Fatalf("default should return 1 user-kind playlist; got %d", len(resp.Owned)) - } - if resp.Owned[0].Kind != "user" { - t.Errorf("expected kind=user; got %q", resp.Owned[0].Kind) - } - if resp.Owned[0].ID != uuidToString(userPL.ID) { - t.Errorf("returned wrong playlist id") - } -} - -// TestListPlaylists_KindSystem verifies ?kind=system returns only -// system-generated playlists and excludes user-created ones. -func TestListPlaylists_KindSystem(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - u := seedUser(t, pool, "klistsys", "pw", false) - - if _, err := h.playlists.Create(context.Background(), u.ID, "User PL", "", false); err != nil { + u := seedUser(t, pool, "klist", "pw", false) + if _, err := h.playlists.Create(context.Background(), u.ID, "My PL", "", false); err != nil { t.Fatalf("create user playlist: %v", err) } if _, err := pool.Exec(context.Background(), ` @@ -511,62 +425,37 @@ func TestListPlaylists_KindSystem(t *testing.T) { t.Fatalf("seed system playlist: %v", err) } - w := doPlaylistsReq(h, u, "GET", "/api/playlists?kind=system", nil) - if w.Code != http.StatusOK { - t.Fatalf("status: got %d, want 200; body=%s", w.Code, w.Body.String()) - } - var resp listPlaylistsResponse - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if len(resp.Owned) != 1 { - t.Fatalf("kind=system should return 1 system playlist; got %d", len(resp.Owned)) - } - if resp.Owned[0].Kind != "system" { - t.Errorf("expected kind=system; got %q", resp.Owned[0].Kind) - } -} - -// TestListPlaylists_KindAll verifies ?kind=all returns all playlists -// regardless of kind. -func TestListPlaylists_KindAll(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - u := seedUser(t, pool, "klistall", "pw", false) - - if _, err := h.playlists.Create(context.Background(), u.ID, "User PL", "", false); err != nil { - t.Fatalf("create user playlist: %v", err) - } - if _, err := pool.Exec(context.Background(), ` - INSERT INTO playlists (user_id, name, description, is_public, kind, system_variant) - VALUES ($1, 'For You', '', false, 'system', 'for_you') - `, u.ID); err != nil { - t.Fatalf("seed system playlist: %v", err) - } - - w := doPlaylistsReq(h, u, "GET", "/api/playlists?kind=all", nil) - if w.Code != http.StatusOK { - t.Fatalf("status: got %d, want 200; body=%s", w.Code, w.Body.String()) - } - var resp listPlaylistsResponse - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v", err) - } - if len(resp.Owned) != 2 { - t.Fatalf("kind=all should return both playlists; got %d", len(resp.Owned)) - } -} - -// TestListPlaylists_BadKindReturns400 verifies an unrecognised kind value -// is rejected with 400 bad_kind. -func TestListPlaylists_BadKindReturns400(t *testing.T) { - h, pool := testHandlers(t) - u := seedUser(t, pool, "klistbad", "pw", false) - _ = pool - - w := doPlaylistsReq(h, u, "GET", "/api/playlists?kind=garbage", nil) - if w.Code != http.StatusBadRequest { - t.Fatalf("expected 400; got %d, body=%s", w.Code, w.Body.String()) + for _, tc := range []struct { + query string + kinds []string // the kinds listed, in any order; nil means a 400 + }{ + {"", []string{"user"}}, + {"?kind=system", []string{"system"}}, + {"?kind=all", []string{"system", "user"}}, + {"?kind=garbage", nil}, + } { + w := doPlaylistsReq(h, u, "GET", "/api/playlists"+tc.query, nil) + if tc.kinds == nil { + if w.Code != http.StatusBadRequest { + t.Errorf("%q: status %d, want 400", tc.query, w.Code) + } + continue + } + if w.Code != http.StatusOK { + t.Fatalf("%q: status %d, want 200; body=%s", tc.query, w.Code, w.Body.String()) + } + var resp listPlaylistsResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("%q: decode: %v", tc.query, err) + } + var got []string + for _, p := range resp.Owned { + got = append(got, p.Kind) + } + sort.Strings(got) + if !reflect.DeepEqual(got, tc.kinds) { + t.Errorf("%q listed kinds %v, want %v", tc.query, got, tc.kinds) + } } } @@ -607,7 +496,7 @@ func TestEditEndpoints_403OnSystemPlaylist(t *testing.T) { if w.Code != http.StatusForbidden { t.Fatalf("status: got %d want 403; body=%s", w.Code, w.Body.String()) } - var env errorBody + var env apierror.Body if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { t.Fatalf("decode envelope: %v", err) } diff --git a/internal/api/prelude.go b/internal/api/prelude.go index 57333d49..0fe0a64e 100644 --- a/internal/api/prelude.go +++ b/internal/api/prelude.go @@ -2,14 +2,16 @@ package api import ( "encoding/json" + "fmt" "net/http" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" + "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // requireUser returns the authenticated user from request context. On @@ -25,6 +27,33 @@ func requireUser(w http.ResponseWriter, r *http.Request) (dbq.User, bool) { return user, true } +// minPasswordLength is the shortest password any account may set: at +// sign-up, on reset, on change, and when an admin sets one. +const minPasswordLength = 8 + +// checkNewPassword answers 400 password_too_short and returns false when pw +// is too short to set. Every path that sets a password calls it, so the +// rule lives in one place. +func checkNewPassword(w http.ResponseWriter, pw string) bool { + if len(pw) < minPasswordLength { + writeErr(w, apierror.BadRequest("password_too_short", + fmt.Sprintf("password must be at least %d characters", minPasswordLength))) + return false + } + return true +} + +// passwordCost is bcrypt's work factor for stored passwords. The package's +// tests lower it, since each hash at the default cost takes most of a second +// under the race detector, and check first that this default is at least +// bcrypt's. +var passwordCost = bcrypt.DefaultCost + +// hashPassword is the one place a password is hashed for storage. +func hashPassword(pw string) ([]byte, error) { + return bcrypt.GenerateFromPassword([]byte(pw), passwordCost) +} + // requireURLUUID parses the chi URL parameter named key as a UUID. On // invalid input, writes a 400 envelope and returns ok=false; the caller // MUST return immediately on ok=false. diff --git a/internal/api/quarantine.go b/internal/api/quarantine.go index 091d24e7..9bdc6e38 100644 --- a/internal/api/quarantine.go +++ b/internal/api/quarantine.go @@ -6,10 +6,10 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - "git.fabledsword.com/bvandeusen/minstrel/internal/quarantine" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/quarantine" ) // quarantineView is the JSON shape returned by the user-facing endpoints diff --git a/internal/api/quarantine_test.go b/internal/api/quarantine_test.go index 83a425e6..8f6e76fe 100644 --- a/internal/api/quarantine_test.go +++ b/internal/api/quarantine_test.go @@ -2,7 +2,6 @@ package api import ( "bytes" - "context" "encoding/json" "fmt" "net/http" @@ -11,7 +10,7 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // newQuarantineRouter builds a test router for the user-facing /api/quarantine @@ -262,44 +261,3 @@ func TestListMine_OK(t *testing.T) { } } } - -// TestQuarantineEndpointsRequireAuth verifies the /api/quarantine endpoints -// return 401 when no user is in context (covers RequireUser failure mode -// uniformly across the three handlers). -func TestQuarantineEndpointsRequireAuth(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - - cases := []struct { - name string - method string - path string - body string - }{ - {"flag", http.MethodPost, "/api/quarantine", `{"track_id":"00000000-0000-0000-0000-000000000001","reason":"bad_rip"}`}, - {"unflag", http.MethodDelete, "/api/quarantine/00000000-0000-0000-0000-000000000001", ""}, - {"mine", http.MethodGet, "/api/quarantine/mine", ""}, - } - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - var reqBody *bytes.Buffer - if tc.body != "" { - reqBody = bytes.NewBufferString(tc.body) - } else { - reqBody = bytes.NewBuffer(nil) - } - req := httptest.NewRequest(tc.method, tc.path, reqBody) - if tc.body != "" { - req.Header.Set("Content-Type", "application/json") - } - // No user injected into context. - req = req.WithContext(context.Background()) - w := httptest.NewRecorder() - newQuarantineRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusUnauthorized { - t.Errorf("%s: status = %d, want 401; body = %s", tc.name, w.Code, w.Body.String()) - } - }) - } -} diff --git a/internal/api/radio.go b/internal/api/radio.go index 641ceb58..b21f37b5 100644 --- a/internal/api/radio.go +++ b/internal/api/radio.go @@ -1,22 +1,18 @@ package api import ( - "context" - "encoding/json" "errors" - "log/slog" "net/http" "strconv" "strings" - "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation" - "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/recommendation" + "github.com/Fabled-Sword/minstrel/internal/recsettings" ) // RadioResponse is the body of GET /api/radio. @@ -26,10 +22,8 @@ type RadioResponse struct { // handleRadio implements GET /api/radio?seed_track=&limit=. // -// Returns the seed at index 0, followed by up to limit-1 weighted-shuffle -// picks from the user's library, scored by recommendation.Score. The -// scoring formula folds in contextual_match_score using the user's current -// session vector (read from the most recent open play_event). +// Returns the seed at index 0, followed by up to limit-1 picks from +// recommendation.Picker.Radio. func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) { user, ok := requireUser(w, r) if !ok { @@ -81,55 +75,15 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) { return } - currentVec := loadCurrentSessionVector(r, q, user.ID, h.logger) - // Condition on the current device: the latest play's device is a - // cheap, request-free proxy for what the user is on right now. - currentVec.DeviceClass = latestDeviceClass(r.Context(), q, user.ID, h.logger) - exclude := parseExcludeParam(r.URL.Query().Get("exclude")) - // Size the pool to the library: a fixed ~170 candidates samples a shrinking - // fraction of a growing collection. Degrades to the base limits if the - // count is unavailable — never fails the request over a sizing hint. - librarySize := h.librarySize.Get(r.Context(), func(ctx context.Context) (int64, error) { - return recommendation.CountLibraryTracks(ctx, q) - }) - limits := recommendation.ScaleForLibrary( - recommendation.DefaultCandidateSourceLimits(), librarySize, - ) - candidates, err := recommendation.LoadCandidatesFromSimilarity( - r.Context(), q, user.ID, seedID, - h.recCfg.RecentlyPlayedHours, currentVec, exclude, limits, - // A fresh seed per request: radio is a new session each time - // and SHOULD draw differently. The system mixes are the surfaces that - // promise repeatability; this is not one of them. - strconv.FormatInt(time.Now().UnixNano(), 36), - ) + // limit-1 because the seed takes the first slot and is prepended below. + picks, err := h.picker().Radio(r.Context(), q, user.ID, seedID, limit-1, exclude) if err != nil { - h.logger.Warn("api: radio: similarity-pool failed; falling back to whole-library", "err", err) - candidates, err = recommendation.LoadCandidates( - r.Context(), q, user.ID, seedID, - h.recCfg.RecentlyPlayedHours, currentVec, - ) - if err != nil { - h.logger.Error("api: radio: load candidates fallback failed", "err", err) - writeErr(w, apierror.InternalMsg("candidate load failed", err)) - return - } + h.logger.Error("api: radio: load candidates failed", "err", err) + writeErr(w, apierror.InternalMsg("candidate load failed", err)) + return } - // Scoring weights come from the DB-backed tuning — - // read per request so an admin change takes effect live. - weights := h.recSettings.Weights(recsettings.ScopeRadio) - // Diversity caps, so a whole session cannot come back from one artist. - // Scaled to - // the requested length so a 20-track radio and a 200-track one are capped - // alike; Shuffle relaxes them rather than returning a short radio. - // - // limit-1 because the seed track occupies the first slot and is prepended - // below — the caps govern the tracks that FOLLOW it. - caps := recommendation.RadioDiversityCaps(limit - 1) - picks := recommendation.Shuffle(candidates, weights, time.Now().UTC(), h.rng, limit-1, caps) - out := make([]TrackRef, 0, len(picks)+1) out = append(out, trackRefFrom(track, album.Title, artist.Name)) for _, p := range picks { @@ -150,46 +104,16 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, RadioResponse{Tracks: out}) } -// loadCurrentSessionVector returns the user's most recent active session -// vector, or a Seed=true sentinel if none exists / the column is NULL / -// the JSON fails to unmarshal. Sentinel short-circuits ContextualMatchScore -// to 0 so the contextual term contributes nothing in cold-start cases. -func loadCurrentSessionVector(r *http.Request, q *dbq.Queries, userID pgtype.UUID, logger *slog.Logger) recommendation.SessionVector { - raw, err := q.GetCurrentSessionVectorForUser(r.Context(), userID) - if err != nil { - // pgx.ErrNoRows is the common path: no active session yet. - if !errors.Is(err, pgx.ErrNoRows) { - logger.Warn("api: radio: load current session vector", "err", err) - } - return recommendation.SessionVector{Seed: true} - } - if len(raw) == 0 { - return recommendation.SessionVector{Seed: true} - } - var v recommendation.SessionVector - if jerr := json.Unmarshal(raw, &v); jerr != nil { - logger.Warn("api: radio: bad session_vector_at_play json", "err", jerr) - return recommendation.SessionVector{Seed: true} - } - return v -} - -// latestDeviceClass returns the device_class of the user's most recent play as -// the "current device" for context conditioning, or "" when unknown -// (no plays yet, or the latest play predates device capture). Best-effort: a -// lookup failure yields a device-agnostic ("") affinity cell. -func latestDeviceClass(ctx context.Context, q *dbq.Queries, userID pgtype.UUID, logger *slog.Logger) string { - dc, err := q.GetLatestPlayDeviceClassForUser(ctx, userID) - if err != nil { - if !errors.Is(err, pgx.ErrNoRows) { - logger.Warn("api: radio: latest device class", "err", err) - } - return "" - } - if dc == nil { - return "" - } - return *dc +// picker is the shared chooser behind radio, with this server's tuning +// (recsettings.Service.Picker). +func (h *handlers) picker() *recommendation.Picker { + return h.recSettings.Picker(recsettings.PickerConfig{ + RecentlyPlayedHours: h.recCfg.RecentlyPlayedHours, + MaxLength: h.recCfg.RadioSizeMax, + Rand: h.rng, + LibrarySize: h.librarySize, + Logger: h.logger, + }) } // parseExcludeParam parses a comma-separated list of UUIDs from the diff --git a/internal/api/radio_test.go b/internal/api/radio_test.go index 90720559..5f140101 100644 --- a/internal/api/radio_test.go +++ b/internal/api/radio_test.go @@ -7,8 +7,8 @@ import ( "net/http/httptest" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/recommendation" ) func callRadio(h *handlers, user dbq.User, query string) *httptest.ResponseRecorder { @@ -66,24 +66,6 @@ func TestHandleRadio_Typical_SeedFirstPlusPicks(t *testing.T) { } } -func TestHandleRadio_UnknownSeedIs404(t *testing.T) { - h, pool := testHandlers(t) - user := seedUser(t, pool, "alice", "x", false) - w := callRadio(h, user, "seed_track=00000000-0000-0000-0000-000000000000") - if w.Code != http.StatusNotFound { - t.Errorf("status = %d", w.Code) - } -} - -func TestHandleRadio_BadSeedIs400(t *testing.T) { - h, pool := testHandlers(t) - user := seedUser(t, pool, "alice", "x", false) - w := callRadio(h, user, "seed_track=not-a-uuid") - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d", w.Code) - } -} - func TestHandleRadio_MissingSeedIs400(t *testing.T) { h, pool := testHandlers(t) user := seedUser(t, pool, "alice", "x", false) @@ -273,6 +255,12 @@ func TestHandleRadio_ContextualMatch_BoostsRankingOverControl(t *testing.T) { // Insert a contextual_like on the target track whose stored vector matches // the rock vibe. Direct DB insert — we want full control over the vector // for this test. + // Both are liked (only a liked song's captured context counts), so the + // like itself favours neither and the contextual match is what differs. + if _, err := pool.Exec(context.Background(), + `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2), ($1, $3)`, user.ID, target.ID, control.ID); err != nil { + t.Fatalf("like target and control: %v", err) + } if _, err := pool.Exec(context.Background(), `INSERT INTO contextual_likes (user_id, track_id, session_vector) VALUES ($1, $2, $3)`, user.ID, target.ID, rockVecJSON); err != nil { diff --git a/internal/api/replay_gain.go b/internal/api/replay_gain.go index c2807031..e6632c99 100644 --- a/internal/api/replay_gain.go +++ b/internal/api/replay_gain.go @@ -4,9 +4,9 @@ import ( "net/http" "strings" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/library" ) // maxReplayGainIDs caps one lookup. A player asks for the tracks around the diff --git a/internal/api/replay_gain_test.go b/internal/api/replay_gain_test.go index 150997bf..4b7e9dca 100644 --- a/internal/api/replay_gain_test.go +++ b/internal/api/replay_gain_test.go @@ -10,14 +10,14 @@ import ( "github.com/go-chi/chi/v5" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func TestGetReplayGain(t *testing.T) { h, pool := testHandlers(t) user := seedUser(t, pool, "rg1", "pw", false) - measured, _ := seedTrackForRemoveTest(t, h, "rg-measured", "", "") - unmeasured, _ := seedTrackForRemoveTest(t, h, "rg-unmeasured", "", "") + measured, _ := seedTrackOnDiskWithMBIDs(t, h, "rg-measured", "", "") + unmeasured, _ := seedTrackOnDiskWithMBIDs(t, h, "rg-unmeasured", "", "") lufs, peak := float32(-12.5), float32(-1) if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{ TrackID: measured.ID, IntegratedLufs: &lufs, TruePeakDbtp: &peak, AnalysisVersion: 1, diff --git a/internal/api/requests.go b/internal/api/requests.go deleted file mode 100644 index 887da75b..00000000 --- a/internal/api/requests.go +++ /dev/null @@ -1,264 +0,0 @@ -package api - -import ( - "context" - "errors" - "net/http" - - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - "git.fabledsword.com/bvandeusen/minstrel/internal/requests" -) - -// requestView is the JSON shape returned by all /api/requests handlers. -// Field names follow the lowercase snake_case convention for /api/* responses. -type requestView struct { - ID pgtype.UUID `json:"id"` - UserID pgtype.UUID `json:"user_id"` - // Username names the requester. Only the admin list fills it; a user's - // own /requests page has no need to name them back to themselves. - Username string `json:"username,omitempty"` - Status string `json:"status"` - Kind string `json:"kind"` - ArtistMBID string `json:"artist_mbid"` - AlbumMBID *string `json:"album_mbid,omitempty"` - TrackMBID *string `json:"track_mbid,omitempty"` - ArtistName string `json:"artist_name"` - AlbumTitle *string `json:"album_title,omitempty"` - TrackTitle *string `json:"track_title,omitempty"` - DecidedAt pgtype.Timestamptz `json:"decided_at,omitempty"` - DecidedBy pgtype.UUID `json:"decided_by,omitempty"` - Notes *string `json:"notes,omitempty"` - CompletedAt pgtype.Timestamptz `json:"completed_at,omitempty"` - MatchedTrackID pgtype.UUID `json:"matched_track_id,omitempty"` - MatchedAlbumID pgtype.UUID `json:"matched_album_id,omitempty"` - MatchedArtistID pgtype.UUID `json:"matched_artist_id,omitempty"` - RequestedAt pgtype.Timestamptz `json:"requested_at"` - UpdatedAt pgtype.Timestamptz `json:"updated_at"` - // Progress counters, computed at response time from the matched - // entity's children. 0 when nothing has been ingested yet (or when - // the request has no matched entity yet). For artist requests both - // counters fill; for album/track requests only ImportedTrackCount. - ImportedAlbumCount int `json:"imported_album_count"` - ImportedTrackCount int `json:"imported_track_count"` -} - -func requestViewFrom(row dbq.Request) requestView { - return requestView{ - ID: row.ID, - UserID: row.UserID, - Status: string(row.Status), - Kind: string(row.Kind), - ArtistMBID: row.ArtistMbid, - AlbumMBID: row.AlbumMbid, - TrackMBID: row.TrackMbid, - ArtistName: row.ArtistName, - AlbumTitle: row.AlbumTitle, - TrackTitle: row.TrackTitle, - DecidedAt: row.DecidedAt, - DecidedBy: row.DecidedBy, - Notes: row.Notes, - CompletedAt: row.CompletedAt, - MatchedTrackID: row.MatchedTrackID, - MatchedAlbumID: row.MatchedAlbumID, - MatchedArtistID: row.MatchedArtistID, - RequestedAt: row.RequestedAt, - UpdatedAt: row.UpdatedAt, - } -} - -// fillProgress fills ImportedAlbumCount + ImportedTrackCount on a view by -// querying the count of children for the request's matched entity. -// -// kind=artist → counts all albums + tracks under the matched artist. -// kind=album → counts tracks under the matched album. -// kind=track → ImportedTrackCount = 1 once matched_track_id is set. -// -// N+1 against the request list: acceptable at admin scale (dozens of -// in-flight requests at most). Errors are swallowed — progress is a -// reporting nicety, not a correctness gate. -func fillProgress(ctx context.Context, q *dbq.Queries, row dbq.Request, view *requestView) { - switch row.Kind { - case dbq.RequestKindArtist: - if !row.MatchedArtistID.Valid { - return - } - if n, err := q.CountAlbumsByArtist(ctx, row.MatchedArtistID); err == nil { - view.ImportedAlbumCount = int(n) - } - if n, err := q.CountTracksByArtist(ctx, row.MatchedArtistID); err == nil { - view.ImportedTrackCount = int(n) - } - case dbq.RequestKindAlbum: - if !row.MatchedAlbumID.Valid { - return - } - view.ImportedAlbumCount = 1 - if n, err := q.CountTracksByAlbum(ctx, row.MatchedAlbumID); err == nil { - view.ImportedTrackCount = int(n) - } - case dbq.RequestKindTrack: - if row.MatchedTrackID.Valid { - view.ImportedTrackCount = 1 - } - } -} - -// createRequestBody is the decoded JSON for POST /api/requests. album_mbid -// is the album's MusicBrainz release group, as catalogue search returns it. -type createRequestBody struct { - Kind string `json:"kind"` - ArtistMBID string `json:"artist_mbid"` - AlbumMBID string `json:"album_mbid"` - TrackMBID string `json:"track_mbid"` - ArtistName string `json:"artist_name"` - AlbumTitle string `json:"album_title"` - TrackTitle string `json:"track_title"` -} - -// handleCreateRequest implements POST /api/requests. -func (h *handlers) handleCreateRequest(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - - var body createRequestBody - if !decodeBody(w, r, &body) { - return - } - - row, created, err := h.requests.CreateTracked(r.Context(), user.ID, requests.CreateParams{ - Kind: body.Kind, - ArtistMBID: body.ArtistMBID, - AlbumMBID: body.AlbumMBID, - TrackMBID: body.TrackMBID, - ArtistName: body.ArtistName, - AlbumTitle: body.AlbumTitle, - TrackTitle: body.TrackTitle, - }) - if err != nil { - if errors.Is(err, requests.ErrInvalidKindFields) { - writeErr(w, apierror.BadRequest("mbid_required", err.Error())) - return - } - h.logger.Error("api: create request", "err", err) - writeErr(w, apierror.InternalMsg("create failed", err)) - return - } - - // Auto-approve: when an admin has set the user's - // auto_approve_requests flag, the new request goes straight onto the - // wanted list as if approved. A failure leaves it pending for an admin, - // the same as a manual approval hitting the same error. The approver is - // the user themselves, acting under the privilege the admin granted; the - // grant is in audit_log (ActionAutoApproveToggle). - if user.AutoApproveRequests { - approved, aerr := h.requests.Approve(r.Context(), row.ID, user.ID, pgtype.UUID{}) - if aerr == nil { - row = approved - } else { - h.logger.Warn("api: auto-approve failed; request stays pending", - "user_id", uuidToString(user.ID), - "request_id", uuidToString(row.ID), - "err", aerr) - } - } - - // A new request still pending after any auto-approval waits on an admin. - // One that deduped into a request already in flight was announced when it - // was first made, and the requester, if they are an admin themselves, - // needs no notice of their own request. - if created && row.Status == dbq.RequestStatusPending { - p := requestPayload(row) - p.Actor = userLabel(user) - h.notifier.NotifyLogged(r.Context(), notifications.KindRequestPending, notifications.ToAdmins(user.ID), p.Map()) - } - - h.publishRequestStatusChanged(row) - writeJSON(w, http.StatusCreated, requestViewFrom(row)) -} - -// handleListRequests implements GET /api/requests — returns caller's own -// requests. -func (h *handlers) handleListRequests(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - - rows, err := h.requests.ListForUser(r.Context(), user.ID, 100) - if err != nil { - h.logger.Error("api: list requests", "err", err) - writeErr(w, apierror.InternalMsg("list failed", err)) - return - } - - q := dbq.New(h.pool) - out := make([]requestView, 0, len(rows)) - for _, row := range rows { - v := requestViewFrom(row) - fillProgress(r.Context(), q, row, &v) - out = append(out, v) - } - writeJSON(w, http.StatusOK, out) -} - -// handleGetRequest implements GET /api/requests/:id. -// The caller must own the request, or be an admin. -func (h *handlers) handleGetRequest(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - - row, apiErr := resolveByID(r, "id", dbq.New(h.pool).GetRequestByID, "request") - if apiErr != nil { - writeErr(w, apiErr) - return - } - - // Allow if caller owns the request or is an admin. - if row.UserID != user.ID && !user.IsAdmin { - writeErr(w, apierror.NotFound("request")) - return - } - - v := requestViewFrom(row) - fillProgress(r.Context(), dbq.New(h.pool), row, &v) - writeJSON(w, http.StatusOK, v) -} - -// handleCancelRequest implements DELETE /api/requests/:id. -// Cancels the caller's own pending request. -func (h *handlers) handleCancelRequest(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - - id, ok := requireURLUUID(w, r, "id") - if !ok { - return - } - - row, err := h.requests.Cancel(r.Context(), id, user.ID) - if err != nil { - switch { - case errors.Is(err, requests.ErrNotPending): - writeErr(w, apierror.Conflict("request_not_pending", "request is not pending")) - case errors.Is(err, requests.ErrNotFound): - writeErr(w, apierror.NotFound("request")) - default: - h.logger.Error("api: cancel request", "err", err) - writeErr(w, apierror.InternalMsg("cancel failed", err)) - } - return - } - - h.publishRequestStatusChanged(row) - writeJSON(w, http.StatusOK, requestViewFrom(row)) -} diff --git a/internal/api/requests_test.go b/internal/api/requests_test.go deleted file mode 100644 index 3e922eec..00000000 --- a/internal/api/requests_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package api - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" -) - -// newRequestsRouter builds a test chi router wiring the /api/requests handlers -// with chi URL params but without RequireUser middleware. Tests inject a user -// into the context manually. -func newRequestsRouter(h *handlers) chi.Router { - r := chi.NewRouter() - r.Post("/api/requests", h.handleCreateRequest) - r.Get("/api/requests", h.handleListRequests) - r.Get("/api/requests/{id}", h.handleGetRequest) - r.Delete("/api/requests/{id}", h.handleCancelRequest) - return r -} - -// withUser injects a user into the request context the same way RequireUser -// does. -func withUser(req *http.Request, user dbq.User) *http.Request { - return req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), user)) -} - -// doCreateRequest fires POST /api/requests with the given JSON body as the -// given user. -func doCreateRequest(h *handlers, user dbq.User, body string) *httptest.ResponseRecorder { - req := httptest.NewRequest(http.MethodPost, "/api/requests", bytes.NewBufferString(body)) - req.Header.Set("Content-Type", "application/json") - req = withUser(req, user) - w := httptest.NewRecorder() - newRequestsRouter(h).ServeHTTP(w, req) - return w -} - -// doListRequests fires GET /api/requests as the given user. -func doListRequests(h *handlers, user dbq.User) *httptest.ResponseRecorder { - req := httptest.NewRequest(http.MethodGet, "/api/requests", nil) - req = withUser(req, user) - w := httptest.NewRecorder() - newRequestsRouter(h).ServeHTTP(w, req) - return w -} - -// doGetRequest fires GET /api/requests/:id as the given user. -func doGetRequest(h *handlers, user dbq.User, id pgtype.UUID) *httptest.ResponseRecorder { - req := httptest.NewRequest(http.MethodGet, "/api/requests/"+uuidToString(id), nil) - req = withUser(req, user) - w := httptest.NewRecorder() - newRequestsRouter(h).ServeHTTP(w, req) - return w -} - -// doCancelRequest fires DELETE /api/requests/:id as the given user. -func doCancelRequest(h *handlers, user dbq.User, id pgtype.UUID) *httptest.ResponseRecorder { - req := httptest.NewRequest(http.MethodDelete, "/api/requests/"+uuidToString(id), nil) - req = withUser(req, user) - w := httptest.NewRecorder() - newRequestsRouter(h).ServeHTTP(w, req) - return w -} - -// createArtistRequest is a convenience wrapper that seeds a valid artist -// request via the handler and returns the parsed response. -func createArtistRequest(t *testing.T, h *handlers, user dbq.User, artistMBID, artistName string) requestView { - t.Helper() - body := fmt.Sprintf(`{"kind":"artist","artist_mbid":%q,"artist_name":%q}`, artistMBID, artistName) - w := doCreateRequest(h, user, body) - if w.Code != http.StatusCreated { - t.Fatalf("createArtistRequest: status = %d, want 201; body = %s", w.Code, w.Body.String()) - } - var rv requestView - if err := json.Unmarshal(w.Body.Bytes(), &rv); err != nil { - t.Fatalf("createArtistRequest: decode: %v; body = %s", err, w.Body.String()) - } - return rv -} - -// TestHandleCreateRequest_AutoApprove_GoesStraightOnTheWantedList verifies -// that a user with auto_approve_requests=true gets their request approved on -// creation: an artist request follows the artist at once. -func TestHandleCreateRequest_AutoApprove_GoesStraightOnTheWantedList(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - if _, err := pool.Exec(context.Background(), - "UPDATE users SET auto_approve_requests = true WHERE id = $1", alice.ID); err != nil { - t.Fatalf("set auto_approve: %v", err) - } - // Re-fetch so the User row carried into the request context has the flag. - refreshed, err := dbq.New(pool).GetUserByID(context.Background(), alice.ID) - if err != nil { - t.Fatalf("reload user: %v", err) - } - - body := `{"kind":"artist","artist_mbid":"auto-mbid-1","artist_name":"Autoband"}` - w := doCreateRequest(h, refreshed, body) - if w.Code != http.StatusCreated { - t.Fatalf("status = %d, want 201; body = %s", w.Code, w.Body.String()) - } - var rv requestView - if err := json.Unmarshal(w.Body.Bytes(), &rv); err != nil { - t.Fatalf("decode: %v", err) - } - if rv.Status != "approved" { - t.Errorf("status = %q, want approved", rv.Status) - } - if _, err := dbq.New(pool).GetFollow(context.Background(), "auto-mbid-1"); err != nil { - t.Errorf("the artist should be followed: %v", err) - } -} - -// TestHandleCreateRequest_Artist_HappyPath verifies a valid artist request -// returns 201 with kind=artist and status=pending. -func TestHandleCreateRequest_Artist_HappyPath(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - body := `{"kind":"artist","artist_mbid":"artist-mbid-1","artist_name":"The Beatles"}` - w := doCreateRequest(h, alice, body) - - if w.Code != http.StatusCreated { - t.Fatalf("status = %d, want 201; body = %s", w.Code, w.Body.String()) - } - var rv requestView - if err := json.Unmarshal(w.Body.Bytes(), &rv); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if string(rv.Kind) != "artist" { - t.Errorf("kind = %q, want artist", rv.Kind) - } - if rv.Status != "pending" { - t.Errorf("status = %q, want pending", rv.Status) - } - if rv.ArtistMBID != "artist-mbid-1" { - t.Errorf("artist_mbid = %q", rv.ArtistMBID) - } - if rv.ArtistName != "The Beatles" { - t.Errorf("artist_name = %q", rv.ArtistName) - } - if !rv.ID.Valid { - t.Error("id not set") - } -} - -// TestHandleCreateRequest_AlbumWithoutAlbumMBID_400 verifies that sending -// kind=album without album_mbid returns 400 with mbid_required. -func TestHandleCreateRequest_AlbumWithoutAlbumMBID_400(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - // Missing album_mbid and album_title. - body := `{"kind":"album","artist_mbid":"artist-mbid-1","artist_name":"The Beatles"}` - w := doCreateRequest(h, alice, body) - - if w.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) - } - var resp struct { - Error struct { - Code string `json:"code"` - } `json:"error"` - } - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if resp.Error.Code != "mbid_required" { - t.Errorf("error.code = %q, want mbid_required", resp.Error.Code) - } -} - -// TestHandleCreateRequest_TrackWithoutTrackFields_400 verifies that kind=track -// with missing track_mbid/track_title returns 400 with mbid_required. -func TestHandleCreateRequest_TrackWithoutTrackFields_400(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - // Provides album fields but misses track_mbid and track_title. - body := `{"kind":"track","artist_mbid":"artist-mbid-1","artist_name":"Beatles","album_mbid":"album-mbid-1","album_title":"Abbey Road"}` - w := doCreateRequest(h, alice, body) - - if w.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) - } - var resp struct { - Error struct { - Code string `json:"code"` - } `json:"error"` - } - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if resp.Error.Code != "mbid_required" { - t.Errorf("error.code = %q, want mbid_required", resp.Error.Code) - } -} - -// TestHandleListRequests_OnlyOwnRequests verifies alice sees only her own -// requests, not bob's. -func TestHandleListRequests_OnlyOwnRequests(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - bob := seedUser(t, pool, "bob", "pw", false) - - createArtistRequest(t, h, alice, "alice-mbid-1", "Alice Artist 1") - createArtistRequest(t, h, alice, "alice-mbid-2", "Alice Artist 2") - createArtistRequest(t, h, bob, "bob-mbid-1", "Bob Artist 1") - - w := doListRequests(h, alice) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - var results []requestView - if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if len(results) != 2 { - t.Fatalf("len(results) = %d, want 2", len(results)) - } - for _, rv := range results { - if rv.UserID != alice.ID { - t.Errorf("result belongs to wrong user: %v", rv.UserID) - } - } -} - -// TestHandleGetRequest_OwnReturns200 verifies a caller can fetch their own -// request. -func TestHandleGetRequest_OwnReturns200(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - rv := createArtistRequest(t, h, alice, "artist-mbid-get", "Get Artist") - - w := doGetRequest(h, alice, rv.ID) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - var got requestView - if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if got.ID != rv.ID { - t.Errorf("id mismatch") - } -} - -// TestHandleGetRequest_OtherUserNotAdmin_404 verifies a non-admin caller -// cannot see another user's request. -func TestHandleGetRequest_OtherUserNotAdmin_404(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - bob := seedUser(t, pool, "bob", "pw", false) - charlie := seedUser(t, pool, "charlie", "pw", false) - - rv := createArtistRequest(t, h, bob, "bob-artist-mbid", "Bob's Artist") - - // Charlie is not an admin, tries to fetch Bob's request. - w := doGetRequest(h, charlie, rv.ID) - if w.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String()) - } - var resp struct { - Error struct { - Code string `json:"code"` - } `json:"error"` - } - if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if resp.Error.Code != "request_not_found" { - t.Errorf("error.code = %q, want request_not_found", resp.Error.Code) - } -} - -// TestHandleGetRequest_OtherUserAsAdmin_200 verifies an admin can fetch any -// user's request. -func TestHandleGetRequest_OtherUserAsAdmin_200(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - bob := seedUser(t, pool, "bob", "pw", false) - admin := seedUser(t, pool, "admin", "pw", true) - - rv := createArtistRequest(t, h, bob, "bob-admin-mbid", "Bob's Artist For Admin") - - // Admin fetches Bob's request — should succeed. - w := doGetRequest(h, admin, rv.ID) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - var got requestView - if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if got.ID != rv.ID { - t.Errorf("id mismatch") - } -} - -// TestHandleCancelRequest_PendingHappyPath verifies that cancelling a pending -// request returns 200 with status=rejected. -func TestHandleCancelRequest_PendingHappyPath(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - rv := createArtistRequest(t, h, alice, "cancel-mbid-1", "Cancel Me") - - w := doCancelRequest(h, alice, rv.ID) - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - var got requestView - if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { - t.Fatalf("decode: %v; body = %s", err, w.Body.String()) - } - if got.Status != "rejected" { - t.Errorf("status = %q, want rejected", got.Status) - } -} - -// TestHandleCancelRequest_NonPending_409 verifies that cancelling an already -// rejected request returns 409 with request_not_pending. -func TestHandleCancelRequest_NonPending_409(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice", "pw", false) - rv := createArtistRequest(t, h, alice, "cancel-mbid-2", "Cancel Twice") - - // First cancel transitions to rejected. - w1 := doCancelRequest(h, alice, rv.ID) - if w1.Code != http.StatusOK { - t.Fatalf("first cancel: status = %d, want 200; body = %s", w1.Code, w1.Body.String()) - } - - // Second cancel on a now-rejected row → ErrNotPending → 409. The cancel SQL - // checks user_id = $2 AND status = 'pending'; zero rows → ErrNotPending. - // For this test we use dbq directly to reject via admin so Cancel returns - // ErrNotPending rather than the ownership miss. We already did first cancel - // so row is rejected. - w2 := doCancelRequest(h, alice, rv.ID) - if w2.Code != http.StatusConflict { - t.Fatalf("second cancel: status = %d, want 409; body = %s", w2.Code, w2.Body.String()) - } - var resp struct { - Error struct { - Code string `json:"code"` - } `json:"error"` - } - if err := json.Unmarshal(w2.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode: %v; body = %s", err, w2.Body.String()) - } - if resp.Error.Code != "request_not_pending" { - t.Errorf("error.code = %q, want request_not_pending", resp.Error.Code) - } -} - -// TestHandleCancelRequest_WrongUser_409 verifies that attempting to cancel -// another user's request returns 409 (not_pending from the ownership miss). -func TestHandleCancelRequest_WrongUser_409(t *testing.T) { - h, pool := testHandlers(t) - resetRequests(t, h) - - alice := seedUser(t, pool, "alice-cancel-owner", "pw", false) - bob := seedUser(t, pool, "bob-cancel-other", "pw", false) - - rv := createArtistRequest(t, h, alice, "cancel-wrong-user-mbid", "Alice's Artist") - - // Bob tries to cancel Alice's request: SQL WHERE user_id=bob AND - // status=pending → 0 rows. - w := doCancelRequest(h, bob, rv.ID) - if w.Code != http.StatusConflict { - t.Fatalf("status = %d, want 409; body = %s", w.Code, w.Body.String()) - } -} diff --git a/internal/api/reset_test.go b/internal/api/reset_test.go deleted file mode 100644 index fd4e4c82..00000000 --- a/internal/api/reset_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package api - -import ( - "context" - "testing" -) - -// resetRequests clears requests rows between tests. -func resetRequests(t *testing.T, h *handlers) { - t.Helper() - if _, err := h.pool.Exec(context.Background(), "DELETE FROM requests"); err != nil { - t.Fatalf("resetRequests: %v", err) - } -} diff --git a/internal/api/resolve.go b/internal/api/resolve.go index 58e85f57..e8aac880 100644 --- a/internal/api/resolve.go +++ b/internal/api/resolve.go @@ -9,7 +9,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/apierror" ) // resolveByID parses paramKey as a UUID, fetches the row via fetch, and diff --git a/internal/api/search.go b/internal/api/search.go index a0fa2765..7112d098 100644 --- a/internal/api/search.go +++ b/internal/api/search.go @@ -7,9 +7,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // handleSearch implements GET /api/search. Runs three paged facets sharing diff --git a/internal/api/search_test.go b/internal/api/search_test.go index 43f6b7b6..08a9173b 100644 --- a/internal/api/search_test.go +++ b/internal/api/search_test.go @@ -10,11 +10,11 @@ import ( func TestHandleSearch_ThreeFacets(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - artist := seedArtist(t, pool, "Beatles") - album := seedAlbum(t, pool, artist.ID, "Beatles Greatest", 1982) - seedTrack(t, pool, album.ID, artist.ID, "Beatles Jam", 1, 60_000) + artist := seedArtist(t, pool, "Copper Lanterns") + album := seedAlbum(t, pool, artist.ID, "Copper Lanterns Greatest", 1982) + seedTrack(t, pool, album.ID, artist.ID, "Copper Lanterns Jam", 1, 60_000) - req := httptest.NewRequest(http.MethodGet, "/api/search?q=beatles", nil) + req := httptest.NewRequest(http.MethodGet, "/api/search?q=copper", nil) w := httptest.NewRecorder() newLibraryRouter(h).ServeHTTP(w, req) @@ -34,13 +34,13 @@ func TestHandleSearch_ThreeFacets(t *testing.T) { if got.Tracks.Total != 1 || len(got.Tracks.Items) != 1 { t.Errorf("tracks = %+v", got.Tracks) } - if got.Artists.Items[0].Name != "Beatles" { + if got.Artists.Items[0].Name != "Copper Lanterns" { t.Errorf("artist name = %q", got.Artists.Items[0].Name) } - if got.Albums.Items[0].ArtistName != "Beatles" { + if got.Albums.Items[0].ArtistName != "Copper Lanterns" { t.Errorf("album.artist_name = %q", got.Albums.Items[0].ArtistName) } - if got.Tracks.Items[0].AlbumTitle != "Beatles Greatest" { + if got.Tracks.Items[0].AlbumTitle != "Copper Lanterns Greatest" { t.Errorf("track.album_title = %q", got.Tracks.Items[0].AlbumTitle) } } @@ -48,7 +48,7 @@ func TestHandleSearch_ThreeFacets(t *testing.T) { func TestHandleSearch_NoMatches(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) - seedArtist(t, pool, "Beatles") + seedArtist(t, pool, "Copper Lanterns") req := httptest.NewRequest(http.MethodGet, "/api/search?q=nothinghere", nil) w := httptest.NewRecorder() @@ -68,23 +68,15 @@ func TestHandleSearch_NoMatches(t *testing.T) { } } -func TestHandleSearch_EmptyQuery(t *testing.T) { +// A search with no query, or only spaces, is a 400. +func TestHandleSearch_AnEmptyQueryIs400(t *testing.T) { h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/search", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) - } -} - -func TestHandleSearch_BlankQuery(t *testing.T) { - h, _ := testHandlers(t) - req := httptest.NewRequest(http.MethodGet, "/api/search?q=%20%20", nil) - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) + for _, path := range []string{"/api/search", "/api/search?q=%20%20"} { + w := httptest.NewRecorder() + newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if w.Code != http.StatusBadRequest { + t.Errorf("%s: status = %d, want 400", path, w.Code) + } } } diff --git a/internal/api/session_lifecycle_test.go b/internal/api/session_lifecycle_test.go index ceb4ab69..4b2bc21e 100644 --- a/internal/api/session_lifecycle_test.go +++ b/internal/api/session_lifecycle_test.go @@ -12,8 +12,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/auth" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func sessionExists(t *testing.T, pool *pgxpool.Pool, id pgtype.UUID) bool { diff --git a/internal/api/suggestions.go b/internal/api/suggestions.go deleted file mode 100644 index 96cca9dd..00000000 --- a/internal/api/suggestions.go +++ /dev/null @@ -1,261 +0,0 @@ -package api - -import ( - "encoding/json" - "errors" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation" -) - -// suggestionView is the wire shape returned by GET /api/discover/suggestions. -type suggestionView struct { - MBID string `json:"mbid"` - Name string `json:"name"` - Score float64 `json:"score"` - Attribution []seedContributionView `json:"attribution"` - // MatchedTags are the candidate's tags that overlap the user's taste - // profile, strongest first — the "matches: shoegaze, melancholic" - // line. Omitted when empty, which is common: tag coverage for - // out-of-library artists is permanently partial, and the card falls back - // to the seed attribution. - MatchedTags []string `json:"matched_tags,omitempty"` - // ImageURL is Minstrel's catalogue art endpoint for the candidate - // (out-of-library artists have no local art row). It - // answers 404 when no enabled source has an image, and the client - // falls back to a placeholder. - ImageURL string `json:"image_url,omitempty"` -} - -type seedContributionView struct { - ArtistID pgtype.UUID `json:"artist_id"` - Name string `json:"name"` - Contribution float64 `json:"contribution"` - IsLiked bool `json:"is_liked"` - PlayCount int64 `json:"play_count"` -} - -// handleListSuggestions implements GET /api/discover/suggestions. -// -// Query params: -// - limit (default 12, capped at 50) -// - half_life_days (default 30) -// -// Returns 200 with a JSON array (possibly empty). Read-only; no admin gate. -func (h *handlers) handleListSuggestions(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - limit := 12 - if v := r.URL.Query().Get("limit"); v != "" { - n, err := strconv.Atoi(v) - if err != nil || n < 1 { - writeErr(w, apierror.BadRequest("bad_request", "invalid limit")) - return - } - limit = n - } - halfLife := 30.0 - if v := r.URL.Query().Get("half_life_days"); v != "" { - f, err := strconv.ParseFloat(v, 64) - if err != nil || f <= 0 { - writeErr(w, apierror.BadRequest("bad_request", "invalid half_life_days")) - return - } - halfLife = f - } - - // Read the tuned weight per request so an admin change takes effect on the - // next refresh, no restart. - tagWeight := h.recSettings.Discover().TagOverlapWeight - suggestions, err := recommendation.SuggestArtists( - r.Context(), h.pool, user.ID, halfLife, limit, tagWeight) - if err != nil { - h.logger.Error("api: list suggestions", "err", err) - writeErr(w, apierror.InternalMsg("failed to load suggestions", err)) - return - } - - out := make([]suggestionView, 0, len(suggestions)) - for _, s := range suggestions { - attr := make([]seedContributionView, 0, len(s.Attribution)) - for _, a := range s.Attribution { - attr = append(attr, seedContributionView{ - ArtistID: a.ArtistID, - Name: a.Name, - Contribution: a.Contribution, - IsLiked: a.IsLiked, - PlayCount: a.PlayCount, - }) - } - out = append(out, suggestionView{ - MBID: s.MBID, Name: s.Name, Score: s.Score, Attribution: attr, - MatchedTags: s.MatchedTags, - }) - } - resolveSuggestionArt(out) - writeJSON(w, http.StatusOK, out) -} - -// maxSnoozeDays caps a client-supplied duration. The DEFAULT is not here: it's -// a DB-backed knob on the admin tuning card, read per request via -// recSettings.Discover().SnoozeDays. -const maxSnoozeDays = 365.0 - -// snoozeRequest is the POST body. Both fields are optional in the JSON sense -// (an absent body snoozes for the default), but Name is required in practice: -// candidates are out-of-library, so the server has no artists row to resolve a -// display name from and the un-snooze list would have nothing to show. The -// client always has it — it just rendered the card. -type snoozeRequest struct { - Name string `json:"name"` - Days float64 `json:"days"` -} - -// snoozeView is one row of GET /api/discover/snoozes. -type snoozeView struct { - MBID string `json:"mbid"` - Name string `json:"name"` - SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"` - CreatedAt pgtype.Timestamptz `json:"created_at"` -} - -// handleSnoozeSuggestion implements -// POST /api/discover/suggestions/{mbid}/snooze. -// -// Parks a candidate for `days` (default 90, capped at 365). Idempotent: -// snoozing an already-snoozed candidate extends it rather than conflicting. -// -// This is NOT negative feedback. It records no verdict on the artist and is -// never read by internal/taste — see 0049_suggestion_snoozes.up.sql for why. -// Returns 204. -func (h *handlers) handleSnoozeSuggestion(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - mbid := strings.TrimSpace(chi.URLParam(r, "mbid")) - if mbid == "" { - writeErr(w, apierror.BadRequest("invalid_id", "missing mbid")) - return - } - - // An empty body is a valid "snooze this for the default period", so EOF - // is not an error here — decodeBody would reject it as a malformed body. - var body snoozeRequest - if err := json.NewDecoder(r.Body).Decode(&body); err != nil && !errors.Is(err, io.EOF) { - writeErr(w, apierror.BadRequest("invalid_body", "")) - return - } - name := strings.TrimSpace(body.Name) - if name == "" { - writeErr(w, apierror.BadRequest("invalid_body", "name is required")) - return - } - days := body.Days - if days <= 0 { - days = h.recSettings.Discover().SnoozeDays - } - if days > maxSnoozeDays { - // Clamp rather than reject: a client asking for longer than we allow - // still means "park this", and failing the write would leave the card - // sitting there as if the tap did nothing. - days = maxSnoozeDays - } - - q := dbq.New(h.pool) - if err := q.SnoozeSuggestion(r.Context(), dbq.SnoozeSuggestionParams{ - UserID: user.ID, - CandidateMbid: mbid, - CandidateName: name, - Column4: days, - }); err != nil { - h.logger.Error("api: snooze suggestion", "err", err) - writeErr(w, apierror.InternalMsg("failed to snooze suggestion", err)) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// handleUnsnoozeSuggestion implements -// DELETE /api/discover/suggestions/{mbid}/snooze. -// -// Brings a parked candidate back immediately. 404s an MBID this user never -// snoozed, so the client can tell "undone" from "there was nothing there". -func (h *handlers) handleUnsnoozeSuggestion(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - mbid := strings.TrimSpace(chi.URLParam(r, "mbid")) - if mbid == "" { - writeErr(w, apierror.BadRequest("invalid_id", "missing mbid")) - return - } - q := dbq.New(h.pool) - rows, err := q.UnsnoozeSuggestion(r.Context(), dbq.UnsnoozeSuggestionParams{ - UserID: user.ID, - CandidateMbid: mbid, - }) - if err != nil { - h.logger.Error("api: unsnooze suggestion", "err", err) - writeErr(w, apierror.InternalMsg("failed to unsnooze suggestion", err)) - return - } - if rows == 0 { - writeErr(w, apierror.NotFound("snooze")) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// handleListSuggestionSnoozes implements GET /api/discover/snoozes. -// -// The un-snooze surface needs this: a parked candidate is by definition -// absent from the suggestion deck, so without a list there is no way to -// reach the DELETE above. Scoped to the caller. Expired rows are -// already filtered by the query — the hourly gc sweep only reclaims space. -func (h *handlers) handleListSuggestionSnoozes(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { - return - } - rows, err := dbq.New(h.pool).ListActiveSuggestionSnoozes(r.Context(), user.ID) - if err != nil { - h.logger.Error("api: list suggestion snoozes", "err", err) - writeErr(w, apierror.InternalMsg("failed to load snoozes", err)) - return - } - out := make([]snoozeView, 0, len(rows)) - for _, row := range rows { - out = append(out, snoozeView{ - MBID: row.CandidateMbid, - Name: row.CandidateName, - SnoozedUntil: row.SnoozedUntil, - CreatedAt: row.CreatedAt, - }) - } - writeJSON(w, http.StatusOK, out) -} - -// resolveSuggestionArt points each suggestion's ImageURL at Minstrel's -// catalogue art endpoint. Nothing is fetched here: the image is -// looked up from the enabled cover-art sources when the browser asks for it, -// and kept, so listing suggestions makes no outbound call. A candidate with -// no MBID keeps an empty ImageURL and the client renders its placeholder. -func resolveSuggestionArt(views []suggestionView) { - for i := range views { - if views[i].MBID != "" { - views[i].ImageURL = artistArtURL(views[i].MBID, views[i].Name) - } - } -} diff --git a/internal/api/suggestions_test.go b/internal/api/suggestions_test.go deleted file mode 100644 index be7bb5de..00000000 --- a/internal/api/suggestions_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" -) - -func newSuggestionsRouter(h *handlers) chi.Router { - r := chi.NewRouter() - r.Get("/api/discover/suggestions", h.handleListSuggestions) - return r -} - -func doListSuggestions(h *handlers, user dbq.User, query string) *httptest.ResponseRecorder { - url := "/api/discover/suggestions" - if query != "" { - url += "?" + query - } - req := httptest.NewRequest(http.MethodGet, url, nil) - req = withUser(req, user) - w := httptest.NewRecorder() - newSuggestionsRouter(h).ServeHTTP(w, req) - return w -} - -func TestSuggestions_HappyPath(t *testing.T) { - h, pool := testHandlers(t) - user := seedUser(t, pool, "alice", "pw", false) - - q := dbq.New(pool) - seed, err := q.UpsertArtist(context.Background(), dbq.UpsertArtistParams{ - Name: "Seed", SortName: "Seed", - }) - if err != nil { - t.Fatalf("UpsertArtist: %v", err) - } - if _, err := pool.Exec(context.Background(), - `INSERT INTO general_likes_artists (user_id, artist_id) VALUES ($1, $2)`, - user.ID, seed.ID, - ); err != nil { - t.Fatalf("like artist: %v", err) - } - if err := q.UpsertArtistSimilarityUnmatched(context.Background(), dbq.UpsertArtistSimilarityUnmatchedParams{ - SeedArtistID: seed.ID, - CandidateMbid: "out-mbid", - CandidateName: "Outsider", - Score: 0.9, - Source: "listenbrainz", - }); err != nil { - t.Fatalf("UpsertArtistSimilarityUnmatched: %v", err) - } - - w := doListSuggestions(h, user, "") - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - var got []suggestionView - if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { - t.Fatalf("decode: %v", err) - } - if len(got) != 1 { - t.Fatalf("len = %d, want 1; body = %s", len(got), w.Body.String()) - } - if got[0].MBID != "out-mbid" || got[0].Name != "Outsider" { - t.Errorf("got = %+v", got[0]) - } - if len(got[0].Attribution) != 1 || got[0].Attribution[0].Name != "Seed" { - t.Errorf("attribution = %+v, want one entry named Seed", got[0].Attribution) - } - if !got[0].Attribution[0].IsLiked { - t.Errorf("attribution.IsLiked = false, want true") - } -} - -func TestSuggestions_EmptyForNewUser(t *testing.T) { - h, pool := testHandlers(t) - user := seedUser(t, pool, "newbie", "pw", false) - - w := doListSuggestions(h, user, "") - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) - } - body := w.Body.String() - if body != "[]" && body != "[]\n" { - t.Errorf("body = %q, want []", body) - } -} - -func TestSuggestions_BadLimit(t *testing.T) { - h, pool := testHandlers(t) - user := seedUser(t, pool, "alice", "pw", false) - - w := doListSuggestions(h, user, "limit=not-a-number") - if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400; body = %s", w.Code, w.Body.String()) - } -} diff --git a/internal/api/types.go b/internal/api/types.go index b68594c5..fb0ce9df 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -42,9 +42,10 @@ type Page[T any] struct { // ArtistRef is the lightweight artist shape used in lists and search results. // SortName is exposed so the SPA's alphabetical-grid divider can group rows -// by the catalogue sort order ("The Beatles" → "B"). CoverURL is derived from -// a representative album (most-recent with cover_art_path); empty when the -// artist's discography has no cover art. +// by the catalogue sort order ("The Copper Lanterns" → "C"). CoverURL is the +// artist's picture (/api/artists/{id}/image) when one was fetched, else a +// representative album's cover (most-recent with cover_art_path) where the +// listing looks one up; empty when there is neither. type ArtistRef struct { ID string `json:"id"` Name string `json:"name"` diff --git a/internal/apierror/apierror.go b/internal/apierror/apierror.go index 7d776809..9a01b7e1 100644 --- a/internal/apierror/apierror.go +++ b/internal/apierror/apierror.go @@ -1,8 +1,10 @@ package apierror import ( + "encoding/json" "errors" "fmt" + "net/http" ) type Error struct { @@ -75,3 +77,36 @@ var ( ErrForbidden = &Error{Status: 403, Code: "forbidden", Message: "forbidden"} ErrUnauthorized = &Error{Status: 401, Code: "unauthorized", Message: "authentication required"} ) + +// New returns an Error with any status, code and message, for the cases the +// named constructors don't cover (a 404 with its own code, say). +func New(status int, code, message string) *Error { + return &Error{Status: status, Code: code, Message: message} +} + +// Body is the one error envelope every native /api response uses: +// +// {"error": {"code": "...", "message": "..."}} +// +// The code is stable and is what clients map to their own copy; the message +// is English for logs and for codes a client doesn't know. Subsonic's /rest +// keeps its own envelope, which its apps expect. +type Body struct { + Error Payload `json:"error"` +} + +// Payload is the inside of Body. +type Payload struct { + Code string `json:"code"` + Message string `json:"message"` +} + +// Write answers err in the Body envelope. If err is or wraps an *Error, its +// Status, Code and Message are used; anything else is a 500 server_error, so +// an internal error's text never reaches the client. +func Write(w http.ResponseWriter, err error) { + apiErr := From(err) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(apiErr.Status) + _ = json.NewEncoder(w).Encode(Body{Error: Payload{Code: apiErr.Code, Message: apiErr.Message}}) +} diff --git a/internal/apierror/apierror_test.go b/internal/apierror/apierror_test.go index 1d8ac0f9..2969c1bf 100644 --- a/internal/apierror/apierror_test.go +++ b/internal/apierror/apierror_test.go @@ -1,22 +1,25 @@ package apierror import ( + "encoding/json" "errors" "fmt" + "net/http/httptest" + "reflect" "testing" ) -func TestError_ErrorString_NoCause(t *testing.T) { - e := &Error{Message: "x"} - if got := e.Error(); got != "x" { - t.Fatalf("Error() = %q, want %q", got, "x") - } -} - -func TestError_ErrorString_WithCause(t *testing.T) { - e := &Error{Message: "x", Cause: errors.New("y")} - if got := e.Error(); got != "x: y" { - t.Fatalf("Error() = %q, want %q", got, "x: y") +func TestError_ErrorString(t *testing.T) { + for _, tc := range []struct { + e *Error + want string + }{ + {&Error{Message: "x"}, "x"}, + {&Error{Message: "x", Cause: errors.New("y")}, "x: y"}, + } { + if got := tc.e.Error(); got != tc.want { + t.Errorf("Error() = %q, want %q", got, tc.want) + } } } @@ -33,46 +36,23 @@ func TestError_Unwrap(t *testing.T) { } } -func TestFrom_NilReturnsNil(t *testing.T) { +// From turns any error into the answer a handler writes: nil stays nil, an +// *Error (wrapped or not) is kept as it is, and anything else is a 500 that +// keeps the error as its cause for the log. +func TestFrom(t *testing.T) { if got := From(nil); got != nil { - t.Fatalf("From(nil) = %v, want nil", got) + t.Errorf("From(nil) = %v, want nil", got) } -} - -func TestFrom_PreservesAPIError(t *testing.T) { orig := NotFound("track") - got := From(orig) - if got != orig { - t.Fatalf("From(orig) returned different pointer: got %p, want %p", got, orig) + if got := From(orig); got != orig { + t.Errorf("From(*Error) = %p, want the same %p", got, orig) } -} - -func TestFrom_PreservesWrappedAPIError(t *testing.T) { - inner := NotFound("track") - wrapped := fmt.Errorf("ctx: %w", inner) - got := From(wrapped) - if got == nil { - t.Fatal("From(wrapped) = nil, want *Error") + if got := From(fmt.Errorf("ctx: %w", orig)); got != orig { + t.Errorf("From(wrapped *Error) = %v, want the *Error it wraps", got) } - if got.Code != "track_not_found" { - t.Fatalf("got.Code = %q, want %q", got.Code, "track_not_found") - } -} - -func TestFrom_WrapsPlainError(t *testing.T) { plain := errors.New("boom") - got := From(plain) - if got == nil { - t.Fatal("From(plain) = nil, want *Error") - } - if got.Status != 500 { - t.Errorf("Status = %d, want 500", got.Status) - } - if got.Code != "server_error" { - t.Errorf("Code = %q, want %q", got.Code, "server_error") - } - if got.Cause != plain { - t.Errorf("Cause = %v, want %v", got.Cause, plain) + if got := From(plain); got == nil || got.Status != 500 || got.Code != "server_error" || got.Cause != plain { + t.Errorf("From(plain) = %+v, want a 500 server_error caused by it", got) } } @@ -171,3 +151,33 @@ func TestSentinels_Identity(t *testing.T) { t.Fatalf("recovered error pointer = %p, want %p", apiErr, ErrNotFound) } } + +// Write sends the status and a JSON body holding exactly the code and the +// message. A plain error goes out as a 500 whose message hides its text. +func TestWrite_SendsTheEnvelopeAndHidesAPlainErrorsText(t *testing.T) { + for _, tc := range []struct { + err error + status int + code, message string + }{ + {fmt.Errorf("ctx: %w", NotFound("track")), 404, "track_not_found", "track not found"}, + {errors.New("boom: secret detail"), 500, "server_error", "internal server error"}, + } { + rec := httptest.NewRecorder() + Write(rec, tc.err) + if rec.Code != tc.status { + t.Errorf("%v: status = %d, want %d", tc.err, rec.Code, tc.status) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/json" { + t.Errorf("%v: Content-Type = %q, want application/json", tc.err, ct) + } + var raw map[string]map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil { + t.Fatalf("%v: body is not the envelope: %v (%s)", tc.err, err, rec.Body.String()) + } + want := map[string]map[string]string{"error": {"code": tc.code, "message": tc.message}} + if !reflect.DeepEqual(raw, want) { + t.Errorf("%v: body = %v, want %v", tc.err, raw, want) + } + } +} diff --git a/internal/audit/audit.go b/internal/audit/audit.go index 07b37ba2..b62fef7a 100644 --- a/internal/audit/audit.go +++ b/internal/audit/audit.go @@ -17,7 +17,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // Action is the discriminator stored in audit_log.action. Every value is @@ -38,7 +38,6 @@ const ( ActionCreateUserAdmin Action = "create_user_admin" ActionDeleteUser Action = "delete_user" ActionPasswordResetAdmin Action = "password_reset_admin" - ActionAutoApproveToggle Action = "auto_approve_toggle" // Credentials. ActionPasswordChangeSelf Action = "password_change_self" @@ -58,15 +57,20 @@ const ( // The resolver settling a group without a merge: // dismissing two versions of a song that are not duplicates, and removing // copies that filled another song's track slot (their tracks are kept, - // marked missing, and fetched again). + // marked missing, until a good copy is in the library). ActionDuplicateDismiss Action = "duplicate_dismiss" ActionDuplicateWrongFile Action = "duplicate_wrong_file" - // An admin removing a track: its file and row are deleted, with every - // like, play and playlist entry that hung off the row. The metadata names - // the track and its file, so the log can say what went after the row is - // gone. - ActionTrackRemove Action = "track_remove" + // An admin forgetting tracks that waited for a file: each row is deleted, + // with every like, play and playlist entry that hung off it. The metadata + // names each track and the file it had, so the log can say what went after + // the rows are gone. + ActionTrackForget Action = "track_forget" + // An admin removing a suspect source's file and keeping its track, which + // waits, missing, for a clean copy. (A report's removal is recorded in + // the Reports history instead, and a duplicate's under + // duplicate_wrong_file.) + ActionSuspectFileRemove Action = "suspect_file_remove" // Subsonic password: generated in Settings for t/s-only clients. ActionSubsonicPasswordSet Action = "subsonic_password_set" diff --git a/internal/audit/audit_test.go b/internal/audit/audit_test.go index 19b0c07e..6e71f550 100644 --- a/internal/audit/audit_test.go +++ b/internal/audit/audit_test.go @@ -4,27 +4,19 @@ import ( "bytes" "context" "log/slog" - "os" "strings" "testing" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func newTestPool(t *testing.T) *pgxpool.Pool { t.Helper() - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) // Reset audit_log so each test runs against a known state. if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil { t.Fatalf("reset audit_log: %v", err) @@ -102,14 +94,7 @@ func TestWriteOrLog_Success(t *testing.T) { // closed pool, and asserts the logger captured a Warn record with // action + err keys. func TestWriteOrLog_DBFailure_Logs(t *testing.T) { - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } + pool := dbtest.Open(t) pool.Close() // force subsequent ops to fail var buf bytes.Buffer @@ -135,14 +120,7 @@ func TestWriteOrLog_DBFailure_Logs(t *testing.T) { // TestWriteOrLog_NilLogger ensures a nil logger + failing pool does // not panic. Uses a closed pool to force the failure branch. func TestWriteOrLog_NilLogger(t *testing.T) { - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } + pool := dbtest.Open(t) pool.Close() var nilUUID pgtype.UUID @@ -163,7 +141,6 @@ func TestWrite_AllActionConstantsArePersisted(t *testing.T) { audit.ActionCreateUserAdmin, audit.ActionDeleteUser, audit.ActionPasswordResetAdmin, - audit.ActionAutoApproveToggle, audit.ActionPasswordChangeSelf, audit.ActionTokenRegenerate, audit.ActionForgotPasswordInit, diff --git a/internal/auth/admin.go b/internal/auth/admin.go index 7cd9b75c..16dfdcda 100644 --- a/internal/auth/admin.go +++ b/internal/auth/admin.go @@ -1,8 +1,9 @@ package auth import ( - "encoding/json" "net/http" + + "github.com/Fabled-Sword/minstrel/internal/apierror" ) // RequireAdmin is a middleware that MUST run after RequireUser. It reads the @@ -23,23 +24,14 @@ func RequireAdmin() func(http.Handler) http.Handler { user, ok := UserFromContext(r.Context()) if !ok { // Programmer error: RequireUser was not mounted before RequireAdmin. - writeAdminErr(w, http.StatusInternalServerError, "internal_error") + apierror.Write(w, apierror.InternalMsg("admin check mounted without a user", nil)) return } if !user.IsAdmin { - writeAdminErr(w, http.StatusForbidden, "not_authorized") + apierror.Write(w, apierror.Forbidden("not_authorized", "admin access required")) return } next.ServeHTTP(w, r) }) } } - -// writeAdminErr writes a flat JSON error envelope {"error":""} and sets -// Content-Type. Uses a flat envelope (not the nested api.errorBody shape) -// because the spec for /api/admin/* errors defines {"error":""} directly. -func writeAdminErr(w http.ResponseWriter, status int, code string) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(map[string]string{"error": code}) -} diff --git a/internal/auth/admin_test.go b/internal/auth/admin_test.go index 70ef99a2..949d9d99 100644 --- a/internal/auth/admin_test.go +++ b/internal/auth/admin_test.go @@ -2,12 +2,14 @@ package auth import ( "context" + "encoding/json" "net/http" "net/http/httptest" "strings" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // injectUser returns a copy of r with the given user stored under userCtxKey. @@ -17,78 +19,54 @@ func injectUser(r *http.Request, u dbq.User) *http.Request { return r.WithContext(ctx) } -func TestRequireAdmin_AdminPasses(t *testing.T) { - called := false - stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - called = true - w.WriteHeader(http.StatusOK) - }) - - h := RequireAdmin()(stub) - - req := injectUser( - httptest.NewRequest(http.MethodGet, "/api/admin/test", nil), - dbq.User{IsAdmin: true}, - ) - w := httptest.NewRecorder() - h.ServeHTTP(w, req) - - if w.Code != http.StatusOK { - t.Errorf("status = %d, want 200", w.Code) +// assertErrorCode checks the response is the /api error envelope with code. +// Clients read only that shape, so a flat {"error":"code"} must fail here. +func assertErrorCode(t *testing.T, w *httptest.ResponseRecorder, code string) { + t.Helper() + var env apierror.Body + if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil { + t.Fatalf("body %q is not the error envelope: %v", w.Body.String(), err) } - if !called { - t.Error("stub handler was not called for admin user") + if env.Error.Code != code { + t.Errorf("error.code = %q, want %q; body %q", env.Error.Code, code, w.Body.String()) } } -func TestRequireAdmin_NonAdminReturns403(t *testing.T) { - stub := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { - t.Fatal("stub handler must not be called for non-admin user") - }) - - h := RequireAdmin()(stub) - - req := injectUser( - httptest.NewRequest(http.MethodGet, "/api/admin/test", nil), - dbq.User{IsAdmin: false}, - ) - w := httptest.NewRecorder() - h.ServeHTTP(w, req) - - if w.Code != http.StatusForbidden { - t.Errorf("status = %d, want 403", w.Code) - } - body := w.Body.String() - if !strings.Contains(body, "not_authorized") { - t.Errorf("body %q does not contain %q", body, "not_authorized") - } - ct := w.Header().Get("Content-Type") - if !strings.HasPrefix(ct, "application/json") { - t.Errorf("Content-Type = %q, want application/json", ct) - } -} - -func TestRequireAdmin_NoUserContextReturns500(t *testing.T) { - stub := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { - t.Fatal("stub handler must not be called when no user is in context") - }) - - h := RequireAdmin()(stub) - - // Do NOT inject a user — simulate RequireUser being bypassed. - req := httptest.NewRequest(http.MethodGet, "/api/admin/test", nil) - w := httptest.NewRecorder() - h.ServeHTTP(w, req) - - if w.Code != http.StatusInternalServerError { - t.Errorf("status = %d, want 500", w.Code) - } - body := w.Body.String() - if !strings.Contains(body, "internal_error") { - t.Errorf("body %q does not contain %q", body, "internal_error") - } - ct := w.Header().Get("Content-Type") - if !strings.HasPrefix(ct, "application/json") { - t.Errorf("Content-Type = %q, want application/json", ct) +// RequireAdmin passes an admin through, answers anyone else 403, and answers +// 500 when no user is in the context at all (RequireUser was not mounted in +// front of it), always as the /api error envelope. +func TestRequireAdmin(t *testing.T) { + for _, tc := range []struct { + name string + user *dbq.User + wantCode int + wantErr string // "" when the handler is reached + }{ + {"an admin", &dbq.User{IsAdmin: true}, http.StatusOK, ""}, + {"a listener", &dbq.User{}, http.StatusForbidden, "not_authorized"}, + {"no user in the context", nil, http.StatusInternalServerError, "server_error"}, + } { + t.Run(tc.name, func(t *testing.T) { + reached := false + h := RequireAdmin()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + reached = true + w.WriteHeader(http.StatusOK) + })) + req := httptest.NewRequest(http.MethodGet, "/api/admin/test", nil) + if tc.user != nil { + req = injectUser(req, *tc.user) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != tc.wantCode || reached != (tc.wantErr == "") { + t.Fatalf("status %d, handler reached %v; want %d, %v", w.Code, reached, tc.wantCode, tc.wantErr == "") + } + if tc.wantErr != "" { + assertErrorCode(t, w, tc.wantErr) + if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { + t.Errorf("Content-Type = %q, want application/json", ct) + } + } + }) } } diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go index 139bf1f7..7631aa73 100644 --- a/internal/auth/middleware.go +++ b/internal/auth/middleware.go @@ -5,7 +5,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) type ctxKey int diff --git a/internal/auth/ratelimit.go b/internal/auth/ratelimit.go index 849aad73..523a807f 100644 --- a/internal/auth/ratelimit.go +++ b/internal/auth/ratelimit.go @@ -50,7 +50,9 @@ func NewAttemptLimiter(max int, window time.Duration) *AttemptLimiter { // Blocked reports whether key has used its attempts for the current window, // and if so how long until the window resets. It records nothing, so a check -// can run before the expensive work and the outcome be recorded after. +// can run before the expensive work and a failure be recorded after, which is +// the shape for a limit that counts only failures. Where every attempt +// counts, Allow checks and counts in one step. func (l *AttemptLimiter) Blocked(key string) (bool, time.Duration) { if l == nil || key == "" { return false, 0 @@ -72,6 +74,31 @@ func (l *AttemptLimiter) Blocked(key string) (bool, time.Duration) { return true, b.start.Add(l.window).Sub(now) } +// Allow counts one attempt against key and reports whether it was within the +// limit, and if not how long until the window resets. The check and the count +// happen together under the lock, so a burst of parallel requests cannot all +// read the count before any of them adds to it. A refused attempt is not +// counted. +func (l *AttemptLimiter) Allow(key string) (bool, time.Duration) { + if l == nil || key == "" { + return true, 0 + } + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + b, ok := l.buckets[key] + if !ok || now.Sub(b.start) >= l.window { + l.buckets[key] = &attemptBucket{count: 1, start: now} + l.maybeSweep(now) + return true, 0 + } + if b.count >= l.max { + return false, b.start.Add(l.window).Sub(now) + } + b.count++ + return true, 0 +} + // Record counts one attempt against key. func (l *AttemptLimiter) Record(key string) { if l == nil || key == "" { diff --git a/internal/auth/ratelimit_test.go b/internal/auth/ratelimit_test.go index 6560fb74..6428c35b 100644 --- a/internal/auth/ratelimit_test.go +++ b/internal/auth/ratelimit_test.go @@ -1,6 +1,8 @@ package auth import ( + "sync" + "sync/atomic" "testing" "time" ) @@ -112,3 +114,34 @@ func TestLoginGuard_AddressLimitSpansAccounts(t *testing.T) { t.Fatal("a success must not clear the address count") } } + +// A parallel burst on one key gets exactly max attempts through: the check +// and the count are one step, so no request reads the count before another +// has added to it. +func TestAttemptLimiter_AllowAdmitsExactlyMaxFromAParallelBurst(t *testing.T) { + l, c := newTestLimiter(10, time.Hour) + var allowed atomic.Int32 + var wg sync.WaitGroup + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if ok, _ := l.Allow("k"); ok { + allowed.Add(1) + } + }() + } + wg.Wait() + if n := allowed.Load(); n != 10 { + t.Fatalf("allowed %d of a 100-request burst, want exactly 10", n) + } + c.t = c.t.Add(20 * time.Minute) + ok, wait := l.Allow("k") + if ok || wait != 40*time.Minute { + t.Fatalf("Allow past the limit = %v, wait %v; want refused with the 40m left", ok, wait) + } + c.t = c.t.Add(40 * time.Minute) + if ok, _ := l.Allow("k"); !ok { + t.Fatal("refused once the window had passed") + } +} diff --git a/internal/auth/session.go b/internal/auth/session.go index 2d4c45df..c0ad1a32 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -15,7 +15,8 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/crypto/bcrypt" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/apierror" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // sessionTokenBytes is the raw entropy per session token. 32 bytes of @@ -62,10 +63,14 @@ func VerifyPassword(hash, plaintext string) bool { // that issue/clear the cookie (handleLogin / handleLogout) need to match it. const SessionCookieName = "minstrel_session" +// errUnauthenticated is the answer to a request with no session, or one +// that has ended. Clients sign out on any 401. +var errUnauthenticated = apierror.Unauthorized("unauthenticated", "sign in to continue") + // RequireUser resolves the caller from a session cookie OR Authorization // bearer header and puts the dbq.User in request context via userCtxKey. -// Requests without a valid session return 401 with no body so callers don't -// leak whether the username existed (matches the /rest/* auth posture). +// Every request without a valid session gets the same 401 unauthenticated, +// so a caller can't tell a missing session from a deleted user. // // trustedHops supplies the reverse-proxy depth used to record the session's // current address. It's a func rather than an int because the value @@ -77,7 +82,7 @@ func RequireUser(pool *pgxpool.Pool, trustedHops func() int) func(http.Handler) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := sessionTokenFromRequest(r) if token == "" { - http.Error(w, "unauthenticated", http.StatusUnauthorized) + apierror.Write(w, errUnauthenticated) return } if pool == nil { @@ -85,18 +90,18 @@ func RequireUser(pool *pgxpool.Pool, trustedHops func() int) func(http.Handler) // the middleware with nil pool to prove the no-token case // short-circuits without a DB call. Any real token here is // programmer error. - http.Error(w, "unauthenticated", http.StatusUnauthorized) + apierror.Write(w, errUnauthenticated) return } q := dbq.New(pool) sess, err := q.GetSessionByTokenHash(r.Context(), HashSessionToken(token)) if err != nil { if errors.Is(err, pgx.ErrNoRows) { - http.Error(w, "unauthenticated", http.StatusUnauthorized) + apierror.Write(w, errUnauthenticated) return } slog.Error("api: session lookup failed", "err", err) - http.Error(w, "auth lookup failed", http.StatusInternalServerError) + apierror.Write(w, apierror.InternalMsg("auth lookup failed", err)) return } user, err := q.GetUserByID(r.Context(), sess.UserID) @@ -105,11 +110,11 @@ func RequireUser(pool *pgxpool.Pool, trustedHops func() int) func(http.Handler) // Session points at a deleted user — treat as unauth, // best-effort cleanup. _ = q.DeleteSession(r.Context(), sess.ID) - http.Error(w, "unauthenticated", http.StatusUnauthorized) + apierror.Write(w, errUnauthenticated) return } slog.Error("api: user lookup failed", "err", err) - http.Error(w, "auth lookup failed", http.StatusInternalServerError) + apierror.Write(w, apierror.InternalMsg("auth lookup failed", err)) return } // Best-effort last-seen update. A failure here shouldn't fail the diff --git a/internal/backup/archive.go b/internal/backup/archive.go new file mode 100644 index 00000000..2c725175 --- /dev/null +++ b/internal/backup/archive.go @@ -0,0 +1,226 @@ +package backup + +import ( + "archive/tar" + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strings" + "time" +) + +// The backup file is laid out so that what didn't change between two days is +// the same bytes both times, which suits a deduplicating off-site copy such as +// Fabled Archives' restic: +// +// - Never compressed. Compression rewrites every byte after the first +// change, so no chunk would match again. +// - One member per table, tables/.jsonl: one row per line, in +// primary-key order, keys sorted, no spacing. +// - What changes every run lives only in manifest.json, the first member. +// Member headers are fixed (mtime 0, owner 0, mode 0644). +// - A new dated name each run, so the target keeps a history and a sender +// only ever adds. +const ( + FormatName = "minstrel-backup-tar" + FormatVersion = 1 + + manifestName = "manifest.json" + tablesDir = "tables/" + tableSuffix = ".jsonl" + namePrefix = "minstrel-" + nameSuffix = ".tar" + + // maxMember bounds any one member a read takes in: far past the largest + // library's tracks table, small enough that a hostile file can't fill + // memory. + maxMember = 1 << 30 +) + +// Manifest is the file's first member. +type Manifest struct { + Format string `json:"format"` + FormatVersion int `json:"format_version"` + CreatedAt time.Time `json:"created_at"` + // Build is the Minstrel version that wrote the file. + Build string `json:"build"` + // Schema is the database's migration version when the file was written. + // A restore refuses a file from a newer schema than its own. + Schema int64 `json:"schema"` + // Rows is each table's row count, so a read can tell a whole member from + // a cut-off one. + Rows map[string]int `json:"rows"` +} + +// FileName is a backup's file name: minstrel-20261102T030000Z.tar, in UTC, so +// names sort by time. +func FileName(at time.Time) string { + return namePrefix + at.UTC().Format("20060102T150405Z") + nameSuffix +} + +// IsFileName reports whether a name is one FileName gives. +func IsFileName(name string) bool { + stamp, ok := strings.CutPrefix(name, namePrefix) + if !ok { + return false + } + stamp, ok = strings.CutSuffix(stamp, nameSuffix) + if !ok { + return false + } + _, err := time.Parse("20060102T150405Z", stamp) + return err == nil +} + +// Write writes c as a backup file to w and returns its manifest. +func Write(w io.Writer, c Contents, at time.Time, build string) (Manifest, error) { + names := make([]string, 0, len(c.Tables)) + m := Manifest{ + Format: FormatName, + FormatVersion: FormatVersion, + CreatedAt: at.UTC(), + Build: build, + Schema: c.Schema, + Rows: make(map[string]int, len(c.Tables)), + } + for name, lines := range c.Tables { + names = append(names, name) + m.Rows[name] = len(lines) + } + slices.Sort(names) + + manifest, err := json.MarshalIndent(m, "", " ") + if err != nil { + return m, err + } + tw := tar.NewWriter(w) + if err := member(tw, manifestName, append(manifest, '\n')); err != nil { + return m, err + } + for _, name := range names { + var body bytes.Buffer + for _, line := range c.Tables[name] { + body.Write(line) + body.WriteByte('\n') + } + if err := member(tw, tablesDir+name+tableSuffix, body.Bytes()); err != nil { + return m, err + } + } + return m, tw.Close() +} + +// WriteFile writes c into dir under its dated name. The bytes go to a hidden +// .part file first, are synced, and only then take the backup's name, so +// anything watching the folder never sees half a backup under a backup's +// name, and a run that fails leaves nothing behind. +func WriteFile(dir string, c Contents, at time.Time, build string) (string, Manifest, error) { + final := filepath.Join(dir, FileName(at)) + part := filepath.Join(dir, "."+FileName(at)+".part") + f, err := os.OpenFile(part, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + return "", Manifest{}, fmt.Errorf("backup: create %s: %w", part, err) + } + m, err := Write(f, c, at, build) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil { + err = os.Rename(part, final) + } + if err != nil { + _ = os.Remove(part) + return "", m, fmt.Errorf("backup: write %s: %w", final, err) + } + if d, err := os.Open(dir); err == nil { + _ = d.Sync() + _ = d.Close() + } + return final, m, nil +} + +func member(tw *tar.Writer, name string, data []byte) error { + hdr := &tar.Header{ + Name: name, + Mode: 0o644, + Size: int64(len(data)), + ModTime: time.Unix(0, 0), + Typeflag: tar.TypeReg, + Format: tar.FormatUSTAR, + } + if err := tw.WriteHeader(hdr); err != nil { + return err + } + _, err := tw.Write(data) + return err +} + +// Read reads a backup file, refusing anything that isn't a whole one. +func Read(r io.Reader) (Manifest, Contents, error) { + var m Manifest + c := Contents{Tables: map[string][][]byte{}} + tr := tar.NewReader(r) + first := true + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return m, c, fmt.Errorf("%w: %w", ErrNotABackup, err) + } + if hdr.Size > maxMember { + return m, c, fmt.Errorf("%w: %s is too large", ErrNotABackup, hdr.Name) + } + data, err := io.ReadAll(io.LimitReader(tr, maxMember)) + if err != nil { + return m, c, fmt.Errorf("%w: %w", ErrNotABackup, err) + } + if first { + first = false + if hdr.Name != manifestName || json.Unmarshal(data, &m) != nil || m.Format != FormatName { + return m, c, ErrNotABackup + } + if m.FormatVersion > FormatVersion { + return m, c, fmt.Errorf("%w: it was written by a newer Minstrel (format %d)", ErrNotABackup, m.FormatVersion) + } + c.Schema = m.Schema + continue + } + table, ok := strings.CutPrefix(hdr.Name, tablesDir) + if !ok { + continue + } + if table, ok = strings.CutSuffix(table, tableSuffix); !ok || table == "" { + continue + } + var lines [][]byte + for line := range bytes.SplitSeq(data, []byte("\n")) { + if len(line) == 0 { + continue + } + if !json.Valid(line) { + return m, c, fmt.Errorf("%w: a row in %s is not JSON", ErrNotABackup, table) + } + lines = append(lines, line) + } + c.Tables[table] = lines + } + if first { + return m, c, ErrNotABackup + } + for table, want := range m.Rows { + if got := len(c.Tables[table]); got != want { + return m, c, fmt.Errorf("%w: %s holds %d rows, the manifest says %d", ErrNotABackup, table, got, want) + } + } + return m, c, nil +} diff --git a/internal/backup/archive_test.go b/internal/backup/archive_test.go new file mode 100644 index 00000000..c1a02b02 --- /dev/null +++ b/internal/backup/archive_test.go @@ -0,0 +1,194 @@ +package backup + +import ( + "archive/tar" + "bytes" + "errors" + "io" + "os" + "path/filepath" + "testing" + "time" +) + +func sample() Contents { + return Contents{ + Schema: 98, + Tables: map[string][][]byte{ + "users": {[]byte(`{"id":"u1","username":"ada"}`), []byte(`{"id":"u2","username":"bo"}`)}, + "tracks": {[]byte(`{"file_path":"/music/a.flac","id":"t1"}`)}, + "playlists": {}, + }, + } +} + +func members(t *testing.T, file []byte) map[string][]byte { + t.Helper() + out := map[string][]byte{} + tr := tar.NewReader(bytes.NewReader(file)) + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + return out + } + if err != nil { + t.Fatal(err) + } + data, _ := io.ReadAll(tr) + out[hdr.Name] = data + } +} + +func TestABackupFileReadsBackAsWritten(t *testing.T) { + var buf bytes.Buffer + at := time.Date(2026, 11, 2, 3, 0, 0, 0, time.UTC) + if _, err := Write(&buf, sample(), at, "2026.11.02.0300"); err != nil { + t.Fatal(err) + } + m, c, err := Read(&buf) + if err != nil { + t.Fatal(err) + } + if m.Schema != 98 || c.Schema != 98 || m.Build != "2026.11.02.0300" || !m.CreatedAt.Equal(at) { + t.Errorf("manifest = %+v", m) + } + want := sample() + for name, lines := range want.Tables { + got := c.Tables[name] + if len(got) != len(lines) { + t.Errorf("%s: %d rows, want %d", name, len(got), len(lines)) + continue + } + for i := range lines { + if !bytes.Equal(got[i], lines[i]) { + t.Errorf("%s row %d = %s, want %s", name, i, got[i], lines[i]) + } + } + } +} + +// Two days over unchanged data differ only in the manifest, so a +// deduplicating copy stores the tables once. +func TestOnlyTheManifestChangesBetweenDays(t *testing.T) { + var day1, day2 bytes.Buffer + if _, err := Write(&day1, sample(), time.Date(2026, 11, 1, 3, 0, 0, 0, time.UTC), "a"); err != nil { + t.Fatal(err) + } + if _, err := Write(&day2, sample(), time.Date(2026, 11, 2, 3, 0, 0, 0, time.UTC), "b"); err != nil { + t.Fatal(err) + } + a, b := members(t, day1.Bytes()), members(t, day2.Bytes()) + if len(a) != 4 { + t.Fatalf("members = %d, want the manifest and three tables", len(a)) + } + for name, data := range a { + same := bytes.Equal(data, b[name]) + if name == manifestName && same { + t.Error("the manifest is identical across days; it should carry the run's time") + } + if name != manifestName && !same { + t.Errorf("%s differs between days over the same rows", name) + } + } + // The table members' bytes, headers included, sit unchanged in both files. + tracks := a[tablesDir+"tracks"+tableSuffix] + if !bytes.Contains(day1.Bytes(), tracks) || !bytes.Contains(day2.Bytes(), tracks) { + t.Error("the tracks member is not stored verbatim") + } +} + +func TestReadRefusesWhatIsNotAWholeBackup(t *testing.T) { + var good bytes.Buffer + if _, err := Write(&good, sample(), time.Now(), "x"); err != nil { + t.Fatal(err) + } + + tarOf := func(name string, data []byte) []byte { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + _ = member(tw, name, data) + _ = tw.Close() + return buf.Bytes() + } + short := func() []byte { + // The manifest promises two users; the member holds one. + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + _ = member(tw, manifestName, []byte(`{"format":"minstrel-backup-tar","format_version":1,"rows":{"users":2}}`)) + _ = member(tw, tablesDir+"users"+tableSuffix, []byte(`{"id":"u1"}`+"\n")) + _ = tw.Close() + return buf.Bytes() + } + + cases := map[string][]byte{ + "empty": nil, + "not a tar": []byte("hello"), + "cut off": good.Bytes()[:good.Len()/2], + "no manifest": tarOf(tablesDir+"users"+tableSuffix, []byte(`{"id":"u1"}`)), + "another format": tarOf(manifestName, []byte(`{"format":"fablednotary-backup-tar","format_version":1}`)), + "a newer format": tarOf(manifestName, []byte(`{"format":"minstrel-backup-tar","format_version":99}`)), + "a member short": short(), + } + for name, file := range cases { + if _, _, err := Read(bytes.NewReader(file)); !errors.Is(err, ErrNotABackup) { + t.Errorf("%s: err = %v, want ErrNotABackup", name, err) + } + } +} + +func TestWriteFileLandsUnderTheDatedNameOnly(t *testing.T) { + dir := t.TempDir() + at := time.Date(2026, 11, 2, 3, 0, 0, 0, time.UTC) + path, _, err := WriteFile(dir, sample(), at, "x") + if err != nil { + t.Fatal(err) + } + if filepath.Base(path) != "minstrel-20261102T030000Z.tar" { + t.Errorf("path = %s", path) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 1 || entries[0].Name() != filepath.Base(path) { + t.Errorf("the folder holds %v, want only the backup", entries) + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer func() { _ = f.Close() }() + if _, _, err := Read(f); err != nil { + t.Errorf("the written file doesn't read: %v", err) + } +} + +func TestAFailedWriteFileLeavesNothingBehind(t *testing.T) { + dir := filepath.Join(t.TempDir(), "missing") + if _, _, err := WriteFile(dir, sample(), time.Now(), "x"); err == nil { + t.Fatal("writing into a missing folder succeeded") + } + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Errorf("the failed write created %s", dir) + } +} + +func TestFileNamesSortByTimeAndAreRecognised(t *testing.T) { + earlier := FileName(time.Date(2026, 1, 9, 23, 0, 0, 0, time.UTC)) + // 01:00 at UTC-5 is 06:00 UTC: the name is in UTC, not the clock's zone. + later := FileName(time.Date(2026, 1, 10, 1, 0, 0, 0, time.FixedZone("x", -5*3600))) + if later != "minstrel-20260110T060000Z.tar" { + t.Errorf("name = %s, want it in UTC", later) + } + if earlier >= later { + t.Errorf("%s does not sort before %s", earlier, later) + } + for name, want := range map[string]bool{ + earlier: true, + "minstrel-20261102T030000Z.tar": true, + ".minstrel-20261102T030000Z.tar.part": false, + "minstrel-yesterday.tar": false, + "fablednotary-20261102T030000Z.tar": false, + } { + if IsFileName(name) != want { + t.Errorf("IsFileName(%q) = %v, want %v", name, !want, want) + } + } +} diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go new file mode 100644 index 00000000..6a873f90 --- /dev/null +++ b/internal/backup/backup_test.go @@ -0,0 +1,233 @@ +package backup_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "slices" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/dbtest" +) + +func index(name string) int { + return slices.IndexFunc(backup.Tables, func(t backup.Table) bool { return t.Name == name }) +} + +// Every table in the schema is backed up or excluded with a reason, so a new +// table fails here until someone decides which. +func TestEveryTableIsAccountedFor_Integration(t *testing.T) { + pool := dbtest.Pool(t) + rows, err := pool.Query(context.Background(), "SELECT tablename FROM pg_tables WHERE schemaname = 'public'") + if err != nil { + t.Fatal(err) + } + schema, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatal(err) + } + for _, p := range backup.Coverage(schema) { + t.Error(p) + } +} + +// A restore loads each table after the ones it references, and never needs a +// table the backup leaves out. +func TestTablesComeAfterWhatTheyReference_Integration(t *testing.T) { + pool := dbtest.Pool(t) + rows, err := pool.Query(context.Background(), ` + SELECT cl.relname, pc.relname + FROM pg_constraint co + JOIN pg_class cl ON cl.oid = co.conrelid + JOIN pg_class pc ON pc.oid = co.confrelid + JOIN pg_namespace n ON n.oid = cl.relnamespace + WHERE co.contype = 'f' AND n.nspname = 'public'`) + if err != nil { + t.Fatal(err) + } + type fk struct{ child, parent string } + fks, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (fk, error) { + var f fk + err := r.Scan(&f.child, &f.parent) + return f, err + }) + if err != nil { + t.Fatal(err) + } + if len(fks) == 0 { + t.Fatal("found no foreign keys; the query is wrong") + } + for _, f := range fks { + child, parent := index(f.child), index(f.parent) + if child < 0 { + continue + } + switch { + case parent < 0: + t.Errorf("%s is backed up but references %s, which is excluded", f.child, f.parent) + case parent >= child && f.parent != f.child: + t.Errorf("%s references %s, so it must come after it in Tables", f.child, f.parent) + } + } +} + +// Every omitted column exists, so a renamed column fails here rather than a +// sealed credential slipping into the file under its new name. +func TestOmittedColumnsExist_Integration(t *testing.T) { + pool := dbtest.Pool(t) + for _, tbl := range backup.Tables { + for _, col := range tbl.Omit { + var n int + if err := pool.QueryRow(context.Background(), ` + SELECT count(*) FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`, + tbl.Name, col).Scan(&n); err != nil || n != 1 { + t.Errorf("%s.%s: found %d columns, err %v", tbl.Name, col, n, err) + } + } + } +} + +func mustExec(t *testing.T, pool *pgxpool.Pool, sql string, args ...any) { + t.Helper() + if _, err := pool.Exec(context.Background(), sql, args...); err != nil { + t.Fatalf("%s: %v", sql, err) + } +} + +func mustID(t *testing.T, pool *pgxpool.Pool, sql string, args ...any) string { + t.Helper() + var id string + if err := pool.QueryRow(context.Background(), sql, args...).Scan(&id); err != nil { + t.Fatalf("%s: %v", sql, err) + } + return id +} + +// A backup restored into an emptied instance gives back the same rows, byte +// for byte, without the credentials and markers it leaves out. +func TestARestoredInstanceHoldsWhatTheBackupHeld_Integration(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + + user := mustID(t, pool, `INSERT INTO users (username, password_hash, api_token_hash, listenbrainz_token, listenbrainz_enabled) + VALUES ($1, 'hash', 'backup-token', 'lb-token', true) RETURNING id::text`, dbtest.TestUserPrefix+"backup") + artist := mustID(t, pool, `INSERT INTO artists (name, sort_name, artist_art_source) VALUES ('Artist', 'artist', 'none') RETURNING id::text`) + album := mustID(t, pool, `INSERT INTO albums (title, sort_title, artist_id, cover_art_source, cover_art_path) + VALUES ('Album', 'album', $1, 'mbcaa', '/data/covers/a.jpg') RETURNING id::text`, artist) + track := mustID(t, pool, `INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format, tag_source) + VALUES ('Track', $1, $2, 180000, '/music/a.flac', 1000, 'flac', 'musicbrainz') RETURNING id::text`, album, artist) + session := mustID(t, pool, `INSERT INTO play_sessions (user_id, started_at, last_event_at) VALUES ($1, now(), now()) RETURNING id::text`, user) + mustExec(t, pool, `INSERT INTO play_events (user_id, track_id, session_id, started_at) VALUES ($1, $2, $3, now())`, user, track, session) + mustExec(t, pool, `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, user, track) + mustExec(t, pool, `INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_by) + VALUES ($1, ARRAY[$2::uuid, $2::uuid], $2, 61000, 'an app')`, user, track) + playlist := mustID(t, pool, `INSERT INTO playlists (user_id, name) VALUES ($1, 'Mine') RETURNING id::text`, user) + mustExec(t, pool, `INSERT INTO playlist_tracks (playlist_id, position, track_id, title, artist_name, album_title, duration_sec) + VALUES ($1, 0, $2, 'Track', 'Artist', 'Album', 180)`, playlist, track) + mustExec(t, pool, `INSERT INTO library_changes (entity_type, entity_id, op) VALUES ('track', $1, 'upsert')`, track) + + first, err := backup.Snapshot(ctx, pool) + if err != nil { + t.Fatalf("snapshot: %v", err) + } + for _, tbl := range backup.Tables { + for _, line := range first.Tables[tbl.Name] { + var row map[string]json.RawMessage + if err := json.Unmarshal(line, &row); err != nil { + t.Fatalf("%s: %v", tbl.Name, err) + } + for _, col := range tbl.Omit { + if _, ok := row[col]; ok { + t.Errorf("%s.%s is in the backup", tbl.Name, col) + } + } + } + } + for _, tbl := range []string{"users", "tracks", "play_events", "general_likes", "play_queues", "playlist_tracks", "library_changes"} { + if len(first.Tables[tbl]) == 0 { + t.Errorf("the backup holds no %s", tbl) + } + } + + if err := backup.Restore(ctx, pool, first); !errors.Is(err, backup.ErrNotEmpty) { + t.Fatalf("restore over data: err = %v, want ErrNotEmpty", err) + } + newer := first + newer.Schema++ + if err := backup.Restore(ctx, pool, newer); !errors.Is(err, backup.ErrNewerSchema) { + t.Fatalf("restore from a newer schema: err = %v, want ErrNewerSchema", err) + } + + // A new server scans its music before anyone signs up, so it already has + // a library, here with a track the backup doesn't know. It still takes + // the backup: the backup's library replaces what the scan found, which the + // next scan finds again under the backup's ids. + mustExec(t, pool, "TRUNCATE users CASCADE") + scannedArtist := mustID(t, pool, `INSERT INTO artists (name, sort_name) VALUES ('Scanned', 'scanned') RETURNING id::text`) + scannedAlbum := mustID(t, pool, `INSERT INTO albums (title, sort_title, artist_id) VALUES ('Scanned', 'scanned', $1) RETURNING id::text`, scannedArtist) + scanned := mustID(t, pool, `INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format) + VALUES ('Scanned', $1, $2, 1000, '/music/b.flac', 10, 'flac') RETURNING id::text`, scannedAlbum, scannedArtist) + mustExec(t, pool, `INSERT INTO library_changes (entity_type, entity_id, op) VALUES ('track', $1, 'upsert')`, scanned) + if err := backup.Restore(ctx, pool, first); err != nil { + t.Fatalf("restore: %v", err) + } + + second, err := backup.Snapshot(ctx, pool) + if err != nil { + t.Fatalf("snapshot after restore: %v", err) + } + for _, tbl := range backup.Tables { + a, b := first.Tables[tbl.Name], second.Tables[tbl.Name] + if len(a) != len(b) { + t.Errorf("%s: %d rows restored, the backup held %d", tbl.Name, len(b), len(a)) + continue + } + for i := range a { + if !bytes.Equal(a[i], b[i]) { + t.Errorf("%s row %d:\nbacked up %s\nrestored %s", tbl.Name, i+1, a[i], b[i]) + } + } + } + + // What the backup leaves out comes back unset, so the credential is + // entered again and the art and tags are redone. ListenBrainz comes back + // off, since it can't send until its token is saved again. + var lbToken, coverSource, tagSource *string + var lbEnabled bool + if err := pool.QueryRow(ctx, `SELECT u.listenbrainz_token, u.listenbrainz_enabled, al.cover_art_source, tr.tag_source + FROM users u, albums al, tracks tr WHERE u.id = $1 AND al.id = $2 AND tr.id = $3`, + user, album, track).Scan(&lbToken, &lbEnabled, &coverSource, &tagSource); err != nil { + t.Fatal(err) + } + if lbToken != nil || lbEnabled || coverSource != nil || tagSource != nil { + t.Errorf("token %v, enabled %v, cover source %v, tag source %v; want all unset", lbToken, lbEnabled, coverSource, tagSource) + } + + // The change feed carries on after the restored ids. + var restoredMax, issued, next int64 + if err := pool.QueryRow(ctx, "SELECT max(id) FROM library_changes").Scan(&restoredMax); err != nil { + t.Fatal(err) + } + // The sequence says the restored history ends there, which is what the + // library sync compares an app's cursor with. + if err := pool.QueryRow(ctx, `SELECT COALESCE(pg_sequence_last_value( + pg_get_serial_sequence('library_changes', 'id')::regclass), 0)`).Scan(&issued); err != nil { + t.Fatal(err) + } + if issued != restoredMax { + t.Errorf("the change sequence stands at %d, want the restored %d", issued, restoredMax) + } + if err := pool.QueryRow(ctx, `INSERT INTO library_changes (entity_type, entity_id, op) + VALUES ('track', $1, 'upsert') RETURNING id`, track).Scan(&next); err != nil { + t.Fatal(err) + } + if next <= restoredMax { + t.Errorf("next change id %d, want it after the restored %d", next, restoredMax) + } +} diff --git a/internal/backup/music.go b/internal/backup/music.go new file mode 100644 index 00000000..4060cdbe --- /dev/null +++ b/internal/backup/music.go @@ -0,0 +1,281 @@ +package backup + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgtype" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" +) + +const ( + // The music's folder inside the destination, beside database/. + musicDir = "music" + // MusicBudget is how long one run may spend sending music. A library + // bigger than a night's worth carries on from where it stopped on the + // next run, so the first copy of a large library spans several nights. + MusicBudget = 6 * time.Hour + musicBatch = 200 + // refusedInARow stops a pass: one refusal is that file, several in a row + // are the key or the bucket refusing the music as a whole. + refusedInARow = 3 +) + +// MusicProgress is how much of the library the backup holds as it is now. +type MusicProgress struct { + TotalFiles int64 `json:"total_files"` + TotalBytes int64 `json:"total_bytes"` + SentFiles int64 `json:"sent_files"` + SentBytes int64 `json:"sent_bytes"` + RefusedFiles int64 `json:"refused_files"` + Refused []RefusedFile `json:"refused"` +} + +// RefusedFile is a library file the destination would not take, with its +// answer. It is tried again once the file changes. +type RefusedFile struct { + Path string `json:"path"` + Error string `json:"error"` + At time.Time `json:"at"` +} + +// musicSent is what one run's music pass did. +type musicSent struct { + files int + bytes int64 + note string +} + +// commonRoot is the deepest folder holding every library root, so the music's +// paths in the backup are the same whichever root a file is under. +func commonRoot(roots []string) string { + if len(roots) == 0 { + return "" + } + common := strings.Split(filepath.Clean(roots[0]), string(filepath.Separator)) + for _, r := range roots[1:] { + parts := strings.Split(filepath.Clean(r), string(filepath.Separator)) + n := 0 + for n < len(common) && n < len(parts) && common[n] == parts[n] { + n++ + } + common = common[:n] + } + root := strings.Join(common, string(filepath.Separator)) + if root == "" { + return string(filepath.Separator) + } + return root +} + +// musicPath is file's path inside music/, relative to root, with forward +// slashes. A file outside root keeps its whole path. +func musicPath(root, file string) string { + rel, err := filepath.Rel(root, file) + if root == "" || err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + rel = strings.TrimPrefix(filepath.Clean(file), string(filepath.Separator)) + } + return musicDir + "/" + filepath.ToSlash(rel) +} + +func (s *Service) musicProgress(ctx context.Context) (*MusicProgress, error) { + q := dbq.New(s.pool) + p, err := q.BackupMusicProgress(ctx) + if err != nil { + return nil, fmt.Errorf("backup: read music progress: %w", err) + } + refused, err := q.RefusedBackupMusic(ctx, recentRuns) + if err != nil { + return nil, fmt.Errorf("backup: list refused music: %w", err) + } + out := &MusicProgress{ + TotalFiles: p.TotalFiles, TotalBytes: p.TotalBytes, + SentFiles: p.SentFiles, SentBytes: p.SentBytes, + RefusedFiles: p.RefusedFiles, Refused: make([]RefusedFile, 0, len(refused)), + } + for _, r := range refused { + out.Refused = append(out.Refused, RefusedFile{Path: r.FilePath, Error: r.Error, At: r.CheckedAt.Time}) + } + return out, nil +} + +// sendMusic sends library files the destination doesn't hold as they are now, +// one at a time in path order, until all are sent or ctx ends. Every file is +// recorded as it lands, so a run cut short loses nothing. It never deletes +// anything at the destination. +func (s *Service) sendMusic(ctx context.Context, st dbq.BackupSetting) musicSent { + var out musicSent + q := dbq.New(s.pool) + var roots []string + if s.Roots != nil { + roots = s.Roots() + } + root := commonRoot(roots) + var bucket Bucket + if st.Destination == DestinationS3 { + b, err := bucketOf(st) + if err != nil { + out.note = describe(err) + return out + } + bucket = b + } + + after := "" + refused := 0 + for { + rows, err := q.PendingBackupMusic(ctx, dbq.PendingBackupMusicParams{AfterPath: after, MaxRows: musicBatch}) + if err != nil { + out.note = musicStopped(ctx, err) + return out + } + if len(rows) == 0 { + return out + } + for _, r := range rows { + after = r.FilePath + if err := ctx.Err(); err != nil { + out.note = musicStopped(ctx, err) + return out + } + info, err := os.Stat(r.FilePath) + if err != nil || !info.Mode().IsRegular() { + // Gone or unreadable: the library scan settles that, and the + // file is looked at again on the next run. + continue + } + mtime := info.ModTime().Truncate(time.Microsecond) + key := musicPath(root, r.FilePath) + location := key + if st.Destination == DestinationFolder { + location = filepath.Join(st.Folder, filepath.FromSlash(key)) + } + rec := dbq.RecordBackupMusicParams{ + TrackID: r.ID, Size: info.Size(), + Mtime: pgtype.Timestamptz{Time: mtime, Valid: true}, + Location: location, + } + if r.SentSize != nil && *r.SentSize == info.Size() && r.SentMtime.Valid && r.SentMtime.Time.Equal(mtime) && + (r.SentError == nil || *r.SentError == "") { + // Touched by a scan but the same file: nothing to send. + if err := q.RecordBackupMusic(ctx, rec); err != nil { + out.note = musicStopped(ctx, err) + return out + } + continue + } + + if st.Destination == DestinationFolder { + err = copyFile(r.FilePath, location, mtime) + } else { + err = putFile(ctx, bucket, key, r.FilePath, int64(st.UploadLimitKib)*1024) + } + switch { + case err == nil: + out.files++ + out.bytes += info.Size() + refused = 0 + case ObjectRefused(err): + rec.Error = strings.TrimPrefix(err.Error(), "backup: ") + if refused++; refused >= refusedInARow { + out.note = fmt.Sprintf("Music stopped: the destination refused %d files in a row (%s). "+ + "Check the key may write under %s/; refused files go again once you save the settings.", + refused, rec.Error, musicDir) + } + case ctx.Err() == nil && errors.Is(err, errSourceRead): + // The library file couldn't be read through: looked at again next run. + continue + default: + out.note = musicStopped(ctx, err) + return out + } + if err := q.RecordBackupMusic(ctx, rec); err != nil { + out.note = musicStopped(ctx, err) + return out + } + if out.note != "" { + return out + } + } + } +} + +// musicStopped is why a music pass ended early, as the panel shows it. +func musicStopped(ctx context.Context, err error) string { + switch { + case errors.Is(ctx.Err(), context.DeadlineExceeded): + return fmt.Sprintf("Music stopped for tonight after %d hours; it carries on with the next backup.", int(MusicBudget/time.Hour)) + case ctx.Err() != nil: + return "Music stopped because the server stopped; it carries on with the next backup." + } + return "Music stopped: " + describe(err) + " It carries on with the next backup." +} + +// errSourceRead marks a library file that could not be read. +var errSourceRead = errors.New("backup: the library file could not be read") + +// putFile uploads file to key. It reads the file twice, once to hash it +// (S3 signs over the body's hash) and once to send it through the limit. +func putFile(ctx context.Context, b Bucket, key, file string, perSecond int64) error { + f, err := os.Open(file) + if err != nil { + return fmt.Errorf("%w: %v", errSourceRead, err) + } + defer func() { _ = f.Close() }() + h := sha256.New() + size, err := io.Copy(h, f) + if err != nil { + return fmt.Errorf("%w: %v", errSourceRead, err) + } + if _, err := f.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("%w: %v", errSourceRead, err) + } + return b.Put(ctx, key, Throttle(ctx, f, perSecond), size, hex.EncodeToString(h.Sum(nil))) +} + +// copyFile copies file to dst under a hidden .part name first, so the folder +// never holds half a file under the file's own name. The copy keeps the +// file's modification time. The upload limit is the bucket's: a folder copy +// runs at the disk's pace. +func copyFile(file, dst string, mtime time.Time) error { + in, err := os.Open(file) + if err != nil { + return fmt.Errorf("%w: %v", errSourceRead, err) + } + defer func() { _ = in.Close() }() + if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil { + return fmt.Errorf("backup: create %s: %w", filepath.Dir(dst), err) + } + part := filepath.Join(filepath.Dir(dst), "."+filepath.Base(dst)+".part") + out, err := os.OpenFile(part, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + return fmt.Errorf("backup: create %s: %w", part, err) + } + _, err = io.Copy(out, in) + if err == nil { + err = out.Sync() + } + if cerr := out.Close(); err == nil { + err = cerr + } + if err == nil { + err = os.Chtimes(part, mtime, mtime) + } + if err == nil { + err = os.Rename(part, dst) + } + if err != nil { + _ = os.Remove(part) + return fmt.Errorf("backup: write %s: %w", dst, err) + } + return nil +} diff --git a/internal/backup/music_integration_test.go b/internal/backup/music_integration_test.go new file mode 100644 index 00000000..5f8cdfba --- /dev/null +++ b/internal/backup/music_integration_test.go @@ -0,0 +1,217 @@ +package backup_test + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/backup" +) + +// library writes music files under a new library folder and adds a track for +// each. It returns the folder. +func library(t *testing.T, pool *pgxpool.Pool, files map[string]string) string { + t.Helper() + root := t.TempDir() + artist := mustID(t, pool, `INSERT INTO artists (name, sort_name) VALUES ('Artist', 'artist') RETURNING id::text`) + album := mustID(t, pool, `INSERT INTO albums (title, sort_title, artist_id) VALUES ('Album', 'album', $1) RETURNING id::text`, artist) + for rel, body := range files { + path := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + mustExec(t, pool, `INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format) + VALUES ($1, $2, $3, 1000, $4, $5, 'flac')`, rel, album, artist, path, len(body)) + } + return root +} + +func runOnce(t *testing.T, svc *backup.Service) backup.Run { + t.Helper() + if err := svc.Start(context.Background(), backup.TriggerManual); err != nil { + t.Fatal(err) + } + waitIdle(t, svc) + st := status(t, svc) + if len(st.Runs) == 0 || st.Runs[0].Status != "succeeded" { + t.Fatalf("the run didn't succeed: %+v", st.Runs) + } + return st.Runs[0] +} + +func TestTheMusicGoesToTheFolderOnceAndAgainOnlyWhenItChanges_Integration(t *testing.T) { + svc, pool := newService(t) + ctx := context.Background() + lib := library(t, pool, map[string]string{"A/one.flac": "one", "B/two.flac": "second"}) + svc.Roots = func() []string { return []string{lib} } + dest := t.TempDir() + if err := svc.Save(ctx, backup.Update{Enabled: true, Destination: backup.DestinationFolder, Folder: dest, RunHour: 3, IncludeMusic: true}); err != nil { + t.Fatal(err) + } + + first := runOnce(t, svc) + if first.MusicFiles != 2 || first.MusicBytes != int64(len("one")+len("second")) || first.MusicNote != "" { + t.Errorf("the first run sent %d files, %d bytes, note %q", first.MusicFiles, first.MusicBytes, first.MusicNote) + } + got, err := os.ReadFile(filepath.Join(dest, "music", "B", "two.flac")) + if err != nil || string(got) != "second" { + t.Errorf("music/B/two.flac = %q, %v", got, err) + } + src, _ := os.Stat(filepath.Join(lib, "A", "one.flac")) + dst, err := os.Stat(filepath.Join(dest, "music", "A", "one.flac")) + // The database keeps microseconds, so the copy's time is the file's to the µs. + if err != nil || !dst.ModTime().Equal(src.ModTime().Truncate(time.Microsecond)) { + t.Errorf("the copy's time = %v, want the file's %v (%v)", dst, src.ModTime(), err) + } + if p := status(t, svc).Music; p == nil || p.TotalFiles != 2 || p.SentFiles != 2 || p.RefusedFiles != 0 { + t.Errorf("progress = %+v, want 2 of 2", p) + } + + if again := runOnce(t, svc); again.MusicFiles != 0 { + t.Errorf("a second run sent %d files, want none", again.MusicFiles) + } + + // A scan that touched the track but found the same file sends nothing. + mustExec(t, pool, `UPDATE tracks SET updated_at = now()`) + if touched := runOnce(t, svc); touched.MusicFiles != 0 { + t.Errorf("after a scan touched the tracks the run sent %d files, want none", touched.MusicFiles) + } + if p := status(t, svc).Music; p == nil || p.SentFiles != 2 { + t.Errorf("progress after the scan = %+v, want 2 sent", p) + } + + // A changed file goes again, to the same place. + path := filepath.Join(lib, "A", "one.flac") + if err := os.WriteFile(path, []byte("one, retagged"), 0o644); err != nil { + t.Fatal(err) + } + later := time.Now().Add(time.Minute) + if err := os.Chtimes(path, later, later); err != nil { + t.Fatal(err) + } + mustExec(t, pool, `UPDATE tracks SET file_size = $1 WHERE file_path = $2`, len("one, retagged"), path) + if changed := runOnce(t, svc); changed.MusicFiles != 1 { + t.Errorf("after one file changed the run sent %d files, want 1", changed.MusicFiles) + } + if got, _ := os.ReadFile(filepath.Join(dest, "music", "A", "one.flac")); string(got) != "one, retagged" { + t.Errorf("music/A/one.flac = %q, want the changed file", got) + } + if entries, _ := os.ReadDir(filepath.Join(dest, "music", "A")); len(entries) != 1 { + t.Errorf("music/A holds %d entries, want just the file", len(entries)) + } +} + +// lockedBucket is a fakeBucket that refuses to overwrite an object, like a +// bucket with object lock. With all set it refuses every music object, like +// a key that may write only under database/. +type lockedBucket struct { + *fakeBucket + all *atomic.Bool +} + +func (b lockedBucket) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/minstrel/music/") { + b.mu.Lock() + _, held := b.puts[r.URL.Path] + b.mu.Unlock() + if held || (b.all != nil && b.all.Load()) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`AccessDeniedobject is locked`)) + return + } + } + b.fakeBucket.ServeHTTP(w, r) +} + +func TestTheMusicGoesToTheBucketAndARefusedOverwriteIsKept_Integration(t *testing.T) { + svc, pool := newService(t) + ctx := context.Background() + fake := &fakeBucket{puts: map[string][]byte{}} + srv := httptest.NewServer(lockedBucket{fakeBucket: fake}) + defer srv.Close() + lib := library(t, pool, map[string]string{"A/one.flac": "one", "B/two.flac": "second"}) + svc.Roots = func() []string { return []string{lib} } + u := bucketUpdate(srv.URL) + u.IncludeMusic = true + if err := svc.Save(ctx, u); err != nil { + t.Fatal(err) + } + + if first := runOnce(t, svc); first.MusicFiles != 2 { + t.Fatalf("the first run sent %d files, want 2", first.MusicFiles) + } + fake.mu.Lock() + body := string(fake.puts["/minstrel/music/A/one.flac"]) + fake.mu.Unlock() + if body != "one" { + t.Errorf("music/A/one.flac in the bucket = %q", body) + } + + path := filepath.Join(lib, "A", "one.flac") + if err := os.WriteFile(path, []byte("one, retagged"), 0o644); err != nil { + t.Fatal(err) + } + mustExec(t, pool, `UPDATE tracks SET file_size = $1, updated_at = now() WHERE file_path = $2`, len("one, retagged"), path) + run := runOnce(t, svc) + if run.MusicFiles != 0 || run.MusicNote != "" { + t.Errorf("a refused overwrite: sent %d, note %q; want nothing sent and no note", run.MusicFiles, run.MusicNote) + } + p := status(t, svc).Music + if p == nil || p.SentFiles != 1 || p.RefusedFiles != 1 || len(p.Refused) != 1 || + p.Refused[0].Path != path || !strings.Contains(p.Refused[0].Error, "AccessDenied") { + t.Errorf("progress = %+v, want one sent and the overwrite refused", p) + } + + // Refused is settled until the file changes again. + if again := runOnce(t, svc); again.MusicFiles != 0 { + t.Errorf("the run after a refusal sent %d files, want none", again.MusicFiles) + } + if p := status(t, svc).Music; p == nil || p.RefusedFiles != 1 { + t.Errorf("progress after the next run = %+v, want the refusal kept", p) + } +} + +func TestAKeyThatMayNotWriteTheMusicStopsThePassAndASaveTriesAgain_Integration(t *testing.T) { + svc, pool := newService(t) + ctx := context.Background() + fake := &fakeBucket{puts: map[string][]byte{}} + all := &atomic.Bool{} + all.Store(true) + srv := httptest.NewServer(lockedBucket{fakeBucket: fake, all: all}) + defer srv.Close() + lib := library(t, pool, map[string]string{"a.flac": "a", "b.flac": "b", "c.flac": "c", "d.flac": "d"}) + svc.Roots = func() []string { return []string{lib} } + u := bucketUpdate(srv.URL) + u.IncludeMusic = true + if err := svc.Save(ctx, u); err != nil { + t.Fatal(err) + } + + run := runOnce(t, svc) + if run.MusicFiles != 0 || !strings.Contains(run.MusicNote, "refused 3 files in a row") { + t.Errorf("sent %d, note %q; want the pass stopped after three refusals", run.MusicFiles, run.MusicNote) + } + if p := status(t, svc).Music; p == nil || p.RefusedFiles != 3 { + t.Errorf("progress = %+v, want three refused and the fourth not tried", p) + } + + // The key is fixed and the settings saved: the refused files go again. + all.Store(false) + if err := svc.Save(ctx, u); err != nil { + t.Fatal(err) + } + if again := runOnce(t, svc); again.MusicFiles != 4 || again.MusicNote != "" { + t.Errorf("after the save: sent %d, note %q; want all four", again.MusicFiles, again.MusicNote) + } +} diff --git a/internal/backup/music_test.go b/internal/backup/music_test.go new file mode 100644 index 00000000..9c60519b --- /dev/null +++ b/internal/backup/music_test.go @@ -0,0 +1,60 @@ +package backup + +import ( + "errors" + "fmt" + "net/http" + "testing" +) + +func TestCommonRootIsTheFolderHoldingEveryLibraryRoot(t *testing.T) { + for _, c := range []struct { + roots []string + want string + }{ + {nil, ""}, + {[]string{"/music"}, "/music"}, + {[]string{"/music/"}, "/music"}, + {[]string{"/data/music/a", "/data/music/b"}, "/data/music"}, + {[]string{"/data/music", "/data/musicals"}, "/data"}, + {[]string{"/music", "/audiobooks"}, "/"}, + } { + if got := commonRoot(c.roots); got != c.want { + t.Errorf("commonRoot(%q) = %q, want %q", c.roots, got, c.want) + } + } +} + +func TestMusicPathIsTheFileUnderTheCommonRoot(t *testing.T) { + for _, c := range []struct{ root, file, want string }{ + {"/data/music", "/data/music/a/Artist/01 Song.flac", "music/a/Artist/01 Song.flac"}, + {"/", "/music/x.mp3", "music/music/x.mp3"}, + {"/data/music", "/elsewhere/x.mp3", "music/elsewhere/x.mp3"}, + {"", "/music/x.mp3", "music/music/x.mp3"}, + } { + if got := musicPath(c.root, c.file); got != c.want { + t.Errorf("musicPath(%q, %q) = %q, want %q", c.root, c.file, got, c.want) + } + } +} + +func TestObjectRefusedIsOneObjectNotTheWholeBucket(t *testing.T) { + for _, c := range []struct { + err error + want bool + }{ + {&Refusal{Status: http.StatusForbidden, Code: "AccessDenied"}, true}, + {&Refusal{Status: http.StatusConflict, Code: "ObjectLocked"}, true}, + {fmt.Errorf("put: %w", &Refusal{Status: http.StatusBadRequest, Code: "InvalidObjectName"}), true}, + {&Refusal{Status: http.StatusForbidden, Code: "SignatureDoesNotMatch"}, false}, + {&Refusal{Status: http.StatusNotFound, Code: "NoSuchBucket"}, false}, + {&Refusal{Status: http.StatusTooManyRequests}, false}, + {&Refusal{Status: http.StatusServiceUnavailable, Code: "SlowDown"}, false}, + {&Refusal{Status: http.StatusInternalServerError}, false}, + {errors.New("connection refused"), false}, + } { + if got := ObjectRefused(c.err); got != c.want { + t.Errorf("ObjectRefused(%v %+v) = %v, want %v", c.err, c.err, got, c.want) + } + } +} diff --git a/internal/backup/restore.go b/internal/backup/restore.go new file mode 100644 index 00000000..46969de5 --- /dev/null +++ b/internal/backup/restore.go @@ -0,0 +1,201 @@ +package backup + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +var ( + // ErrNotEmpty is a restore into an instance that already has accounts. + ErrNotEmpty = errors.New("backup: this Minstrel already has accounts; a backup restores into a new one") + + // ErrNewerSchema is a backup written by a newer Minstrel than this one. + ErrNewerSchema = errors.New("backup: the backup was written by a newer version of Minstrel; upgrade this one first") + + // ErrNotABackup is contents that aren't rows a backup writes. + ErrNotABackup = errors.New("backup: not a Minstrel backup") +) + +// batchRows is how many rows one INSERT carries. +const batchRows = 500 + +// Restore loads a backup into an empty instance, in one transaction: either +// all of it lands or none of it does. +// +// The instance must have no accounts. Its rows in the tables the backup holds +// are replaced: a fresh instance's seeded settings, and the library its +// startup scan found before anyone signed up, which the scan after the +// restore finds again under the backup's ids. A table the backup doesn't +// hold, because it was written before that table existed, keeps what the +// instance has. +// +// A row's columns are those the backup and the table both have: an older +// backup's rows take the defaults of columns added since, and a column dropped +// since is left out. +func Restore(ctx context.Context, pool *pgxpool.Pool, c Contents) error { + tx, err := pool.Begin(ctx) + if err != nil { + return fmt.Errorf("backup: begin: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + + schema, err := schemaVersion(ctx, tx) + if err != nil { + return err + } + if c.Schema > schema { + return ErrNewerSchema + } + // Taken before the emptiness check, so a first account made at the same + // moment waits for the restore, then finds the data. A scan still running + // waits too, rather than adding to the library while it is replaced. + if _, err := tx.Exec(ctx, "LOCK TABLE users, artists, albums, tracks IN EXCLUSIVE MODE"); err != nil { + return fmt.Errorf("backup: lock: %w", err) + } + var occupied bool + if err := tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM users)").Scan(&occupied); err != nil { + return fmt.Errorf("backup: check the instance is new: %w", err) + } + if occupied { + return ErrNotEmpty + } + + // Children first, so no row is left pointing at one already gone. + for _, t := range slices.Backward(Tables) { + if _, ok := c.Tables[t.Name]; !ok { + continue + } + if _, err := tx.Exec(ctx, "DELETE FROM "+pgx.Identifier{t.Name}.Sanitize()); err != nil { + return fmt.Errorf("backup: clear %s: %w", t.Name, err) + } + } + for _, t := range Tables { + rows, ok := c.Tables[t.Name] + if !ok { + continue + } + if err := restoreTable(ctx, tx, t.Name, rows); err != nil { + return err + } + } + if err := tx.Commit(ctx); err != nil { + return fmt.Errorf("backup: commit: %w", err) + } + return nil +} + +type column struct { + name string + identity bool + sequence bool +} + +func restoreTable(ctx context.Context, tx pgx.Tx, table string, rows [][]byte) error { + cols, err := writableColumns(ctx, tx, table) + if err != nil { + return err + } + ident := pgx.Identifier{table}.Sanitize() + overriding := "" + if slices.ContainsFunc(cols, func(c column) bool { return c.identity }) { + overriding = " OVERRIDING SYSTEM VALUE" + } + + // Rows go in batches that share one key set; a backup's rows for a table + // all do, since one read wrote them. + var ( + batch []json.RawMessage + list string + ) + flush := func() error { + if len(batch) == 0 { + return nil + } + payload, err := json.Marshal(batch) + if err != nil { + return err + } + sql := fmt.Sprintf("INSERT INTO %s (%s)%s SELECT %s FROM jsonb_populate_recordset(NULL::%s, $1::jsonb)", + ident, list, overriding, list, ident) + if _, err := tx.Exec(ctx, sql, string(payload)); err != nil { + return fmt.Errorf("backup: restore %s: %w", table, err) + } + batch = batch[:0] + return nil + } + for i, raw := range rows { + var keys map[string]json.RawMessage + if err := json.Unmarshal(raw, &keys); err != nil { + return fmt.Errorf("%w: row %d of %s is not an object", ErrNotABackup, i+1, table) + } + var names []string + for _, c := range cols { + if _, ok := keys[c.name]; ok { + names = append(names, pgx.Identifier{c.name}.Sanitize()) + } + } + if len(names) == 0 { + continue + } + slices.Sort(names) + rowList := strings.Join(names, ", ") + if rowList != list || len(batch) == batchRows { + if err := flush(); err != nil { + return err + } + list = rowList + } + batch = append(batch, raw) + } + if err := flush(); err != nil { + return err + } + + // A sequence carries on after the highest restored value, so the next row + // doesn't collide with one from the backup. It is left as having issued + // that value, so the sequence itself says how far the restored history + // goes: the library sync compares an app's cursor with it. + for _, c := range cols { + if !c.sequence { + continue + } + col := pgx.Identifier{c.name}.Sanitize() + if _, err := tx.Exec(ctx, fmt.Sprintf(` + SELECT CASE WHEN m > 0 THEN setval(pg_get_serial_sequence($1, $2), m, true) + ELSE setval(pg_get_serial_sequence($1, $2), 1, false) END + FROM (SELECT COALESCE(max(%s), 0) AS m FROM %s) AS top`, col, ident), + table, c.name); err != nil { + return fmt.Errorf("backup: carry on %s's sequence: %w", table, err) + } + } + return nil +} + +// writableColumns returns the columns of a table an INSERT can set: all but +// generated ones, which Postgres computes. +func writableColumns(ctx context.Context, tx pgx.Tx, table string) ([]column, error) { + rows, err := tx.Query(ctx, ` + SELECT column_name, is_identity = 'YES', pg_get_serial_sequence($1::text, column_name) IS NOT NULL + FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = $1::text AND is_generated = 'NEVER' + ORDER BY ordinal_position`, table) + if err != nil { + return nil, fmt.Errorf("backup: read %s's columns: %w", table, err) + } + cols, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (column, error) { + var c column + err := row.Scan(&c.name, &c.identity, &c.sequence) + return c, err + }) + if err != nil { + return nil, fmt.Errorf("backup: read %s's columns: %w", table, err) + } + return cols, nil +} diff --git a/internal/backup/s3.go b/internal/backup/s3.go new file mode 100644 index 00000000..6efb21b1 --- /dev/null +++ b/internal/backup/s3.go @@ -0,0 +1,231 @@ +package backup + +import ( + "context" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// ErrS3 is a request the bucket refused or never answered. +var ErrS3 = errors.New("backup: the S3 bucket refused the request") + +// Bucket is a path-style S3 bucket: an endpoint such as Fabled Archives' +// backup port or MinIO, a bucket name, and a key pair. A backup only ever +// adds objects and lists them, so an append-only key is enough. +type Bucket struct { + Endpoint string + Name string + AccessKey string + SecretKey string + // Region defaults to us-east-1, which S3-compatible servers accept. + Region string + Client *http.Client + // now is the signing clock; tests pin it. + now func() time.Time +} + +// Object is one stored object. +type Object struct { + Key string + Size int64 + LastModified time.Time +} + +func (b Bucket) region() string { + if b.Region == "" { + return "us-east-1" + } + return b.Region +} + +func (b Bucket) client() *http.Client { + if b.Client != nil { + return b.Client + } + return http.DefaultClient +} + +func (b Bucket) clock() time.Time { + if b.now != nil { + return b.now() + } + return time.Now() +} + +// objectURL is the path-style URL of key, encoded exactly as it is signed. +func (b Bucket) objectURL(key string) (*url.URL, error) { + u, err := url.Parse(strings.TrimRight(b.Endpoint, "/")) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return nil, fmt.Errorf("%w: the endpoint %q is not an http(s) address", ErrS3, b.Endpoint) + } + if b.Name == "" { + return nil, fmt.Errorf("%w: no bucket name", ErrS3) + } + raw := "/" + uriEncode(b.Name) + if key != "" { + for s := range strings.SplitSeq(key, "/") { + raw += "/" + uriEncode(s) + } + } + u.RawPath = u.EscapedPath() + raw + u.Path, _ = url.PathUnescape(u.RawPath) + return u, nil +} + +func (b Bucket) do(req *http.Request, payloadSHA256 string) (*http.Response, error) { + sign(req, payloadSHA256, b.AccessKey, b.SecretKey, b.region(), b.clock()) + resp, err := b.client().Do(req) + if err != nil { + return nil, fmt.Errorf("%w: %s is unreachable: %v", ErrS3, req.URL.Host, err) + } + if resp.StatusCode/100 != 2 { + defer func() { _ = resp.Body.Close() }() + return nil, refusal(resp) + } + return resp, nil +} + +// Put stores body under key. size is the body's length and payloadSHA256 +// its hex SHA-256, which the request is signed over. +func (b Bucket) Put(ctx context.Context, key string, body io.Reader, size int64, payloadSHA256 string) error { + u, err := b.objectURL(key) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPut, u.String(), body) + if err != nil { + return err + } + req.URL = u + req.ContentLength = size + if size == 0 { + req.Body = http.NoBody + } + resp, err := b.do(req, payloadSHA256) + if err != nil { + return err + } + drain(resp) + return nil +} + +// List returns up to limit objects whose keys start with prefix, in key +// order. +func (b Bucket) List(ctx context.Context, prefix string, limit int) ([]Object, error) { + if limit < 1 { + limit = 1000 + } + var out []Object + token := "" + for { + u, err := b.objectURL("") + if err != nil { + return nil, err + } + q := url.Values{"list-type": {"2"}, "prefix": {prefix}} + if page := limit - len(out); page < 1000 { + q.Set("max-keys", strconv.Itoa(page)) + } + if token != "" { + q.Set("continuation-token", token) + } + u.RawQuery = canonicalQuery(q) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return nil, err + } + req.URL = u + resp, err := b.do(req, emptySHA256) + if err != nil { + return nil, err + } + var page struct { + Contents []struct { + Key string `xml:"Key"` + Size int64 `xml:"Size"` + LastModified string `xml:"LastModified"` + } `xml:"Contents"` + IsTruncated bool `xml:"IsTruncated"` + NextContinuationToken string `xml:"NextContinuationToken"` + } + err = xml.NewDecoder(io.LimitReader(resp.Body, 16<<20)).Decode(&page) + drain(resp) + if err != nil { + return nil, fmt.Errorf("%w: the listing is not S3 XML: %v", ErrS3, err) + } + for _, c := range page.Contents { + modified, _ := time.Parse(time.RFC3339, c.LastModified) + out = append(out, Object{Key: c.Key, Size: c.Size, LastModified: modified}) + } + if !page.IsTruncated || page.NextContinuationToken == "" || len(out) >= limit { + return out, nil + } + token = page.NextContinuationToken + } +} + +// Refusal is an S3 error response: its HTTP status, S3's code, and the +// reason in words. It matches ErrS3. +type Refusal struct { + Status int + Code string + text string +} + +func (r *Refusal) Error() string { return r.text } +func (r *Refusal) Unwrap() error { return ErrS3 } + +// refusal turns an S3 error response into words an admin can act on. +func refusal(resp *http.Response) error { + var e struct { + Code string `xml:"Code"` + Message string `xml:"Message"` + } + _ = xml.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&e) + hint := map[string]string{ + "SignatureDoesNotMatch": "the secret key is wrong", + "InvalidAccessKeyId": "the access key is not known to this server", + "AccessDenied": "the key may not do this in this bucket", + "NoSuchBucket": "there is no bucket by that name", + "SlowDown": "the server asks to slow down", + }[e.Code] + r := &Refusal{Status: resp.StatusCode, Code: e.Code} + switch { + case hint != "": + r.text = fmt.Sprintf("%v: HTTP %d %s: %s", ErrS3, resp.StatusCode, e.Code, hint) + case e.Code != "": + r.text = fmt.Sprintf("%v: HTTP %d %s: %s", ErrS3, resp.StatusCode, e.Code, e.Message) + default: + r.text = fmt.Sprintf("%v: HTTP %d", ErrS3, resp.StatusCode) + } + return r +} + +// ObjectRefused reports whether err is the bucket refusing one object (an +// overwrite a write-once target won't take, a name it won't store) rather +// than refusing everything: bad keys, a missing bucket, a request to slow +// down, or a server error all stop a run instead. +func ObjectRefused(err error) bool { + var r *Refusal + if !errors.As(err, &r) || r.Status/100 != 4 || r.Status == http.StatusTooManyRequests { + return false + } + switch r.Code { + case "SignatureDoesNotMatch", "InvalidAccessKeyId", "NoSuchBucket", "SlowDown", + "RequestTimeTooSkewed", "ExpiredToken", "InvalidToken": + return false + } + return true +} + +func drain(resp *http.Response) { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20)) + _ = resp.Body.Close() +} diff --git a/internal/backup/s3_test.go b/internal/backup/s3_test.go new file mode 100644 index 00000000..69f511f8 --- /dev/null +++ b/internal/backup/s3_test.go @@ -0,0 +1,154 @@ +package backup + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// AWS's published examples ("Examples: Signature Calculations in AWS +// Signature Version 4", Amazon S3 API reference). +const ( + awsAccessKey = "AKIAIOSFODNN7EXAMPLE" + awsSecretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" + awsCred = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request" +) + +var awsTime = time.Date(2013, 5, 24, 0, 0, 0, 0, time.UTC) + +func TestSignMatchesAWSsExamples(t *testing.T) { + put := "Welcome to Amazon S3." + if got := hexSHA256([]byte(put)); got != "44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072" { + t.Fatalf("payload hash = %s", got) + } + for _, tc := range []struct { + name, method, url, body string + headers map[string]string + want string // after the credential + }{ + {"GET object", http.MethodGet, "http://examplebucket.s3.amazonaws.com/test.txt", "", + map[string]string{"Range": "bytes=0-9"}, + "SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"}, + {"PUT object", http.MethodPut, "http://examplebucket.s3.amazonaws.com/test$file.text", put, + map[string]string{"Date": "Fri, 24 May 2013 00:00:00 GMT", "X-Amz-Storage-Class": "REDUCED_REDUNDANCY"}, + "SignedHeaders=date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class, Signature=98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"}, + {"list objects", http.MethodGet, "http://examplebucket.s3.amazonaws.com/?max-keys=2&prefix=J", "", nil, + "SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"}, + } { + req, _ := http.NewRequest(tc.method, tc.url, strings.NewReader(tc.body)) + for k, v := range tc.headers { + req.Header.Set(k, v) + } + payload := emptySHA256 + if tc.body != "" { + payload = hexSHA256([]byte(tc.body)) + } + sign(req, payload, awsAccessKey, awsSecretKey, "us-east-1", awsTime) + if got, want := req.Header.Get("Authorization"), awsCred+", "+tc.want; got != want { + t.Errorf("%s: Authorization =\n%s\nwant\n%s", tc.name, got, want) + } + } +} + +func TestUriEncodeKeepsOnlyUnreservedCharacters(t *testing.T) { + for in, want := range map[string]string{ + "01 - Song.flac": "01%20-%20Song.flac", + "a+b=c&d": "a%2Bb%3Dc%26d", + "Höla~_.": "H%C3%B6la~_.", + "a/b": "a%2Fb", + } { + if got := uriEncode(in); got != want { + t.Errorf("uriEncode(%q) = %q, want %q", in, got, want) + } + } +} + +func testBucket(url string) Bucket { + return Bucket{Endpoint: url, Name: "minstrel", AccessKey: "ak", SecretKey: "sk", + now: func() time.Time { return awsTime }} +} + +func TestPutSendsTheBodyToItsPathStyleKey(t *testing.T) { + var gotPath, gotSHA, gotBody, gotAuth string + var gotLen int64 + srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + gotPath, gotSHA, gotAuth, gotLen = r.URL.EscapedPath(), r.Header.Get("X-Amz-Content-Sha256"), r.Header.Get("Authorization"), r.ContentLength + b, _ := io.ReadAll(r.Body) + gotBody = string(b) + })) + defer srv.Close() + + body := "flac bytes" + sum := hexSHA256([]byte(body)) + if err := testBucket(srv.URL).Put(context.Background(), "music/A B/01 + x.flac", strings.NewReader(body), int64(len(body)), sum); err != nil { + t.Fatal(err) + } + if gotPath != "/minstrel/music/A%20B/01%20%2B%20x.flac" { + t.Errorf("path = %s", gotPath) + } + if gotSHA != sum || gotBody != body || gotLen != int64(len(body)) { + t.Errorf("sha %s body %q length %d", gotSHA, gotBody, gotLen) + } + if !strings.HasPrefix(gotAuth, "AWS4-HMAC-SHA256 Credential=ak/20130524/us-east-1/s3/aws4_request") { + t.Errorf("Authorization = %s", gotAuth) + } +} + +func TestListFollowsContinuationTokens(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if r.URL.Path != "/minstrel" || q.Get("list-type") != "2" || q.Get("prefix") != "database/" { + http.Error(w, "unexpected "+r.URL.String(), http.StatusBadRequest) + return + } + if q.Get("continuation-token") == "" { + _, _ = fmt.Fprint(w, `truenext + database/minstrel-20261101T030000Z.tar102026-11-01T03:00:05.000Z + database/minstrel-20261102T030000Z.tar112026-11-02T03:00:05.000Z + `) + return + } + _, _ = fmt.Fprint(w, `false + database/minstrel-20261103T030000Z.tar122026-11-03T03:00:05.000Z + `) + })) + defer srv.Close() + + objs, err := testBucket(srv.URL).List(context.Background(), "database/", 0) + if err != nil { + t.Fatal(err) + } + if len(objs) != 3 || objs[2].Key != "database/minstrel-20261103T030000Z.tar" || objs[1].Size != 11 || + !objs[0].LastModified.Equal(time.Date(2026, 11, 1, 3, 0, 5, 0, time.UTC)) { + t.Errorf("objects = %+v", objs) + } +} + +func TestARefusalSaysWhatIsWrong(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = fmt.Fprint(w, `SignatureDoesNotMatchThe request signature we calculated does not match`) + })) + defer srv.Close() + + _, err := testBucket(srv.URL).List(context.Background(), "", 1) + if !errors.Is(err, ErrS3) || !strings.Contains(err.Error(), "HTTP 403 SignatureDoesNotMatch: the secret key is wrong") { + t.Errorf("err = %v", err) + } +} + +func TestAnUnreachableOrMalformedEndpointIsAnS3Error(t *testing.T) { + srv := httptest.NewServer(http.NotFoundHandler()) + srv.Close() + for name, endpoint := range map[string]string{"closed": srv.URL, "not http": "ftp://archives", "empty": ""} { + if _, err := testBucket(endpoint).List(context.Background(), "", 1); !errors.Is(err, ErrS3) { + t.Errorf("%s: err = %v, want ErrS3", name, err) + } + } +} diff --git a/internal/backup/service.go b/internal/backup/service.go new file mode 100644 index 00000000..9ddc4a26 --- /dev/null +++ b/internal/backup/service.go @@ -0,0 +1,747 @@ +package backup + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "log/slog" + "net/url" + "os" + "path" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" + "github.com/Fabled-Sword/minstrel/internal/secret" +) + +// Where a backup can go. +const ( + DestinationFolder = "folder" + DestinationS3 = "s3" +) + +// What started a run. +const ( + TriggerSchedule = "schedule" + TriggerManual = "manual" +) + +// The verdict a Status gives, worst first in the order an admin acts on them. +const ( + StateOff = "off" // the nightly backup is switched off + StateIncomplete = "incomplete" // switched on, but the destination isn't set up + StateFailing = "failing" // the latest run failed + StateWaiting = "waiting" // set up, and no backup has finished yet + StateOverdue = "overdue" // the latest good backup is more than a day old + StateOK = "ok" +) + +const ( + // RunLimit bounds one run, snapshot and upload together. The web panel + // stops polling a run a little after this, since the run is over by then. + RunLimit = 30 * time.Minute + // A nightly backup that hasn't succeeded for this long is overdue; the + // slack past a day covers a run that starts late or takes a while. + overdueAfter = 26 * time.Hour + tickEvery = 5 * time.Minute + // A failed run is tried again after at least this long, and after longer + // each time it fails again, so a destination that is down isn't hammered. + retryAfter = time.Hour + recentRuns = 10 + // Run history older than this is pruned after each run. + keepRunsFor = 90 * 24 * time.Hour + testTimeout = 30 * time.Second + // The database backups' folder inside the destination. The music, when + // it is backed up, sits beside it in the same destination. + databaseDir = "database" +) + +var ( + // ErrRunning is returned by Start while a backup is running. + ErrRunning = errors.New("backup: a backup is already running") + // ErrNotReady is returned by Start when the destination isn't set up. + ErrNotReady = errors.New("backup: the destination isn't set up yet") + // ErrClosed is returned by Start once the server is shutting down. + ErrClosed = errors.New("backup: the server is shutting down") +) + +// FieldError is a setting that can't be saved, with the reason in words. +type FieldError struct { + Field string `json:"field"` + Message string `json:"message"` +} + +func (e *FieldError) Error() string { return e.Field + ": " + e.Message } + +// Config is the backup's settings as an admin sees them. The bucket's secret +// key is never sent back, only whether one is stored. +type Config struct { + Enabled bool `json:"enabled"` + Destination string `json:"destination"` + Folder string `json:"folder"` + Endpoint string `json:"endpoint"` + Bucket string `json:"bucket"` + AccessKey string `json:"access_key"` + HasSecretKey bool `json:"has_secret_key"` + RunHour int `json:"run_hour"` + UploadLimitKiB int `json:"upload_limit_kib"` + IncludeMusic bool `json:"include_music"` +} + +// Update is a save from the admin card. An empty SecretKey keeps the stored +// one, so the key doesn't have to be typed again on every save. +type Update struct { + Enabled bool `json:"enabled"` + Destination string `json:"destination"` + Folder string `json:"folder"` + Endpoint string `json:"endpoint"` + Bucket string `json:"bucket"` + AccessKey string `json:"access_key"` + SecretKey string `json:"secret_key"` + RunHour int `json:"run_hour"` + UploadLimitKiB int `json:"upload_limit_kib"` + IncludeMusic bool `json:"include_music"` +} + +// Run is one attempt at a backup. +type Run struct { + ID string `json:"id"` + Trigger string `json:"trigger"` + Status string `json:"status"` + StartedAt time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at"` + Location string `json:"location"` + Bytes int64 `json:"bytes"` + Error string `json:"error"` + // What the run sent of the music, and why that stopped early, if it did. + MusicFiles int `json:"music_files"` + MusicBytes int64 `json:"music_bytes"` + MusicNote string `json:"music_note"` +} + +// Status is everything the admin panel shows: a verdict, what stands in its +// way, and the recent runs. +type Status struct { + Config Config `json:"config"` + State string `json:"state"` + Problems []string `json:"problems"` + RunningSince *time.Time `json:"running_since"` + LastSuccess *time.Time `json:"last_success"` + FailingSince *time.Time `json:"failing_since"` + // NextRun is when the schedule starts the next backup, or nil when it + // won't: switched off, or not set up. + NextRun *time.Time `json:"next_run"` + RunLimitSeconds int `json:"run_limit_seconds"` + Runs []Run `json:"runs"` + // Music is how much of the library the backup holds, when it includes + // the music. + Music *MusicProgress `json:"music"` +} + +// TestResult is what a destination test found: how many backups are there +// already and when the newest was made. +type TestResult struct { + Backups int `json:"backups"` + Latest *time.Time `json:"latest"` +} + +// Service runs Minstrel's own backup: nightly when switched on, or when an +// admin asks. One run at a time; each is recorded in backup_runs. +type Service struct { + pool *pgxpool.Pool + logger *slog.Logger + build string + now func() time.Time + // Roots lists the library's folders. The music's paths in the backup are + // relative to the folder holding them all. + Roots func() []string + + base context.Context + cancel context.CancelFunc + wg sync.WaitGroup + + mu sync.Mutex + runningSince time.Time + closed bool +} + +// NewService returns a Service over pool. build is the server's version, +// written into each backup's manifest. +func NewService(pool *pgxpool.Pool, logger *slog.Logger, build string) *Service { + base, cancel := context.WithCancel(context.Background()) + return &Service{pool: pool, logger: logger, build: build, now: time.Now, base: base, cancel: cancel} +} + +func (s *Service) settings(ctx context.Context) (dbq.BackupSetting, error) { + st, err := dbq.New(s.pool).GetBackupSettings(ctx) + if err != nil { + return st, fmt.Errorf("backup: read settings: %w", err) + } + return st, nil +} + +func view(st dbq.BackupSetting) Config { + return Config{ + Enabled: st.Enabled, + Destination: st.Destination, + Folder: st.Folder, + Endpoint: st.Endpoint, + Bucket: st.Bucket, + AccessKey: st.AccessKey, + HasSecretKey: st.SecretKey != "", + RunHour: int(st.RunHour), + UploadLimitKiB: int(st.UploadLimitKib), + IncludeMusic: st.IncludeMusic, + } +} + +// Config returns the settings as an admin sees them. +func (s *Service) Config(ctx context.Context) (Config, error) { + st, err := s.settings(ctx) + return view(st), err +} + +// merge applies u over the stored settings: it checks each field, and seals +// a new secret key. It returns a *FieldError for a value that can't be kept. +func merge(st dbq.BackupSetting, u Update) (dbq.BackupSetting, error) { + if u.Destination != DestinationFolder && u.Destination != DestinationS3 { + return st, &FieldError{"destination", "Choose a folder or an S3 bucket."} + } + if u.RunHour < 0 || u.RunHour > 23 { + return st, &FieldError{"run_hour", "The hour is from 0 to 23."} + } + if u.UploadLimitKiB < 0 || u.UploadLimitKiB > 1<<30 { + return st, &FieldError{"upload_limit_kib", "The upload limit is 0 (no limit) or more."} + } + folder := strings.TrimSpace(u.Folder) + if folder != "" && !filepath.IsAbs(folder) { + return st, &FieldError{"folder", "Give the folder's full path, starting with /."} + } + endpoint := strings.TrimRight(strings.TrimSpace(u.Endpoint), "/") + if endpoint != "" { + e, err := url.Parse(endpoint) + if err != nil || (e.Scheme != "http" && e.Scheme != "https") || e.Host == "" { + return st, &FieldError{"endpoint", "Give the endpoint as a URL, such as https://s3.example.com."} + } + } + st.Enabled = u.Enabled + st.Destination = u.Destination + st.Folder = filepath.Clean(folder) + if folder == "" { + st.Folder = "" + } + st.Endpoint = endpoint + st.Bucket = strings.TrimSpace(u.Bucket) + st.AccessKey = strings.TrimSpace(u.AccessKey) + st.RunHour = int16(u.RunHour) + st.UploadLimitKib = int32(u.UploadLimitKiB) + st.IncludeMusic = u.IncludeMusic + if u.SecretKey != "" { + sealed, err := secret.Seal(secret.BackupSecretKey.Purpose(), "", u.SecretKey) + if err != nil { + return st, err + } + st.SecretKey = sealed + } + return st, nil +} + +// Save stores u. A value that can't be kept is a *FieldError and nothing is +// stored. Settings that are incomplete still save; Status lists what's missing. +func (s *Service) Save(ctx context.Context, u Update) error { + st, err := s.settings(ctx) + if err != nil { + return err + } + st, err = merge(st, u) + if err != nil { + return err + } + return dbq.New(s.pool).SaveBackupSettings(ctx, dbq.SaveBackupSettingsParams{ + Enabled: st.Enabled, + Destination: st.Destination, + Folder: st.Folder, + Endpoint: st.Endpoint, + Bucket: st.Bucket, + AccessKey: st.AccessKey, + SecretKey: st.SecretKey, + RunHour: st.RunHour, + UploadLimitKib: st.UploadLimitKib, + IncludeMusic: st.IncludeMusic, + }) +} + +// problems is what stops a backup from running with these settings, in words. +func problems(st dbq.BackupSetting) []string { + var out []string + switch st.Destination { + case DestinationFolder: + if st.Folder == "" { + out = append(out, "Choose the folder backups are written to.") + } + case DestinationS3: + if st.Endpoint == "" { + out = append(out, "Enter the bucket's endpoint.") + } + if st.Bucket == "" { + out = append(out, "Enter the bucket's name.") + } + if st.AccessKey == "" { + out = append(out, "Enter the access key.") + } + if st.SecretKey == "" { + out = append(out, "Enter the secret key.") + } + default: + out = append(out, "Choose where backups go.") + } + return out +} + +func timeOf(t pgtype.Timestamptz) time.Time { + if !t.Valid || t.Time.Unix() <= 0 { + return time.Time{} + } + return t.Time +} + +func ptr(t time.Time) *time.Time { + if t.IsZero() { + return nil + } + return &t +} + +// runTimes is what the verdict and the schedule turn on. A zero time is a run +// that never happened. +type runTimes struct { + lastSuccess, lastAttempt, failingSince time.Time +} + +func (s *Service) times(ctx context.Context) (runTimes, error) { + row, err := dbq.New(s.pool).BackupRunTimes(ctx) + if err != nil { + return runTimes{}, fmt.Errorf("backup: read run times: %w", err) + } + return runTimes{timeOf(row.LastSuccess), timeOf(row.LastAttempt), timeOf(row.FailingSince)}, nil +} + +// slotBefore is the latest scheduled start at or before now: today at hour +// UTC, or yesterday's if that hour hasn't come yet. +func slotBefore(now time.Time, hour int) time.Time { + now = now.UTC() + slot := time.Date(now.Year(), now.Month(), now.Day(), hour, 0, 0, 0, time.UTC) + if slot.After(now) { + slot = slot.AddDate(0, 0, -1) + } + return slot +} + +// due reports when the schedule next starts a backup: now or earlier means +// the next tick starts one. A slot that passed with no attempt since is due, +// so a server that was down at the hour catches up. A run that failed is +// tried again, waiting at least retryAfter and then as long again as it has +// been failing, until it succeeds or the next slot comes. +func due(now time.Time, hour int, t runTimes) time.Time { + slot := slotBefore(now, hour) + if t.lastAttempt.Before(slot) { + return slot + } + next := slot.AddDate(0, 0, 1) + if !t.failingSince.IsZero() { + wait := max(retryAfter, t.lastAttempt.Sub(t.failingSince)) + if retry := t.lastAttempt.Add(wait); retry.Before(next) { + return retry + } + } + return next +} + +func verdict(st dbq.BackupSetting, probs []string, t runTimes, now time.Time) string { + switch { + case !st.Enabled: + return StateOff + case len(probs) > 0: + return StateIncomplete + case !t.failingSince.IsZero(): + return StateFailing + case t.lastSuccess.IsZero(): + return StateWaiting + case now.Sub(t.lastSuccess) > overdueAfter: + return StateOverdue + } + return StateOK +} + +func uuidText(u pgtype.UUID) string { + b := u.Bytes + return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) +} + +// Status is the verdict, what stands in its way, and the recent runs. +func (s *Service) Status(ctx context.Context) (Status, error) { + st, err := s.settings(ctx) + if err != nil { + return Status{}, err + } + t, err := s.times(ctx) + if err != nil { + return Status{}, err + } + rows, err := dbq.New(s.pool).ListBackupRuns(ctx, recentRuns) + if err != nil { + return Status{}, fmt.Errorf("backup: list runs: %w", err) + } + now := s.now() + probs := problems(st) + out := Status{ + Config: view(st), + State: verdict(st, probs, t, now), + Problems: probs, + LastSuccess: ptr(t.lastSuccess), + FailingSince: ptr(t.failingSince), + RunLimitSeconds: int(runLimit(st) / time.Second), + Runs: make([]Run, 0, len(rows)), + } + if out.Problems == nil { + out.Problems = []string{} + } + if st.IncludeMusic { + if out.Music, err = s.musicProgress(ctx); err != nil { + return Status{}, err + } + } + s.mu.Lock() + out.RunningSince = ptr(s.runningSince) + s.mu.Unlock() + if st.Enabled && len(probs) == 0 { + next := due(now, int(st.RunHour), t) + if next.Before(now) { + // Due now: the next tick starts it. + next = now + } + out.NextRun = &next + } + for _, r := range rows { + out.Runs = append(out.Runs, Run{ + ID: uuidText(r.ID), + Trigger: r.Trigger, + Status: r.Status, + StartedAt: r.StartedAt.Time, + FinishedAt: ptr(timeOf(r.FinishedAt)), + Location: r.Location, + Bytes: r.Bytes, + Error: r.Error, + MusicFiles: int(r.MusicFiles), + MusicBytes: r.MusicBytes, + MusicNote: r.MusicNote, + }) + } + return out, nil +} + +func bucketOf(st dbq.BackupSetting) (Bucket, error) { + key, err := secret.Open(secret.BackupSecretKey.Purpose(), "", st.SecretKey) + if err != nil { + return Bucket{}, fmt.Errorf("backup: the stored secret key doesn't open; enter it again: %w", err) + } + return Bucket{Endpoint: st.Endpoint, Name: st.Bucket, AccessKey: st.AccessKey, SecretKey: key}, nil +} + +// Test checks the destination u describes, falling back to the stored +// secret key when u leaves it empty. It only reads: it lists the backups +// already there and writes nothing. +func (s *Service) Test(ctx context.Context, u Update) (TestResult, error) { + st, err := s.settings(ctx) + if err != nil { + return TestResult{}, err + } + st, err = merge(st, u) + if err != nil { + return TestResult{}, err + } + if probs := problems(st); len(probs) > 0 { + return TestResult{}, fmt.Errorf("%w: %s", ErrNotReady, strings.Join(probs, " ")) + } + ctx, cancel := context.WithTimeout(ctx, testTimeout) + defer cancel() + + var res TestResult + note := func(name string, at time.Time) { + if !IsFileName(name) { + return + } + res.Backups++ + if res.Latest == nil || at.After(*res.Latest) { + res.Latest = &at + } + } + if st.Destination == DestinationFolder { + if err := isFolder(st.Folder); err != nil { + return res, err + } + entries, err := os.ReadDir(filepath.Join(st.Folder, databaseDir)) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return res, fmt.Errorf("backup: read %s: %w", filepath.Join(st.Folder, databaseDir), err) + } + for _, e := range entries { + if info, err := e.Info(); err == nil && info.Mode().IsRegular() { + note(e.Name(), info.ModTime()) + } + } + return res, nil + } + b, err := bucketOf(st) + if err != nil { + return res, err + } + objs, err := b.List(ctx, databaseDir+"/", 1000) + if err != nil { + return res, err + } + for _, o := range objs { + note(path.Base(o.Key), o.LastModified) + } + return res, nil +} + +// isFolder refuses a folder that isn't there. A backup never creates the +// destination folder itself: a missing one usually means a volume that +// isn't mounted, and writing beside it would fill the server's own disk. +func isFolder(dir string) error { + info, err := os.Stat(dir) + if err != nil { + return fmt.Errorf("backup: the folder %s isn't there; is its volume mounted? %w", dir, err) + } + if !info.IsDir() { + return fmt.Errorf("backup: %s is a file, not a folder", dir) + } + return nil +} + +// Start begins a backup in the background and returns at once. It returns +// ErrRunning while one runs, ErrNotReady when the destination isn't set up, +// and ErrClosed once the server is shutting down. +func (s *Service) Start(ctx context.Context, trigger string) error { + st, err := s.settings(ctx) + if err != nil { + return err + } + if len(problems(st)) > 0 { + return ErrNotReady + } + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return ErrClosed + } + if !s.runningSince.IsZero() { + return ErrRunning + } + s.runningSince = s.now() + s.wg.Add(1) + go func() { + defer s.wg.Done() + defer func() { + s.mu.Lock() + s.runningSince = time.Time{} + s.mu.Unlock() + }() + periodic.Safe(context.Background(), s.logger, "backup run", func(context.Context) { s.run(trigger, st) }) + }() + return nil +} + +// Running reports when the running backup started, or the zero time. +func (s *Service) Running() time.Time { + s.mu.Lock() + defer s.mu.Unlock() + return s.runningSince +} + +// runLimit is the longest a run may take: the database file, and the +// music's nightly budget when the backup includes the music. +func runLimit(st dbq.BackupSetting) time.Duration { + if st.IncludeMusic { + return RunLimit + MusicBudget + } + return RunLimit +} + +func (s *Service) run(trigger string, st dbq.BackupSetting) { + ctx, cancel := context.WithTimeout(s.base, RunLimit) + defer cancel() + q := dbq.New(s.pool) + started, err := q.StartBackupRun(ctx, trigger) + if err != nil { + s.logger.Error("backup: record the run's start", "err", err) + return + } + location, size, err := s.write(ctx, st, started.StartedAt.Time) + // The music goes only after the database file has landed, which also + // proves the destination takes writes. + var music musicSent + if err == nil && st.IncludeMusic { + mctx, mcancel := context.WithTimeout(s.base, MusicBudget) + music = s.sendMusic(mctx, st) + mcancel() + } + + // The finish is recorded on its own context, so a run stopped by a + // shutdown or its time limit still says how it ended. + fctx, fcancel := context.WithTimeout(context.Background(), 10*time.Second) + defer fcancel() + fin := dbq.FinishBackupRunParams{ + ID: started.ID, Status: "succeeded", Location: location, Bytes: size, + MusicFiles: int32(music.files), MusicBytes: music.bytes, MusicNote: music.note, + } + if err != nil { + fin.Status, fin.Error = "failed", describe(err) + s.logger.Warn("backup failed", "trigger", trigger, "err", err) + } else { + s.logger.Info("backup written", "trigger", trigger, "location", location, "bytes", size, + "music_files", music.files, "music_bytes", music.bytes, "music_note", music.note) + } + if err := q.FinishBackupRun(fctx, fin); err != nil { + s.logger.Error("backup: record the run's end", "err", err) + } + if _, err := q.PruneBackupRuns(fctx, pgtype.Timestamptz{Time: s.now().Add(-keepRunsFor), Valid: true}); err != nil { + s.logger.Warn("backup: prune old runs", "err", err) + } +} + +// describe is a run's error as the panel shows it. +func describe(err error) string { + switch { + case errors.Is(err, context.DeadlineExceeded): + return fmt.Sprintf("The backup took longer than %d minutes and was stopped.", int(RunLimit/time.Minute)) + case errors.Is(err, context.Canceled): + return "The server stopped while the backup was running." + } + return strings.TrimPrefix(err.Error(), "backup: ") +} + +// write snapshots the database into one backup file at the destination and +// returns where it went and its size. +func (s *Service) write(ctx context.Context, st dbq.BackupSetting, at time.Time) (string, int64, error) { + if st.Destination == DestinationFolder { + // Checked before the snapshot, so a missing volume costs nothing. + if err := isFolder(st.Folder); err != nil { + return "", 0, err + } + } + c, err := Snapshot(ctx, s.pool) + if err != nil { + return "", 0, err + } + if st.Destination == DestinationFolder { + dir := filepath.Join(st.Folder, databaseDir) + if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return "", 0, fmt.Errorf("backup: create %s: %w", dir, err) + } + file, _, err := WriteFile(dir, c, at, s.build) + if err != nil { + return "", 0, err + } + info, err := os.Stat(file) + if err != nil { + return file, 0, err + } + return file, info.Size(), nil + } + + b, err := bucketOf(st) + if err != nil { + return "", 0, err + } + // The file is written to a temporary file first: S3 signs over the + // body's hash and needs its length before the upload starts. + tmp, err := os.CreateTemp("", ".minstrel-backup-*.tar") + if err != nil { + return "", 0, fmt.Errorf("backup: create a temporary file: %w", err) + } + defer func() { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + }() + h := sha256.New() + if _, err := Write(io.MultiWriter(tmp, h), c, at, s.build); err != nil { + return "", 0, fmt.Errorf("backup: write the temporary file: %w", err) + } + size, err := tmp.Seek(0, io.SeekCurrent) + if err == nil { + _, err = tmp.Seek(0, io.SeekStart) + } + if err != nil { + return "", 0, fmt.Errorf("backup: rewind the temporary file: %w", err) + } + key := databaseDir + "/" + FileName(at) + body := Throttle(ctx, tmp, int64(st.UploadLimitKib)*1024) + if err := b.Put(ctx, key, body, size, hex.EncodeToString(h.Sum(nil))); err != nil { + return "", 0, err + } + return key, size, nil +} + +// Tick starts a scheduled backup when one is due. A backup that is already +// running, or settings that aren't ready, mean there's nothing to do. +func (s *Service) Tick(ctx context.Context) { + st, err := s.settings(ctx) + if err != nil { + s.logger.Warn("backup: tick", "err", err) + return + } + if !st.Enabled || len(problems(st)) > 0 { + return + } + t, err := s.times(ctx) + if err != nil { + s.logger.Warn("backup: tick", "err", err) + return + } + if due(s.now(), int(st.RunHour), t).After(s.now()) { + return + } + if err := s.Start(ctx, TriggerSchedule); err != nil && !errors.Is(err, ErrRunning) && !errors.Is(err, ErrClosed) { + s.logger.Warn("backup: start the scheduled backup", "err", err) + } +} + +// Recover marks runs a stopped server left running as failed. It runs once +// at startup, before the first tick. +func (s *Service) Recover(ctx context.Context) { + n, err := dbq.New(s.pool).FailUnfinishedBackupRuns(ctx) + if err != nil { + s.logger.Warn("backup: recover unfinished runs", "err", err) + return + } + if n > 0 { + s.logger.Warn("backup: a run was cut off by the last shutdown", "runs", n) + } +} + +// Loop recovers, then ticks until ctx ends. The first tick waits a full +// interval, so a restart isn't followed straight away by a backup. +func (s *Service) Loop(ctx context.Context) { + periodic.Safe(ctx, s.logger, "backup recover", s.Recover) + periodic.Run(ctx, s.logger, "backup", tickEvery, s.Tick, periodic.Delayed()) +} + +// Close stops a running backup and waits for it to record how it ended. +func (s *Service) Close() { + s.mu.Lock() + s.closed = true + s.mu.Unlock() + s.cancel() + s.wg.Wait() +} diff --git a/internal/backup/service_integration_test.go b/internal/backup/service_integration_test.go new file mode 100644 index 00000000..e20701c1 --- /dev/null +++ b/internal/backup/service_integration_test.go @@ -0,0 +1,282 @@ +package backup_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/backup" + "github.com/Fabled-Sword/minstrel/internal/dbtest" +) + +func newService(t *testing.T) (*backup.Service, *pgxpool.Pool) { + t.Helper() + pool := dbtest.Pool(t) + svc := backup.NewService(pool, slog.New(slog.NewTextHandler(io.Discard, nil)), "test-build") + t.Cleanup(svc.Close) + return svc, pool +} + +// waitIdle waits for the running backup to finish, for at most 30 seconds. +func waitIdle(t *testing.T, svc *backup.Service) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for !svc.Running().IsZero() { + if time.Now().After(deadline) { + t.Fatal("the backup is still running after 30s") + } + time.Sleep(20 * time.Millisecond) + } +} + +func status(t *testing.T, svc *backup.Service) backup.Status { + t.Helper() + st, err := svc.Status(context.Background()) + if err != nil { + t.Fatal(err) + } + return st +} + +func TestABackupIsOffAndRefusesToStartUntilSetUp_Integration(t *testing.T) { + svc, _ := newService(t) + st := status(t, svc) + if st.State != backup.StateOff || st.Config.Enabled || st.NextRun != nil || len(st.Runs) != 0 { + t.Errorf("a fresh server's backup = %+v, want off with no runs", st) + } + if err := svc.Start(context.Background(), backup.TriggerManual); !errors.Is(err, backup.ErrNotReady) { + t.Errorf("Start = %v, want ErrNotReady", err) + } + if err := svc.Save(context.Background(), backup.Update{Enabled: true, Destination: backup.DestinationS3, RunHour: 3}); err != nil { + t.Fatal(err) + } + if st := status(t, svc); st.State != backup.StateIncomplete || len(st.Problems) != 4 { + t.Errorf("switched on with no bucket: %s %v", st.State, st.Problems) + } +} + +func TestABackupRunsIntoAFolder_Integration(t *testing.T) { + svc, _ := newService(t) + dir := t.TempDir() + ctx := context.Background() + if err := svc.Save(ctx, backup.Update{Enabled: true, Destination: backup.DestinationFolder, Folder: dir, RunHour: 3}); err != nil { + t.Fatal(err) + } + if st := status(t, svc); st.State != backup.StateWaiting || st.NextRun == nil { + t.Errorf("set up, never run: %s next %v", st.State, st.NextRun) + } + if err := svc.Start(ctx, backup.TriggerManual); err != nil { + t.Fatal(err) + } + waitIdle(t, svc) + + st := status(t, svc) + if st.State != backup.StateOK || len(st.Runs) != 1 || st.LastSuccess == nil { + t.Fatalf("after a run: %+v", st) + } + run := st.Runs[0] + if run.Status != "succeeded" || run.Trigger != backup.TriggerManual || run.FinishedAt == nil || + filepath.Dir(run.Location) != filepath.Join(dir, "database") || run.Error != "" { + t.Fatalf("run = %+v", run) + } + f, err := os.Open(run.Location) + if err != nil { + t.Fatal(err) + } + defer func() { _ = f.Close() }() + info, _ := f.Stat() + if info.Size() != run.Bytes { + t.Errorf("recorded %d bytes, the file holds %d", run.Bytes, info.Size()) + } + m, _, err := backup.Read(f) + if err != nil || m.Build != "test-build" { + t.Errorf("the backup reads back as %+v, %v", m, err) + } + + res, err := svc.Test(ctx, backup.Update{Destination: backup.DestinationFolder, Folder: dir, RunHour: 3}) + if err != nil || res.Backups != 1 || res.Latest == nil { + t.Errorf("Test = %+v, %v; want the one backup", res, err) + } +} + +func TestAMissingFolderFailsTheRunAndSaysSo_Integration(t *testing.T) { + svc, _ := newService(t) + ctx := context.Background() + missing := filepath.Join(t.TempDir(), "not-mounted") + if err := svc.Save(ctx, backup.Update{Enabled: true, Destination: backup.DestinationFolder, Folder: missing, RunHour: 3}); err != nil { + t.Fatal(err) + } + if _, err := svc.Test(ctx, backup.Update{Destination: backup.DestinationFolder, Folder: missing}); err == nil { + t.Error("Test passed on a missing folder") + } + if err := svc.Start(ctx, backup.TriggerManual); err != nil { + t.Fatal(err) + } + waitIdle(t, svc) + st := status(t, svc) + if st.State != backup.StateFailing || st.FailingSince == nil || len(st.Runs) != 1 || + !strings.Contains(st.Runs[0].Error, "isn't there") { + t.Errorf("after a failed run: %s %+v", st.State, st.Runs) + } + if _, err := os.Stat(missing); !os.IsNotExist(err) { + t.Error("the run created the missing folder") + } +} + +// fakeBucket answers PUTs and lists like an S3 bucket. While hold is open a +// PUT waits on it. +type fakeBucket struct { + mu sync.Mutex + puts map[string][]byte + hold chan struct{} +} + +func (b *fakeBucket) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.Header.Get("Authorization"), "AWS4-HMAC-SHA256 Credential=ak/") { + w.WriteHeader(http.StatusForbidden) + return + } + switch r.Method { + case http.MethodPut: + if b.hold != nil { + <-b.hold + } + body, _ := io.ReadAll(r.Body) + b.mu.Lock() + b.puts[r.URL.Path] = body + b.mu.Unlock() + case http.MethodGet: + b.mu.Lock() + defer b.mu.Unlock() + _, _ = fmt.Fprint(w, `false`) + for p, body := range b.puts { + _, _ = fmt.Fprintf(w, `%s%d2026-11-02T03:00:05.000Z`, + strings.TrimPrefix(p, "/minstrel/"), len(body)) + } + _, _ = fmt.Fprint(w, ``) + } +} + +func bucketUpdate(endpoint string) backup.Update { + return backup.Update{Enabled: true, Destination: backup.DestinationS3, Endpoint: endpoint, + Bucket: "minstrel", AccessKey: "ak", SecretKey: "sk", RunHour: 3} +} + +func TestABackupRunsIntoABucket_Integration(t *testing.T) { + svc, pool := newService(t) + fake := &fakeBucket{puts: map[string][]byte{}} + srv := httptest.NewServer(fake) + defer srv.Close() + ctx := context.Background() + + if err := svc.Save(ctx, bucketUpdate(srv.URL)); err != nil { + t.Fatal(err) + } + var stored string + if err := pool.QueryRow(ctx, "SELECT secret_key FROM backup_settings").Scan(&stored); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(stored, "v1.") { + t.Fatalf("the secret key is stored as %q, want it sealed", stored) + } + if cfg, _ := svc.Config(ctx); !cfg.HasSecretKey { + t.Error("the config doesn't say a secret key is stored") + } + if err := svc.Start(ctx, backup.TriggerManual); err != nil { + t.Fatal(err) + } + waitIdle(t, svc) + + st := status(t, svc) + if st.State != backup.StateOK || len(st.Runs) != 1 || st.Runs[0].Status != "succeeded" { + t.Fatalf("after a run: %s %+v", st.State, st.Runs) + } + key := st.Runs[0].Location + if !strings.HasPrefix(key, "database/minstrel-") || !backup.IsFileName(filepath.Base(key)) { + t.Errorf("stored under %q", key) + } + fake.mu.Lock() + body := fake.puts["/minstrel/"+key] + fake.mu.Unlock() + if int64(len(body)) != st.Runs[0].Bytes { + t.Errorf("the bucket got %d bytes, the run recorded %d", len(body), st.Runs[0].Bytes) + } + if _, _, err := backup.Read(bytes.NewReader(body)); err != nil { + t.Errorf("the uploaded backup doesn't read: %v", err) + } + + // The test sends no secret key: it uses the stored one, and only lists. + u := bucketUpdate(srv.URL) + u.SecretKey = "" + res, err := svc.Test(ctx, u) + if err != nil || res.Backups != 1 { + t.Errorf("Test = %+v, %v; want the one backup", res, err) + } + fake.mu.Lock() + defer fake.mu.Unlock() + if len(fake.puts) != 1 { + t.Errorf("the test wrote to the bucket: %d objects", len(fake.puts)) + } +} + +func TestOneBackupAtATime_Integration(t *testing.T) { + svc, _ := newService(t) + fake := &fakeBucket{puts: map[string][]byte{}, hold: make(chan struct{})} + srv := httptest.NewServer(fake) + defer srv.Close() + ctx := context.Background() + if err := svc.Save(ctx, bucketUpdate(srv.URL)); err != nil { + t.Fatal(err) + } + if err := svc.Start(ctx, backup.TriggerManual); err != nil { + t.Fatal(err) + } + if err := svc.Start(ctx, backup.TriggerManual); !errors.Is(err, backup.ErrRunning) { + t.Errorf("a second Start = %v, want ErrRunning", err) + } + if st := status(t, svc); st.RunningSince == nil { + t.Error("the status doesn't say a backup is running") + } + close(fake.hold) + waitIdle(t, svc) +} + +func TestRecoverFailsARunTheLastShutdownCutOff_Integration(t *testing.T) { + svc, pool := newService(t) + ctx := context.Background() + if _, err := pool.Exec(ctx, "INSERT INTO backup_runs (trigger) VALUES ('schedule')"); err != nil { + t.Fatal(err) + } + svc.Recover(ctx) + st := status(t, svc) + if len(st.Runs) != 1 || st.Runs[0].Status != "failed" || st.Runs[0].FinishedAt == nil || + !strings.Contains(st.Runs[0].Error, "server stopped") { + t.Errorf("runs = %+v", st.Runs) + } +} + +func TestSaveRefusesABadValueAndKeepsTheOldSettings_Integration(t *testing.T) { + svc, _ := newService(t) + ctx := context.Background() + err := svc.Save(ctx, backup.Update{Enabled: true, Destination: backup.DestinationFolder, Folder: "relative/path"}) + var fe *backup.FieldError + if !errors.As(err, &fe) || fe.Field != "folder" { + t.Fatalf("err = %v, want a FieldError on folder", err) + } + if cfg, _ := svc.Config(ctx); cfg.Enabled || cfg.Folder != "" { + t.Errorf("a refused save changed the settings: %+v", cfg) + } +} diff --git a/internal/backup/service_test.go b/internal/backup/service_test.go new file mode 100644 index 00000000..20572b08 --- /dev/null +++ b/internal/backup/service_test.go @@ -0,0 +1,171 @@ +package backup + +import ( + "bytes" + "context" + "errors" + "io" + "strings" + "testing" + "time" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" +) + +func at(s string) time.Time { + t, err := time.Parse(time.RFC3339, s) + if err != nil { + panic(err) + } + return t +} + +func TestDueRunsAtTheHourCatchesUpAndBacksOffAfterAFailure(t *testing.T) { + cases := []struct { + name string + now string + t runTimes + want string + }{ + {"never run: the slot that passed is due", "2026-11-02T10:00:00Z", + runTimes{}, "2026-11-02T03:00:00Z"}, + {"ran at the hour: tomorrow's slot", "2026-11-02T10:00:00Z", + runTimes{lastSuccess: at("2026-11-02T03:00:05Z"), lastAttempt: at("2026-11-02T03:00:05Z")}, "2026-11-03T03:00:00Z"}, + {"before today's hour, yesterday's ran: today's slot", "2026-11-02T02:00:00Z", + runTimes{lastSuccess: at("2026-11-01T03:00:05Z"), lastAttempt: at("2026-11-01T03:00:05Z")}, "2026-11-02T03:00:00Z"}, + {"server was down at the hour: catches up", "2026-11-02T10:00:00Z", + runTimes{lastSuccess: at("2026-11-01T03:00:05Z"), lastAttempt: at("2026-11-01T03:00:05Z")}, "2026-11-02T03:00:00Z"}, + {"first failure: an hour later", "2026-11-02T03:30:00Z", + runTimes{lastAttempt: at("2026-11-02T03:00:00Z"), failingSince: at("2026-11-02T03:00:00Z")}, "2026-11-02T04:00:00Z"}, + {"failing for two hours: two hours later", "2026-11-02T05:30:00Z", + runTimes{lastAttempt: at("2026-11-02T05:00:00Z"), failingSince: at("2026-11-02T03:00:00Z")}, "2026-11-02T07:00:00Z"}, + {"a retry past the next slot waits for the slot", "2026-11-02T19:30:00Z", + runTimes{lastAttempt: at("2026-11-02T19:00:00Z"), failingSince: at("2026-11-02T03:00:00Z")}, "2026-11-03T03:00:00Z"}, + } + for _, c := range cases { + if got := due(at(c.now), 3, c.t); !got.Equal(at(c.want)) { + t.Errorf("%s: due = %s, want %s", c.name, got.Format(time.RFC3339), c.want) + } + } +} + +func TestTheHourIsUTC(t *testing.T) { + // 22:00 at UTC-5 is 03:00 UTC the next day, which is that day's slot. + now := time.Date(2026, 11, 1, 22, 0, 0, 0, time.FixedZone("x", -5*3600)) + if got := slotBefore(now, 3); !got.Equal(at("2026-11-02T03:00:00Z")) { + t.Errorf("slot = %s", got) + } +} + +func TestVerdict(t *testing.T) { + now := at("2026-11-02T10:00:00Z") + on := dbq.BackupSetting{Enabled: true} + good := runTimes{lastSuccess: at("2026-11-02T03:00:00Z"), lastAttempt: at("2026-11-02T03:00:00Z")} + cases := []struct { + name string + st dbq.BackupSetting + probs []string + t runTimes + want string + }{ + {"switched off, even with problems and failures", dbq.BackupSetting{}, []string{"x"}, runTimes{failingSince: now}, StateOff}, + {"on but not set up", on, []string{"x"}, good, StateIncomplete}, + {"the latest run failed", on, nil, runTimes{lastSuccess: good.lastSuccess, failingSince: now}, StateFailing}, + {"nothing has run yet", on, nil, runTimes{}, StateWaiting}, + {"the latest backup is old", on, nil, runTimes{lastSuccess: now.Add(-27 * time.Hour)}, StateOverdue}, + {"a day and a bit is still fine", on, nil, runTimes{lastSuccess: now.Add(-25 * time.Hour)}, StateOK}, + {"fine", on, nil, good, StateOK}, + } + for _, c := range cases { + if got := verdict(c.st, c.probs, c.t, now); got != c.want { + t.Errorf("%s: %s, want %s", c.name, got, c.want) + } + } +} + +func TestProblemsNameWhatIsMissing(t *testing.T) { + if p := problems(dbq.BackupSetting{Destination: DestinationS3}); len(p) != 4 { + t.Errorf("an empty bucket: %v, want endpoint, name, access key and secret key", p) + } + if p := problems(dbq.BackupSetting{Destination: DestinationS3, Endpoint: "https://s3.example.com", Bucket: "b", AccessKey: "a", SecretKey: "v1.x"}); len(p) != 0 { + t.Errorf("a whole bucket: %v", p) + } + if p := problems(dbq.BackupSetting{Destination: DestinationFolder}); len(p) != 1 { + t.Errorf("an empty folder: %v", p) + } + if p := problems(dbq.BackupSetting{Destination: DestinationFolder, Folder: "/backups"}); len(p) != 0 { + t.Errorf("a folder: %v", p) + } +} + +func TestMergeRefusesWhatCannotBeKept(t *testing.T) { + ok := Update{Destination: DestinationS3, RunHour: 3} + for field, u := range map[string]func(Update) Update{ + "destination": func(u Update) Update { u.Destination = "ftp"; return u }, + "run_hour": func(u Update) Update { u.RunHour = 24; return u }, + "upload_limit_kib": func(u Update) Update { u.UploadLimitKiB = -1; return u }, + "folder": func(u Update) Update { u.Folder = "backups"; return u }, + "endpoint": func(u Update) Update { u.Endpoint = "s3.example.com"; return u }, + } { + _, err := merge(dbq.BackupSetting{}, u(ok)) + var fe *FieldError + if !errors.As(err, &fe) || fe.Field != field { + t.Errorf("%s: err = %v, want a FieldError on it", field, err) + } + } +} + +func TestMergeTidiesAndKeepsTheStoredSecret(t *testing.T) { + st, err := merge(dbq.BackupSetting{SecretKey: "v1.stored"}, Update{ + Enabled: true, Destination: DestinationS3, Endpoint: " https://s3.example.com/ ", + Bucket: " minstrel ", AccessKey: " ak ", RunHour: 4, UploadLimitKiB: 512, Folder: "/srv/backups/", + }) + if err != nil { + t.Fatal(err) + } + if st.Endpoint != "https://s3.example.com" || st.Bucket != "minstrel" || st.AccessKey != "ak" || + st.SecretKey != "v1.stored" || st.RunHour != 4 || st.UploadLimitKib != 512 || st.Folder != "/srv/backups" || !st.Enabled { + t.Errorf("merged = %+v", st) + } +} + +func TestThrottleKeepsToItsRate(t *testing.T) { + data := bytes.Repeat([]byte("x"), 20*1024) + start := time.Now() + got, err := io.ReadAll(Throttle(context.Background(), bytes.NewReader(data), 100*1024)) + if err != nil || !bytes.Equal(got, data) { + t.Fatalf("read %d bytes, err %v", len(got), err) + } + // 20 KiB at 100 KiB a second takes at least a fifth of a second. + if took := time.Since(start); took < 180*time.Millisecond { + t.Errorf("took %s, want at least 200ms", took) + } +} + +func TestThrottleWithNoLimitIsTheReaderItself(t *testing.T) { + r := strings.NewReader("x") + if Throttle(context.Background(), r, 0) != io.Reader(r) { + t.Error("a zero limit wrapped the reader") + } +} + +func TestThrottleStopsWhenItsContextEnds(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := io.ReadAll(Throttle(ctx, bytes.NewReader(make([]byte, 4096)), 1024)) + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } +} + +func TestDescribeSaysWhyARunStopped(t *testing.T) { + if got := describe(context.DeadlineExceeded); !strings.Contains(got, "longer than 30 minutes") { + t.Errorf("deadline: %q", got) + } + if got := describe(context.Canceled); !strings.Contains(got, "server stopped") { + t.Errorf("canceled: %q", got) + } + if got := describe(errors.New("backup: the folder /x isn't there")); got != "the folder /x isn't there" { + t.Errorf("other: %q", got) + } +} diff --git a/internal/backup/sigv4.go b/internal/backup/sigv4.go new file mode 100644 index 00000000..ee676819 --- /dev/null +++ b/internal/backup/sigv4.go @@ -0,0 +1,119 @@ +package backup + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "net/http" + "net/url" + "slices" + "strings" + "time" +) + +// emptySHA256 is the payload hash of a request with no body. +const emptySHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + +// sign adds AWS Signature Version 4 headers for S3 to req: X-Amz-Date, +// X-Amz-Content-Sha256 and Authorization. Every header already on the +// request is signed, along with the host. +func sign(req *http.Request, payloadSHA256, accessKey, secretKey, region string, at time.Time) { + at = at.UTC() + stamp := at.Format("20060102T150405Z") + date := at.Format("20060102") + req.Header.Set("X-Amz-Date", stamp) + req.Header.Set("X-Amz-Content-Sha256", payloadSHA256) + + host := req.Host + if host == "" { + host = req.URL.Host + } + headers := map[string]string{"host": host} + for name, values := range req.Header { + headers[strings.ToLower(name)] = strings.TrimSpace(strings.Join(values, ",")) + } + names := make([]string, 0, len(headers)) + for name := range headers { + names = append(names, name) + } + slices.Sort(names) + var canonHeaders strings.Builder + for _, name := range names { + canonHeaders.WriteString(name + ":" + headers[name] + "\n") + } + signed := strings.Join(names, ";") + + canonical := strings.Join([]string{ + req.Method, + canonicalPath(req.URL), + canonicalQuery(req.URL.Query()), + canonHeaders.String(), + signed, + payloadSHA256, + }, "\n") + scope := date + "/" + region + "/s3/aws4_request" + toSign := "AWS4-HMAC-SHA256\n" + stamp + "\n" + scope + "\n" + hexSHA256([]byte(canonical)) + + key := hmacSHA256([]byte("AWS4"+secretKey), date) + key = hmacSHA256(key, region) + key = hmacSHA256(key, "s3") + key = hmacSHA256(key, "aws4_request") + signature := hex.EncodeToString(hmacSHA256(key, toSign)) + + req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential="+accessKey+"/"+scope+ + ", SignedHeaders="+signed+", Signature="+signature) +} + +// canonicalPath is the request path with each segment URI-encoded once. +func canonicalPath(u *url.URL) string { + p := u.EscapedPath() + if p == "" { + return "/" + } + if unescaped, err := url.PathUnescape(p); err == nil { + p = unescaped + } + segments := strings.Split(p, "/") + for i, s := range segments { + segments[i] = uriEncode(s) + } + return strings.Join(segments, "/") +} + +// canonicalQuery is the query sorted by name, names and values URI-encoded. +func canonicalQuery(q url.Values) string { + pairs := make([]string, 0, len(q)) + for name, values := range q { + for _, v := range values { + pairs = append(pairs, uriEncode(name)+"="+uriEncode(v)) + } + } + slices.Sort(pairs) + return strings.Join(pairs, "&") +} + +// uriEncode percent-encodes everything but the unreserved characters, as +// SigV4 requires; url.QueryEscape differs on space and '~'. +func uriEncode(s string) string { + var b strings.Builder + for i := 0; i < len(s); i++ { + c := s[i] + if c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.' || c == '~' { + b.WriteByte(c) + continue + } + b.WriteString("%" + strings.ToUpper(hex.EncodeToString([]byte{c}))) + } + return b.String() +} + +func hmacSHA256(key []byte, msg string) []byte { + m := hmac.New(sha256.New, key) + m.Write([]byte(msg)) + return m.Sum(nil) +} + +func hexSHA256(b []byte) string { + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/backup/snapshot.go b/internal/backup/snapshot.go new file mode 100644 index 00000000..9fa716dd --- /dev/null +++ b/internal/backup/snapshot.go @@ -0,0 +1,114 @@ +package backup + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +// Contents is a backup's data: the schema version that wrote it, and each +// table's rows as JSON objects with their keys sorted, in primary-key order. +// An unchanged row is the same bytes in every backup. +type Contents struct { + Schema int64 + Tables map[string][][]byte +} + +// Snapshot reads every table in Tables as of one moment. +func Snapshot(ctx context.Context, pool *pgxpool.Pool) (Contents, error) { + c := Contents{Tables: make(map[string][][]byte, len(Tables))} + tx, err := pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}) + if err != nil { + return c, fmt.Errorf("backup: begin: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + + if c.Schema, err = schemaVersion(ctx, tx); err != nil { + return c, err + } + for _, t := range Tables { + lines, err := readTable(ctx, tx, t) + if err != nil { + return c, err + } + c.Tables[t.Name] = lines + } + return c, nil +} + +func readTable(ctx context.Context, tx pgx.Tx, t Table) ([][]byte, error) { + pk, err := primaryKey(ctx, tx, t.Name) + if err != nil { + return nil, err + } + order := make([]string, len(pk)) + for i, col := range pk { + order[i] = "t." + pgx.Identifier{col}.Sanitize() + } + omit := t.Omit + if omit == nil { + omit = []string{} + } + rows, err := tx.Query(ctx, fmt.Sprintf("SELECT to_jsonb(t) - $1::text[] FROM %s t ORDER BY %s", + pgx.Identifier{t.Name}.Sanitize(), strings.Join(order, ", ")), omit) + if err != nil { + return nil, fmt.Errorf("backup: read %s: %w", t.Name, err) + } + lines, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) ([]byte, error) { + var raw []byte + if err := row.Scan(&raw); err != nil { + return nil, err + } + return canonical(raw) + }) + if err != nil { + return nil, fmt.Errorf("backup: read %s: %w", t.Name, err) + } + return lines, nil +} + +// canonical re-encodes a row with its keys sorted. Numbers pass through as +// written, so a bigint or a float stays exact. +func canonical(raw []byte) ([]byte, error) { + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + var row map[string]any + if err := dec.Decode(&row); err != nil { + return nil, err + } + return json.Marshal(row) +} + +// primaryKey returns a table's primary-key columns in key order. +func primaryKey(ctx context.Context, tx pgx.Tx, table string) ([]string, error) { + rows, err := tx.Query(ctx, ` + SELECT a.attname + FROM pg_index i + JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY (i.indkey) + WHERE i.indrelid = to_regclass($1) AND i.indisprimary + ORDER BY array_position(i.indkey, a.attnum)`, table) + if err != nil { + return nil, fmt.Errorf("backup: read %s's primary key: %w", table, err) + } + cols, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + return nil, fmt.Errorf("backup: read %s's primary key: %w", table, err) + } + if len(cols) == 0 { + return nil, fmt.Errorf("backup: %s has no primary key to order its rows by", table) + } + return cols, nil +} + +func schemaVersion(ctx context.Context, tx pgx.Tx) (int64, error) { + var v int64 + if err := tx.QueryRow(ctx, "SELECT version FROM schema_migrations").Scan(&v); err != nil { + return 0, fmt.Errorf("backup: read the schema version: %w", err) + } + return v, nil +} diff --git a/internal/backup/tables.go b/internal/backup/tables.go new file mode 100644 index 00000000..608cd706 --- /dev/null +++ b/internal/backup/tables.go @@ -0,0 +1,184 @@ +// Package backup reads Minstrel's irreplaceable data out of Postgres as JSON +// Lines, one table at a time, and loads it back into an empty instance. +// +// What goes in is everything a person made or decided: accounts, likes, play +// and skip history, playlists, admin decisions, and settings. What stays out is everything the restored +// server rebuilds by itself: what it computes from the music files, what it +// fetches again from MusicBrainz, ListenBrainz and the other providers, and +// logs of past runs. Excluded says why for each, and the coverage test fails +// on a table that is in neither list. +package backup + +// Table is one table a backup holds. +// +// Omit names columns left out of the file. They restore to their defaults: +// - a credential Minstrel stores sealed, which only the server holding the +// stream secret could open, so it is entered again after the restore, +// and a switch that is only on while that credential is set; +// - a marker saying work on an excluded table is done (a tag source, an art +// source), so the restored server does that work again rather than +// believing it has the result. +type Table struct { + Name string + Omit []string +} + +// Tables is every table a backup holds, in the order a restore loads them: +// each after every table it references. There are no self-referencing +// tables, so no table needs its rows loaded in depth order. +var Tables = []Table{ + // Each person makes a new Subsonic password and saves their ListenBrainz + // token again in their own Settings. ListenBrainz restores to off, since + // it can't send without the token. + {Name: "users", Omit: []string{"subsonic_password", "listenbrainz_token", "listenbrainz_enabled"}}, + + // The library's identity. Every like, play and playlist entry hangs off a + // track id, so the rows travel even though a scan could rebuild most of + // their columns; the scan after a restore finds each file at its path and + // keeps its id. + {Name: "artists", Omit: []string{"artist_thumb_path", "artist_fanart_path", "artist_art_source", "artist_art_sources_version"}}, + {Name: "albums", Omit: []string{"cover_art_path", "cover_art_source", "cover_art_sources_version"}}, + {Name: "tracks", Omit: []string{"tag_source", "tag_sources_version"}}, + + // Settings. + {Name: "library_settings"}, + {Name: "network_settings"}, + {Name: "smtp_config", Omit: []string{"password"}}, + {Name: "notification_email_settings"}, + {Name: "acoustid_settings", Omit: []string{"api_key"}}, + {Name: "fingerprint_settings"}, + {Name: "loudness_settings"}, + {Name: "lookup_settings"}, + {Name: "cover_art_provider_settings", Omit: []string{"api_key"}}, + {Name: "cover_art_sources_meta"}, + {Name: "tag_provider_settings", Omit: []string{"api_key"}}, + {Name: "tag_sources_meta"}, + {Name: "taste_tuning"}, + {Name: "recommendation_weight_profiles"}, + {Name: "recommendation_tuning_audit"}, + + // Listening history and likes. + {Name: "play_sessions"}, + {Name: "play_events"}, + {Name: "skip_events"}, + {Name: "scrobble_queue"}, + {Name: "contextual_likes"}, + {Name: "general_likes"}, + {Name: "general_likes_albums"}, + {Name: "general_likes_artists"}, + + // Playlists and what is built from history. The taste profile and the + // "you might like" rows are rebuilt nightly from the history above; they + // travel so a restored Home is full before that first nightly pass. + // A collage is a file in the data directory, which the backup doesn't + // carry; the restored server draws each one again. + {Name: "playlists", Omit: []string{"cover_path"}}, + {Name: "playlist_tracks"}, + {Name: "system_playlist_runs"}, + {Name: "system_playlist_rotation_state"}, + {Name: "taste_profile_artists"}, + {Name: "taste_profile_tags"}, + {Name: "taste_profile_eras"}, + {Name: "taste_profile_moods"}, + {Name: "you_might_like_albums"}, + {Name: "you_might_like_artists"}, + + // Per-user preferences and notifications. + {Name: "user_normalization_prefs"}, + // The queue a Subsonic app saved, so it resumes where it was. + {Name: "play_queues"}, + {Name: "user_notification_prefs"}, + {Name: "user_notification_email_state"}, + {Name: "user_notifications"}, + {Name: "quarantine"}, + {Name: "quarantine_actions"}, + + // Admin decisions: a dismissed duplicate group stays dismissed when the + // sweep finds it again. + {Name: "duplicate_sweeps"}, + {Name: "duplicate_groups"}, + {Name: "duplicate_group_members"}, + + // The library change feed is how the apps sync, including a first sync, + // so a restored server carries it on from where the backup left it. + {Name: "library_changes"}, + {Name: "library_changes_trimmed"}, + {Name: "audit_log"}, + {Name: "playback_errors"}, +} + +// Excluded is every table a backup leaves out, with the reason. +var Excluded = map[string]string{ + "schema_migrations": "the restored server's own migrations write it; the backup's schema version is in its manifest", + "sessions": "sign-ins; everyone signs in again on the restored server", + "password_resets": "one-time reset links, which expire within hours", + "playlist_append_requests": "replay guards for appends a phone sent; the restored server has received none of them", + "user_invites": "open sign-up links; an admin sends an invite again from the restored server", + + "track_fingerprints": "computed from the music files", + "track_loudness": "computed from the music files", + "album_loudness": "computed from the music files", + "track_acoustid_lookups": "looked up again from each track's fingerprint", + "track_tags": "fetched again from the tag providers", + + "mb_release_groups": "MusicBrainz cache, fetched again", + "mb_releases": "MusicBrainz cache, fetched again", + "mb_release_tracks": "MusicBrainz cache, fetched again", + + "listenbrainz_similar_recordings": "similarity, fetched again from ListenBrainz", + "track_similarity": "similarity, fetched again from the similarity providers", + "track_similarity_fetches": "similarity, fetched again from the similarity providers", + "artist_similarity": "similarity, fetched again from the similarity providers", + "artist_similarity_fetches": "similarity, fetched again from the similarity providers", + + "scan_runs": "a log of past library scans", + "diagnostic_events": "debug-mode diagnostics", + + "backup_settings": "holds the bucket's secret key; point the restored server at its destination again", + "backup_runs": "this server's own backup history", + "backup_music_files": "which music files this server has sent; the files themselves are beside the database in the destination", +} + +// carried reports whether a table is in Tables. +func carried(name string) bool { + for _, t := range Tables { + if t.Name == name { + return true + } + } + return false +} + +// Coverage checks a schema's tables against Tables and Excluded. It returns +// one line per problem: a table in neither list, in both, or listed twice, +// and a listed table the schema doesn't have. +func Coverage(schema []string) []string { + var problems []string + inSchema := map[string]bool{} + for _, name := range schema { + inSchema[name] = true + _, excluded := Excluded[name] + switch { + case carried(name) && excluded: + problems = append(problems, name+": both backed up and excluded") + case !carried(name) && !excluded: + problems = append(problems, name+": neither backed up nor excluded; add it to Tables, or to Excluded with the reason") + } + } + seen := map[string]bool{} + for _, t := range Tables { + if seen[t.Name] { + problems = append(problems, t.Name+": listed twice in Tables") + } + seen[t.Name] = true + if !inSchema[t.Name] { + problems = append(problems, t.Name+": in Tables but not in the schema") + } + } + for name := range Excluded { + if !inSchema[name] { + problems = append(problems, name+": in Excluded but not in the schema") + } + } + return problems +} diff --git a/internal/backup/tables_test.go b/internal/backup/tables_test.go new file mode 100644 index 00000000..d03b03b7 --- /dev/null +++ b/internal/backup/tables_test.go @@ -0,0 +1,57 @@ +package backup + +import ( + "slices" + "strings" + "testing" +) + +func everyListedTable() []string { + var names []string + for _, t := range Tables { + names = append(names, t.Name) + } + for name := range Excluded { + names = append(names, name) + } + return names +} + +// Coverage holds the schema against the two lists: every table is backed up +// or excluded with a reason, and every listed table exists. A migration that +// adds or drops a table without updating the lists fails here. +func TestCoverage(t *testing.T) { + without := func(drop ...string) []string { + return slices.DeleteFunc(everyListedTable(), func(n string) bool { return slices.Contains(drop, n) }) + } + for _, tc := range []struct { + name string + schema []string + want []string // a prefix of each problem, in order + }{ + {"the schema matches the lists", everyListedTable(), nil}, + {"a table in neither list", append(everyListedTable(), "new_table"), []string{"new_table: neither"}}, + {"listed tables the schema lacks", without("playlists", "scan_runs"), []string{"playlists", "scan_runs"}}, + } { + problems := Coverage(tc.schema) + slices.Sort(problems) + ok := len(problems) == len(tc.want) + for i := 0; ok && i < len(problems); i++ { + ok = strings.HasPrefix(problems[i], tc.want[i]) + } + if !ok { + t.Errorf("%s: problems = %q, want ones starting %q", tc.name, problems, tc.want) + } + } +} + +func TestEveryExclusionHasAReason(t *testing.T) { + for name, why := range Excluded { + if strings.TrimSpace(why) == "" { + t.Errorf("%s is excluded without a reason", name) + } + if carried(name) { + t.Errorf("%s is both backed up and excluded", name) + } + } +} diff --git a/internal/backup/throttle.go b/internal/backup/throttle.go new file mode 100644 index 00000000..4a8dc623 --- /dev/null +++ b/internal/backup/throttle.go @@ -0,0 +1,50 @@ +package backup + +import ( + "context" + "io" + "time" +) + +// Throttle returns a reader that reads r no faster than perSecond bytes a +// second, so an upload leaves room on the connection for everything else. +// perSecond of 0 or less returns r unchanged. A wait ends early when ctx does, +// and the read then returns ctx's error. +func Throttle(ctx context.Context, r io.Reader, perSecond int64) io.Reader { + if perSecond <= 0 { + return r + } + return &throttled{ctx: ctx, r: r, perSecond: perSecond} +} + +type throttled struct { + ctx context.Context + r io.Reader + perSecond int64 + start time.Time + sent int64 +} + +func (t *throttled) Read(p []byte) (int, error) { + if t.start.IsZero() { + t.start = time.Now() + } + // Reads are cut to a tenth of a second's worth, so the pace is even + // rather than a burst followed by a long pause. + if chunk := max(t.perSecond/10, 1); int64(len(p)) > chunk { + p = p[:chunk] + } + n, err := t.r.Read(p) + t.sent += int64(n) + at := t.start.Add(time.Duration(float64(t.sent) / float64(t.perSecond) * float64(time.Second))) + if wait := time.Until(at); wait > 0 { + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-t.ctx.Done(): + return n, t.ctx.Err() + case <-timer.C: + } + } + return n, err +} diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go index 67bc4d8b..a4e4b207 100644 --- a/internal/buildinfo/buildinfo.go +++ b/internal/buildinfo/buildinfo.go @@ -9,10 +9,10 @@ import "time" // the commit it was built from by ci/version.sh. Defaults to "dev" for local // builds; overridden at link time via: // -// -ldflags="-X 'git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo.Version=2026.09.10.1449'" +// -ldflags="-X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Version=2026.09.10.1449'" // -// release.yml passes it through the MINSTREL_VERSION build-arg → Dockerfile -// ldflag. +// The release build passes it through the MINSTREL_VERSION build-arg → +// Dockerfile ldflag. // // Image tags carry no version, so this is the only thing that says which // build is running. @@ -29,3 +29,19 @@ var Channel = "local" // Started is when this process started, for the admin Overview's uptime. var Started = time.Now() + +// ProjectURL is where Minstrel's source lives. Outside services that ask a +// client to say how to reach its maker are pointed here. +const ProjectURL = "https://github.com/Fabled-Sword/minstrel" + +// UserAgent is how Minstrel names itself to outside services (MusicBrainz, +// the Cover Art Archive, AcoustID), which ask for the app's name, its +// version and a contact, so a release can be told from a dev build in +// their logs. contact is the operator's address when one is configured; +// without one the project's URL stands in. +func UserAgent(contact string) string { + if contact == "" { + contact = ProjectURL + } + return "Minstrel/" + Version + " ( " + contact + " )" +} diff --git a/internal/buildinfo/useragent_test.go b/internal/buildinfo/useragent_test.go new file mode 100644 index 00000000..8fd8d1fb --- /dev/null +++ b/internal/buildinfo/useragent_test.go @@ -0,0 +1,19 @@ +package buildinfo + +import "testing" + +// The User-Agent carries the build's own version, so MusicBrainz and the +// others can tell a release from a dev build, and a contact: the operator's +// when set, the project's otherwise. +func TestUserAgent_NamesTheVersionAndAContact(t *testing.T) { + was := Version + t.Cleanup(func() { Version = was }) + Version = "2026.11.28.1700" + + if got, want := UserAgent("admin@example.com"), "Minstrel/2026.11.28.1700 ( admin@example.com )"; got != want { + t.Errorf("with a contact: %q, want %q", got, want) + } + if got, want := UserAgent(""), "Minstrel/2026.11.28.1700 ( "+ProjectURL+" )"; got != want { + t.Errorf("without one: %q, want %q", got, want) + } +} diff --git a/internal/catalogue/art.go b/internal/catalogue/art.go deleted file mode 100644 index 0d1a1b63..00000000 --- a/internal/catalogue/art.go +++ /dev/null @@ -1,214 +0,0 @@ -package catalogue - -import ( - "context" - "errors" - "fmt" - "os" - "path/filepath" - "regexp" - "sync" - "time" - - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" -) - -// NoArtRetry is how long "no source has art for this" is believed before -// the sources are asked again. -const NoArtRetry = 7 * 24 * time.Hour - -// fetchTimeout bounds one look-up across every source. -const fetchTimeout = 30 * time.Second - -// ErrNoArt: no enabled source has an image, or the sources could not be -// reached. The caller shows its placeholder. -var ErrNoArt = errors.New("catalogue: no art") - -var mbidPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) - -// ValidMBID reports whether s is shaped like a MusicBrainz id. It is the -// guard that keeps a request path out of the cache directory's parents. -func ValidMBID(s string) bool { return mbidPattern.MatchString(s) } - -// Art serves images for artists and release groups that are not in the -// library (search results, Discover suggestions, wanted albums), from the -// enabled cover-art sources. Each image is fetched once and kept -// under the data directory, so the browser only ever talks to Minstrel. -type Art struct { - dir string - artistSources func() []coverart.ArtistArtProvider - albumSources func() []coverart.AlbumCoverProvider - now func() time.Time - - mu sync.Mutex - inflight map[string]*artCall -} - -type artCall struct { - done chan struct{} - body []byte - err error -} - -// ArtSources lists the image sources to ask, in order. The cover-art -// settings service is one: it answers with the sources an admin enabled. -type ArtSources interface { - EnabledArtistProviders() []coverart.ArtistArtProvider - EnabledAlbumProviders() []coverart.AlbumCoverProvider -} - -// NewArt keeps images under dataDir/catalogue-art and asks the given -// sources. Nil sources ask nothing, so every image is the placeholder. -func NewArt(dataDir string, sources ArtSources) *Art { - a := &Art{dir: filepath.Join(dataDir, "catalogue-art"), now: time.Now, inflight: map[string]*artCall{}} - if sources != nil { - a.artistSources = sources.EnabledArtistProviders - a.albumSources = sources.EnabledAlbumProviders - } - return a -} - -// Artist returns an image of the artist: the first enabled artist source -// with one wins, its thumbnail preferred over its backdrop. -func (a *Art) Artist(ctx context.Context, mbid, name string) ([]byte, error) { - return a.cached(ctx, "artist", mbid, func(ctx context.Context) ([]byte, error) { - if a.artistSources == nil { - return nil, coverart.ErrNotFound - } - ref := coverart.ArtistRef{MBID: mbid, Name: name} - return firstOf(a.artistSources(), func(p coverart.ArtistArtProvider) ([]byte, error) { - thumb, fanart, err := p.FetchArtistArt(ctx, ref) - if err == nil && len(thumb) == 0 { - thumb = fanart - } - return thumb, err - }) - }) -} - -// ReleaseGroup returns a cover for the release group: a source that can -// answer by group (the Cover Art Archive) is asked by its id, the rest by -// artist and title. -func (a *Art) ReleaseGroup(ctx context.Context, mbid, artist, title string) ([]byte, error) { - return a.cached(ctx, "release-group", mbid, func(ctx context.Context) ([]byte, error) { - if a.albumSources == nil { - return nil, coverart.ErrNotFound - } - byName := coverart.AlbumRef{ArtistName: artist, AlbumTitle: title} - return firstOf(a.albumSources(), func(p coverart.AlbumCoverProvider) ([]byte, error) { - if g, ok := p.(coverart.ReleaseGroupCoverProvider); ok { - return g.FetchReleaseGroupCover(ctx, mbid) - } - if artist == "" || title == "" { - return nil, coverart.ErrNotFound - } - return p.FetchAlbumCover(ctx, byName) - }) - }) -} - -// firstOf asks each source in turn. It reports ErrNotFound only when every -// source said so; if any could not be reached, the miss is transient. -func firstOf[P any](sources []P, ask func(P) ([]byte, error)) ([]byte, error) { - transient := false - for _, p := range sources { - body, err := ask(p) - if err == nil && len(body) > 0 { - return body, nil - } - if err != nil && !errors.Is(err, coverart.ErrNotFound) { - transient = true - } - } - if transient { - return nil, coverart.ErrTransient - } - return nil, coverart.ErrNotFound -} - -// cached serves kind/mbid from disk, or fetches it once however many -// requests ask at the same moment. A definite "nobody has one" is written -// down and believed for NoArtRetry; an unreachable source is not, so the -// next request asks again. -func (a *Art) cached(ctx context.Context, kind, mbid string, fetch func(context.Context) ([]byte, error)) ([]byte, error) { - if !ValidMBID(mbid) { - return nil, ErrNoArt - } - dir := filepath.Join(a.dir, kind) - imgPath := filepath.Join(dir, mbid) - nonePath := imgPath + ".none" - - if body, err := os.ReadFile(imgPath); err == nil && len(body) > 0 { - return body, nil - } - if fi, err := os.Stat(nonePath); err == nil && a.now().Sub(fi.ModTime()) < NoArtRetry { - return nil, ErrNoArt - } - - key := kind + "/" + mbid - a.mu.Lock() - if call, ok := a.inflight[key]; ok { - a.mu.Unlock() - select { - case <-call.done: - return call.body, call.err - case <-ctx.Done(): - return nil, ctx.Err() - } - } - call := &artCall{done: make(chan struct{})} - a.inflight[key] = call - a.mu.Unlock() - - defer func() { - a.mu.Lock() - delete(a.inflight, key) - a.mu.Unlock() - close(call.done) - }() - - // The fetch outlives a browser that navigates away: a second request is - // likely, and the image is worth keeping. - fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), fetchTimeout) - defer cancel() - body, err := fetch(fctx) - switch { - case err == nil && len(body) > 0: - if werr := writeFile(dir, imgPath, body); werr != nil { - // Serving it uncached is still better than a placeholder. - call.body = body - return body, nil - } - _ = os.Remove(nonePath) - call.body = body - return body, nil - case err == nil || errors.Is(err, coverart.ErrNotFound): - _ = writeFile(dir, nonePath, nil) - } - call.err = ErrNoArt - return nil, ErrNoArt -} - -func writeFile(dir, path string, body []byte) error { - if err := os.MkdirAll(dir, 0o755); err != nil { - return fmt.Errorf("catalogue art: %w", err) - } - tmp, err := os.CreateTemp(dir, ".part-*") - if err != nil { - return fmt.Errorf("catalogue art: %w", err) - } - if _, err := tmp.Write(body); err != nil { - _ = tmp.Close() - _ = os.Remove(tmp.Name()) - return fmt.Errorf("catalogue art: %w", err) - } - if err := tmp.Close(); err != nil { - _ = os.Remove(tmp.Name()) - return fmt.Errorf("catalogue art: %w", err) - } - if err := os.Rename(tmp.Name(), path); err != nil { - _ = os.Remove(tmp.Name()) - return fmt.Errorf("catalogue art: %w", err) - } - return nil -} diff --git a/internal/catalogue/art_test.go b/internal/catalogue/art_test.go deleted file mode 100644 index 70d099e9..00000000 --- a/internal/catalogue/art_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package catalogue - -import ( - "context" - "errors" - "os" - "path/filepath" - "sync" - "sync/atomic" - "testing" - "time" - - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" -) - -const someMBID = "e21857d5-3256-4547-afb3-4b6ded592596" - -// fakeSource is an artist and album source answering with fixed results. -type fakeSource struct { - thumb, fanart, cover []byte - err error - calls atomic.Int32 - gate chan struct{} // when set, each fetch waits for it - lastRef coverart.AlbumRef - mu sync.Mutex -} - -func (f *fakeSource) ID() string { return "fake" } -func (f *fakeSource) DisplayName() string { return "Fake" } -func (f *fakeSource) RequiresAPIKey() bool { return false } -func (f *fakeSource) DefaultEnabled() bool { return true } -func (f *fakeSource) Configure(_ coverart.ProviderSettings) error { return nil } - -func (f *fakeSource) wait() { - f.calls.Add(1) - if f.gate != nil { - <-f.gate - } -} - -func (f *fakeSource) FetchArtistArt(_ context.Context, _ coverart.ArtistRef) ([]byte, []byte, error) { - f.wait() - return f.thumb, f.fanart, f.err -} - -func (f *fakeSource) FetchAlbumCover(_ context.Context, ref coverart.AlbumRef) ([]byte, error) { - f.wait() - f.mu.Lock() - f.lastRef = ref - f.mu.Unlock() - return f.cover, f.err -} - -// groupSource can also answer by release group, as the Cover Art Archive does. -type groupSource struct{ *fakeSource } - -func (g groupSource) FetchReleaseGroupCover(_ context.Context, _ string) ([]byte, error) { - g.wait() - return []byte("by-group"), nil -} - -type sources struct { - artists []coverart.ArtistArtProvider - albums []coverart.AlbumCoverProvider -} - -func (s sources) EnabledArtistProviders() []coverart.ArtistArtProvider { return s.artists } -func (s sources) EnabledAlbumProviders() []coverart.AlbumCoverProvider { return s.albums } - -func TestArt_FetchesOnceAndKeepsIt(t *testing.T) { - src := &fakeSource{fanart: []byte("backdrop")} - a := NewArt(t.TempDir(), sources{artists: []coverart.ArtistArtProvider{src}}) - - body, err := a.Artist(context.Background(), someMBID, "Gorillaz") - if err != nil || string(body) != "backdrop" { - t.Fatalf("with only a backdrop, use it: %q, %v", body, err) - } - if body, _ := a.Artist(context.Background(), someMBID, "Gorillaz"); string(body) != "backdrop" || src.calls.Load() != 1 { - t.Errorf("the second ask should come from disk: %q after %d calls", body, src.calls.Load()) - } -} - -func TestArt_NobodyHasOneIsBelievedForAWeek(t *testing.T) { - src := &fakeSource{err: coverart.ErrNotFound} - a := NewArt(t.TempDir(), sources{artists: []coverart.ArtistArtProvider{src}}) - - if _, err := a.Artist(context.Background(), someMBID, "x"); !errors.Is(err, ErrNoArt) { - t.Fatalf("err = %v, want ErrNoArt", err) - } - if _, err := a.Artist(context.Background(), someMBID, "x"); !errors.Is(err, ErrNoArt) || src.calls.Load() != 1 { - t.Errorf("a definite miss is remembered: %d calls", src.calls.Load()) - } - a.now = func() time.Time { return time.Now().Add(NoArtRetry + time.Hour) } - src.err, src.thumb = nil, []byte("thumb") - if body, err := a.Artist(context.Background(), someMBID, "x"); err != nil || string(body) != "thumb" { - t.Errorf("after a week the sources are asked again: %q, %v", body, err) - } -} - -func TestArt_AnUnreachableSourceIsAskedAgain(t *testing.T) { - src := &fakeSource{err: coverart.ErrTransient} - a := NewArt(t.TempDir(), sources{artists: []coverart.ArtistArtProvider{src}}) - for range 2 { - if _, err := a.Artist(context.Background(), someMBID, "x"); !errors.Is(err, ErrNoArt) { - t.Fatalf("err = %v", err) - } - } - if src.calls.Load() != 2 { - t.Errorf("calls = %d: an outage must not be written down as 'no art'", src.calls.Load()) - } -} - -func TestArt_ReleaseGroupAsksByGroupThenByName(t *testing.T) { - byName := &fakeSource{cover: []byte("by-name")} - caa := groupSource{&fakeSource{}} - a := NewArt(t.TempDir(), sources{albums: []coverart.AlbumCoverProvider{caa, byName}}) - if body, _ := a.ReleaseGroup(context.Background(), someMBID, "Gorillaz", "Demon Days"); string(body) != "by-group" { - t.Errorf("a source that answers by group is asked by group: %q", body) - } - - other := "0c4d5b5f-2f3c-3d31-9c4e-4b4f6b4c1a01" - a = NewArt(t.TempDir(), sources{albums: []coverart.AlbumCoverProvider{byName}}) - if body, _ := a.ReleaseGroup(context.Background(), other, "Gorillaz", "Demon Days"); string(body) != "by-name" { - t.Errorf("by name: %q", body) - } - if byName.lastRef.MBID != "" || byName.lastRef.AlbumTitle != "Demon Days" { - t.Errorf("a release-group id is not a release id, so it is not passed as one: %+v", byName.lastRef) - } -} - -func TestArt_ConcurrentAsksShareOneFetch(t *testing.T) { - src := &fakeSource{thumb: []byte("t"), gate: make(chan struct{})} - a := NewArt(t.TempDir(), sources{artists: []coverart.ArtistArtProvider{src}}) - var wg sync.WaitGroup - for range 5 { - wg.Add(1) - go func() { - defer wg.Done() - if body, err := a.Artist(context.Background(), someMBID, "x"); err != nil || string(body) != "t" { - t.Errorf("%q, %v", body, err) - } - }() - } - // Let the fetch through once every caller has had time to queue on it. - time.Sleep(50 * time.Millisecond) - close(src.gate) - wg.Wait() - if src.calls.Load() != 1 { - t.Errorf("calls = %d, want one fetch for five asks", src.calls.Load()) - } -} - -func TestArt_RefusesWhatIsNotAnMBID(t *testing.T) { - dir := t.TempDir() - a := NewArt(dir, sources{artists: []coverart.ArtistArtProvider{&fakeSource{thumb: []byte("t")}}}) - if _, err := a.Artist(context.Background(), "../../etc/passwd", "x"); !errors.Is(err, ErrNoArt) { - t.Fatalf("err = %v", err) - } - if _, err := os.Stat(filepath.Join(dir, "catalogue-art")); !os.IsNotExist(err) { - t.Error("nothing should be written for a refused id") - } - if _, err := NewArt(dir, nil).Artist(context.Background(), someMBID, "x"); !errors.Is(err, ErrNoArt) { - t.Errorf("no sources: err = %v", err) - } -} diff --git a/internal/catalogue/catalogue.go b/internal/catalogue/catalogue.go index ada4fe47..0f685d8b 100644 --- a/internal/catalogue/catalogue.go +++ b/internal/catalogue/catalogue.go @@ -1,7 +1,6 @@ -// Package catalogue is Minstrel's own record of what artists have released, -// read from MusicBrainz and kept in the database. The wanted -// list, search and import read it; MusicBrainz is asked only when what is -// held is missing or old. +// Package catalogue keeps MusicBrainz's releases and track lists for the +// albums the library holds. The duplicate resolver reads them to tell a song +// filed in the wrong slot from one legitimately repeated. package catalogue import ( @@ -9,34 +8,22 @@ import ( "errors" "fmt" "log/slog" - "time" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/musicbrainz" ) -const ( - // DiscographyMaxAge is how long an artist's list of release groups is - // trusted before it is read again. New releases appear on this cadence. - DiscographyMaxAge = 7 * 24 * time.Hour - // ReleasesMaxAge is how long a release group's editions and track lists - // are trusted. They change rarely once a group is out. - ReleasesMaxAge = 30 * 24 * time.Hour -) - -// ErrNotFound: MusicBrainz has no artist or release group under that id. +// ErrNotFound: MusicBrainz has no release group under that id. var ErrNotFound = errors.New("catalogue: not in MusicBrainz") -// Service reads and refreshes the catalogue. +// Service reads release groups from MusicBrainz into the catalogue. type Service struct { pool *pgxpool.Pool mb *musicbrainz.Client logger *slog.Logger - now func() time.Time } // New makes a Service. A nil client talks to the public MusicBrainz. @@ -47,91 +34,7 @@ func New(pool *pgxpool.Pool, mb *musicbrainz.Client, logger *slog.Logger) *Servi if logger == nil { logger = slog.Default() } - return &Service{pool: pool, mb: mb, logger: logger, now: time.Now} -} - -// MusicBrainz is the client the service asks, for callers that search. -func (s *Service) MusicBrainz() *musicbrainz.Client { return s.mb } - -// Discography is an artist and the release groups credited to them. -type Discography struct { - Artist dbq.MbArtist - Groups []dbq.MbReleaseGroup - // Stale: MusicBrainz could not be asked, so this is the last copy read. - Stale bool -} - -// Discography returns the artist's release groups, reading them from -// MusicBrainz first when they have never been read or are older than -// DiscographyMaxAge. When MusicBrainz is unreachable, a copy already held is -// returned marked Stale; with nothing held, the error is returned. -func (s *Service) Discography(ctx context.Context, artistMBID string) (Discography, error) { - return s.DiscographyWithin(ctx, artistMBID, DiscographyMaxAge) -} - -// DiscographyWithin is Discography with the age past which the held copy is -// read again: a followed artist is checked for new releases more often than -// one the catalogue merely knows. -func (s *Service) DiscographyWithin(ctx context.Context, artistMBID string, maxAge time.Duration) (Discography, error) { - q := dbq.New(s.pool) - artist, err := q.GetMBArtist(ctx, artistMBID) - held := err == nil && artist.DiscographyRefreshedAt.Valid - if err != nil && !errors.Is(err, pgx.ErrNoRows) { - return Discography{}, fmt.Errorf("catalogue: read artist: %w", err) - } - stale := false - if !held || s.now().Sub(artist.DiscographyRefreshedAt.Time) > maxAge { - if rerr := s.RefreshArtist(ctx, artistMBID); rerr != nil { - if !held || !errors.Is(rerr, musicbrainz.ErrUnreachable) { - return Discography{}, rerr - } - stale = true - } - if artist, err = q.GetMBArtist(ctx, artistMBID); err != nil { - return Discography{}, fmt.Errorf("catalogue: read artist: %w", err) - } - } - groups, err := q.ListMBArtistReleaseGroups(ctx, artistMBID) - if err != nil { - return Discography{}, fmt.Errorf("catalogue: read discography: %w", err) - } - return Discography{Artist: artist, Groups: groups, Stale: stale}, nil -} - -// RefreshArtist reads the artist and every release group credited to them, -// and replaces the held discography in one transaction. -func (s *Service) RefreshArtist(ctx context.Context, artistMBID string) error { - artist, err := s.mb.Artist(ctx, artistMBID) - if err != nil { - return mbErr(err) - } - groups, err := s.mb.ArtistReleaseGroups(ctx, artistMBID) - if err != nil { - return mbErr(err) - } - return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { - q := dbq.New(tx) - if err := q.UpsertMBArtist(ctx, dbq.UpsertMBArtistParams{ - Mbid: artist.MBID, Name: artist.Name, SortName: artist.SortName, - Disambiguation: artist.Disambiguation, ArtistType: artist.Type, Country: artist.Country, - }); err != nil { - return fmt.Errorf("catalogue: save artist: %w", err) - } - if err := q.DeleteMBArtistReleaseGroups(ctx, artist.MBID); err != nil { - return fmt.Errorf("catalogue: clear discography: %w", err) - } - for _, g := range groups { - if err := upsertGroup(ctx, q, g); err != nil { - return err - } - if err := q.AddMBArtistReleaseGroup(ctx, dbq.AddMBArtistReleaseGroupParams{ - ArtistMbid: artist.MBID, ReleaseGroupMbid: g.MBID, - }); err != nil { - return fmt.Errorf("catalogue: link release group: %w", err) - } - } - return q.MarkMBArtistDiscographyRefreshed(ctx, artist.MBID) - }) + return &Service{pool: pool, mb: mb, logger: logger} } func upsertGroup(ctx context.Context, q *dbq.Queries, g musicbrainz.ReleaseGroup) error { @@ -148,60 +51,6 @@ func upsertGroup(ctx context.Context, q *dbq.Queries, g musicbrainz.ReleaseGroup return nil } -// Edition is one release of a group with its track list. -type Edition struct { - Release dbq.MbRelease - Tracks []dbq.MbReleaseTrack -} - -// Editions is a release group and its releases. -type Editions struct { - Group dbq.MbReleaseGroup - Editions []Edition - Stale bool -} - -// Releases returns a release group's releases with their track lists, read -// from MusicBrainz first when never read or older than ReleasesMaxAge. Like -// Discography, an unreachable MusicBrainz serves the held copy as Stale. -func (s *Service) Releases(ctx context.Context, groupMBID string) (Editions, error) { - q := dbq.New(s.pool) - group, err := q.GetMBReleaseGroup(ctx, groupMBID) - if err != nil && !errors.Is(err, pgx.ErrNoRows) { - return Editions{}, fmt.Errorf("catalogue: read release group: %w", err) - } - held := err == nil && group.ReleasesRefreshedAt.Valid - stale := false - if !held || s.now().Sub(group.ReleasesRefreshedAt.Time) > ReleasesMaxAge { - if rerr := s.RefreshReleaseGroup(ctx, groupMBID); rerr != nil { - if !held || !errors.Is(rerr, musicbrainz.ErrUnreachable) { - return Editions{}, rerr - } - stale = true - } - if group, err = q.GetMBReleaseGroup(ctx, groupMBID); err != nil { - return Editions{}, fmt.Errorf("catalogue: read release group: %w", err) - } - } - releases, err := q.ListMBReleasesForGroup(ctx, groupMBID) - if err != nil { - return Editions{}, fmt.Errorf("catalogue: read releases: %w", err) - } - tracks, err := q.ListMBReleaseTracksForGroup(ctx, groupMBID) - if err != nil { - return Editions{}, fmt.Errorf("catalogue: read track lists: %w", err) - } - byRelease := make(map[string][]dbq.MbReleaseTrack, len(releases)) - for _, t := range tracks { - byRelease[t.ReleaseMbid] = append(byRelease[t.ReleaseMbid], t) - } - out := Editions{Group: group, Stale: stale} - for _, r := range releases { - out.Editions = append(out.Editions, Edition{Release: r, Tracks: byRelease[r.Mbid]}) - } - return out, nil -} - // RefreshReleaseGroup reads a group's releases and track lists and replaces // the held copy in one transaction. A group not yet held is looked up first. func (s *Service) RefreshReleaseGroup(ctx context.Context, groupMBID string) error { @@ -254,60 +103,6 @@ func (s *Service) RefreshReleaseGroup(ctx context.Context, groupMBID string) err }) } -// RefreshDue re-reads up to limit discographies that are older than -// DiscographyMaxAge, never-read first. It stops at the first unreachable -// MusicBrainz, since the rest would fail the same way. -func (s *Service) RefreshDue(ctx context.Context, limit int) (refreshed int, err error) { - due, err := dbq.New(s.pool).ListMBArtistsDueForRefresh(ctx, dbq.ListMBArtistsDueForRefreshParams{ - Before: pgtype.Timestamptz{Time: s.now().Add(-DiscographyMaxAge), Valid: true}, - MaxRows: int32(limit), - }) - if err != nil { - return 0, fmt.Errorf("catalogue: list due artists: %w", err) - } - for _, mbid := range due { - if err := s.RefreshArtist(ctx, mbid); err != nil { - if errors.Is(err, musicbrainz.ErrUnreachable) || ctx.Err() != nil { - return refreshed, err - } - // One artist MusicBrainz cannot describe (merged away, say) - // must not stop the rest. - s.logger.Warn("catalogue: refresh artist", "mbid", mbid, "err", err) - continue - } - refreshed++ - } - return refreshed, nil -} - -// RefreshInterval is how often Run looks for discographies due a re-read, -// and RefreshBatch how many it reads per look: 20 artists is about a minute -// of MusicBrainz's budget. -const ( - RefreshInterval = time.Hour - RefreshBatch = 20 -) - -// Run refreshes due discographies every RefreshInterval until ctx ends. -func (s *Service) Run(ctx context.Context) { - ticker := time.NewTicker(RefreshInterval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - } - n, err := s.RefreshDue(ctx, RefreshBatch) - switch { - case err != nil && ctx.Err() == nil: - s.logger.Warn("catalogue: refresh pass stopped", "refreshed", n, "err", err) - case n > 0: - s.logger.Info("catalogue: refresh pass complete", "refreshed", n) - } - } -} - // mbErr maps MusicBrainz's not-found to the catalogue's; anything else passes // through so callers can tell an unreachable MusicBrainz apart. func mbErr(err error) error { diff --git a/internal/catalogue/catalogue_test.go b/internal/catalogue/catalogue_test.go index 5b495122..e840a2b1 100644 --- a/internal/catalogue/catalogue_test.go +++ b/internal/catalogue/catalogue_test.go @@ -4,55 +4,25 @@ import ( "context" "errors" "fmt" - "io" - "log/slog" "net/http" "net/http/httptest" - "os" - "strings" "sync/atomic" "testing" - "time" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/musicbrainz" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - const ( - gorillaz = "e21857d5-3256-4547-afb3-4b6ded592596" - deLaSoul = "4f2a6b9e-9ae6-4f34-9a41-3e9f2f7c4c1d" - demonDays = "0c4d5b5f-2f3c-3d31-9c4e-4b4f6b4c1a01" - feelGood = "0c4d5b5f-2f3c-3d31-9c4e-4b4f6b4c1a02" // credited to both - demonDaysR = "1a2b3c4d-0000-4000-8000-000000000001" - demonDaysJ = "1a2b3c4d-0000-4000-8000-000000000002" + apes = "0a11ce00-0000-4000-8000-000000000001" + ghostNights = "0a11ce00-0000-4000-8000-000000000002" + ghostNightsR = "1a2b3c4d-0000-4000-8000-000000000001" + ghostNightsJ = "1a2b3c4d-0000-4000-8000-000000000002" ) -// fakeMB is a MusicBrainz with two artists, a collaboration between them, -// and one album with two editions. down makes every request a 503. +// fakeMB is a MusicBrainz with one album in two editions. down makes every +// request a 503. type fakeMB struct { srv *httptest.Server calls atomic.Int32 @@ -70,34 +40,19 @@ func newFakeMB(t *testing.T) *fakeMB { } q := r.URL.Query() switch { - case r.URL.Path == "/artist/"+gorillaz: - _, _ = fmt.Fprintf(w, `{"id": %q, "name": "Gorillaz", "sort-name": "Gorillaz", "type": "Group", "country": "GB"}`, gorillaz) - case r.URL.Path == "/artist/"+deLaSoul: - _, _ = fmt.Fprintf(w, `{"id": %q, "name": "De La Soul", "type": "Group", "country": "US"}`, deLaSoul) - case r.URL.Path == "/release-group" && q.Get("artist") == gorillaz: - _, _ = fmt.Fprintf(w, `{"release-group-count": 2, "release-groups": [ - {"id": %q, "title": "Demon Days", "primary-type": "Album", "first-release-date": "2005-05-11", - "artist-credit": [{"name": "Gorillaz", "artist": {"id": %q}}]}, - {"id": %q, "title": "Feel Good Inc.", "primary-type": "Single", "secondary-types": [], "first-release-date": "2005-05-09", - "artist-credit": [{"name": "Gorillaz", "joinphrase": " feat. ", "artist": {"id": %q}}, {"name": "De La Soul", "artist": {"id": %q}}]} - ]}`, demonDays, gorillaz, feelGood, gorillaz, deLaSoul) - case r.URL.Path == "/release-group" && q.Get("artist") == deLaSoul: - _, _ = fmt.Fprintf(w, `{"release-group-count": 1, "release-groups": [ - {"id": %q, "title": "Feel Good Inc.", "primary-type": "Single", "first-release-date": "2005-05-09"} - ]}`, feelGood) - case r.URL.Path == "/release-group/"+demonDays: - _, _ = fmt.Fprintf(w, `{"id": %q, "title": "Demon Days", "primary-type": "Album", "first-release-date": "2005-05-11", - "artist-credit": [{"name": "Gorillaz", "artist": {"id": %q}}]}`, demonDays, gorillaz) - case r.URL.Path == "/release" && q.Get("release-group") == demonDays: + case r.URL.Path == "/release-group/"+ghostNights: + _, _ = fmt.Fprintf(w, `{"id": %q, "title": "Ghost Nights", "primary-type": "Album", "first-release-date": "2005-05-11", + "artist-credit": [{"name": "Plastic Apes", "artist": {"id": %q}}]}`, ghostNights, apes) + case r.URL.Path == "/release" && q.Get("release-group") == ghostNights: _, _ = fmt.Fprintf(w, `{"release-count": 2, "releases": [ - {"id": %q, "title": "Demon Days", "status": "Promotion", "date": "2005-04", "country": "JP", + {"id": %q, "title": "Ghost Nights", "status": "Promotion", "date": "2005-04", "country": "JP", "media": [{"position": 1, "format": "CD", "tracks": [ {"position": 1, "number": "1", "title": "Intro", "length": 63000, "recording": {"id": "rec-intro"}}]}]}, - {"id": %q, "title": "Demon Days", "status": "Official", "date": "2005-05-11", "country": "GB", + {"id": %q, "title": "Ghost Nights", "status": "Official", "date": "2005-05-11", "country": "GB", "media": [{"position": 1, "format": "CD", "tracks": [ {"position": 1, "number": "1", "title": "Intro", "length": 63000, "recording": {"id": "rec-intro"}}, - {"position": 2, "number": "2", "title": "Last Living Souls", "length": 190000, "recording": {"id": "rec-lls"}}]}]} - ]}`, demonDaysJ, demonDaysR) + {"position": 2, "number": "2", "title": "Last Lit Rooms", "length": 190000, "recording": {"id": "rec-lls"}}]}]} + ]}`, ghostNightsJ, ghostNightsR) default: w.WriteHeader(http.StatusNotFound) } @@ -110,138 +65,60 @@ func (f *fakeMB) client() *musicbrainz.Client { return &musicbrainz.Client{BaseURL: f.srv.URL, Pace: &musicbrainz.Pacer{}, Retries: -1} } -func TestDiscography_ReadsOnceThenServesTheHeldCopy_Integration(t *testing.T) { +func TestRefreshReleaseGroup_ReadsEditionsAndTrackLists_Integration(t *testing.T) { ctx := context.Background() mb := newFakeMB(t) - s := New(newPool(t), mb.client(), nil) - - d, err := s.Discography(ctx, gorillaz) - if err != nil { - t.Fatal(err) - } - if d.Artist.Name != "Gorillaz" || d.Artist.Country != "GB" || len(d.Groups) != 2 || d.Stale { - t.Fatalf("discography = %+v", d) - } - // Oldest first: the single came out two days before the album. - if d.Groups[0].Mbid != feelGood || d.Groups[1].PrimaryType != "Album" { - t.Errorf("order = %s, %s", d.Groups[0].Title, d.Groups[1].Title) - } - if d.Groups[0].ArtistCredit != "Gorillaz feat. De La Soul" { - t.Errorf("credit = %q", d.Groups[0].ArtistCredit) - } - - before := mb.calls.Load() - if _, err := s.Discography(ctx, gorillaz); err != nil { - t.Fatal(err) - } - if mb.calls.Load() != before { - t.Error("a fresh discography should be served without asking MusicBrainz") - } - - // The collaboration belongs to both artists. - dls, err := s.Discography(ctx, deLaSoul) - if err != nil { - t.Fatal(err) - } - if len(dls.Groups) != 1 || dls.Groups[0].Mbid != feelGood { - t.Errorf("De La Soul's discography = %+v", dls.Groups) - } - if again, _ := s.Discography(ctx, gorillaz); len(again.Groups) != 2 { - t.Error("refreshing one artist must not take a shared group from the other") - } -} - -func TestDiscography_UnreachableServesStaleOrFails_Integration(t *testing.T) { - ctx := context.Background() - mb := newFakeMB(t) - pool := newPool(t) + pool := dbtest.Pool(t) s := New(pool, mb.client(), nil) - - mb.down.Store(true) - if _, err := s.Discography(ctx, gorillaz); !errors.Is(err, musicbrainz.ErrUnreachable) { - t.Fatalf("nothing held and MusicBrainz down: err = %v, want ErrUnreachable", err) - } - - mb.down.Store(false) - if _, err := s.Discography(ctx, gorillaz); err != nil { - t.Fatal(err) - } - // A week and a day later, MusicBrainz is down: the held copy is served. - s.now = func() time.Time { return time.Now().Add(DiscographyMaxAge + 24*time.Hour) } - mb.down.Store(true) - d, err := s.Discography(ctx, gorillaz) - if err != nil || !d.Stale || len(d.Groups) != 2 { - t.Fatalf("stale copy: %+v, %v", d, err) - } -} - -func TestDiscography_UnknownArtistIsNotFound_Integration(t *testing.T) { - s := New(newPool(t), newFakeMB(t).client(), nil) - if _, err := s.Discography(context.Background(), "00000000-0000-4000-8000-000000000000"); !errors.Is(err, ErrNotFound) { - t.Fatalf("err = %v, want ErrNotFound", err) - } -} - -func TestReleases_ReadsEditionsAndTrackLists_Integration(t *testing.T) { - ctx := context.Background() - mb := newFakeMB(t) - s := New(newPool(t), mb.client(), nil) + q := dbq.New(pool) // The group isn't held yet: it is looked up first. - e, err := s.Releases(ctx, demonDays) + if err := s.RefreshReleaseGroup(ctx, ghostNights); err != nil { + t.Fatal(err) + } + group, err := q.GetMBReleaseGroup(ctx, ghostNights) if err != nil { t.Fatal(err) } - if e.Group.Title != "Demon Days" || len(e.Editions) != 2 { - t.Fatalf("editions = %+v", e) + if group.Title != "Ghost Nights" || !group.ReleasesRefreshedAt.Valid { + t.Fatalf("group = %+v", group) } - official := e.Editions[0] - if official.Release.Mbid != demonDaysR || official.Release.TrackCount != 2 || official.Release.Formats != "CD" { - t.Errorf("the official edition should come first: %+v", official.Release) - } - if len(official.Tracks) != 2 || official.Tracks[1].RecordingMbid != "rec-lls" || official.Tracks[1].LengthMs != 190000 { - t.Errorf("tracks = %+v", official.Tracks) - } - - before := mb.calls.Load() - if _, err := s.Releases(ctx, demonDays); err != nil { + tracks, err := q.ListMBReleaseTracksForGroup(ctx, ghostNights) + if err != nil { t.Fatal(err) } - if mb.calls.Load() != before { - t.Error("fresh editions should be served without asking MusicBrainz") + if len(tracks) != 3 { + t.Fatalf("want 3 tracks across both editions, got %+v", tracks) } - // Refreshing replaces rather than adds. - if err := s.RefreshReleaseGroup(ctx, demonDays); err != nil { - t.Fatal(err) - } - if again, _ := s.Releases(ctx, demonDays); len(again.Editions) != 2 || len(again.Editions[0].Tracks) != 2 { - t.Errorf("after a refresh: %+v", again) - } -} - -func TestRefreshDue_ReadsWhatIsOldAndStopsWhenMusicBrainzIsDown_Integration(t *testing.T) { - ctx := context.Background() - mb := newFakeMB(t) - s := New(newPool(t), mb.client(), nil) - for _, a := range []string{gorillaz, deLaSoul} { - if err := s.RefreshArtist(ctx, a); err != nil { - t.Fatal(err) + var lls *dbq.MbReleaseTrack + for i := range tracks { + if tracks[i].RecordingMbid == "rec-lls" { + lls = &tracks[i] } } - if n, err := s.RefreshDue(ctx, 10); err != nil || n != 0 { - t.Fatalf("nothing is due yet: %d, %v", n, err) + if lls == nil || lls.ReleaseMbid != ghostNightsR || lls.LengthMs != 190000 { + t.Errorf("Last Lit Rooms = %+v", lls) } - s.now = func() time.Time { return time.Now().Add(DiscographyMaxAge + time.Hour) } - if n, err := s.RefreshDue(ctx, 1); err != nil || n != 1 { - t.Errorf("one due, limit one: %d, %v", n, err) + // Refreshing replaces rather than adds. + if err := s.RefreshReleaseGroup(ctx, ghostNights); err != nil { + t.Fatal(err) } + if again, _ := q.ListMBReleaseTracksForGroup(ctx, ghostNights); len(again) != 3 { + t.Errorf("after a refresh: %d tracks, want 3", len(again)) + } +} + +func TestRefreshReleaseGroup_UnknownAndUnreachable_Integration(t *testing.T) { + ctx := context.Background() + mb := newFakeMB(t) + s := New(dbtest.Pool(t), mb.client(), nil) + + if err := s.RefreshReleaseGroup(ctx, "00000000-0000-4000-8000-000000000000"); !errors.Is(err, ErrNotFound) { + t.Errorf("unknown group: err = %v, want ErrNotFound", err) + } mb.down.Store(true) - n, err := s.RefreshDue(ctx, 10) - if !errors.Is(err, musicbrainz.ErrUnreachable) || n != 0 { - t.Errorf("MusicBrainz down: %d, %v", n, err) - } - if !strings.Contains(err.Error(), "503") { - t.Errorf("the error should say what MusicBrainz answered: %v", err) + if err := s.RefreshReleaseGroup(ctx, ghostNights); !errors.Is(err, musicbrainz.ErrUnreachable) { + t.Errorf("MusicBrainz down: err = %v, want ErrUnreachable", err) } } diff --git a/internal/config/config.go b/internal/config/config.go index 645a21e3..c5be5bba 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -98,8 +98,8 @@ func Default() Config { Database: DatabaseConfig{URL: ""}, Log: LogConfig{Level: "info", Format: "text"}, Branding: BrandingConfig{ - AppName: "Minstrel", - Description: "Self-hosted music server with Subsonic compatibility, smart shuffle, and music acquisition.", + AppName: "Fabled Minstrel", + Description: "Self-hosted music server with Subsonic compatibility and smart shuffle.", }, Events: EventsConfig{ SessionTimeoutMinutes: 30, diff --git a/internal/config/config_test.go b/internal/config/config_test.go index bdbdcffd..49af33fd 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -157,8 +157,8 @@ func TestLibraryYAMLLoads(t *testing.T) { func TestBrandingDefaults(t *testing.T) { cfg := Default() - if cfg.Branding.AppName != "Minstrel" { - t.Errorf("AppName: got %q, want %q", cfg.Branding.AppName, "Minstrel") + if cfg.Branding.AppName != "Fabled Minstrel" { + t.Errorf("AppName: got %q, want %q", cfg.Branding.AppName, "Fabled Minstrel") } if cfg.Branding.Description == "" { t.Errorf("Description: empty after Default(); want default tagline") diff --git a/internal/coplay/worker.go b/internal/coplay/worker.go index 732508e9..e163a0e5 100644 --- a/internal/coplay/worker.go +++ b/internal/coplay/worker.go @@ -15,7 +15,8 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // minJaccard is the co-play edge floor: prune weak pairs and self-limit hub @@ -44,21 +45,11 @@ func NewWorker(pool *pgxpool.Pool, logger *slog.Logger) *Worker { // then every w.tick until ctx is cancelled. Runs in its own goroutine, so a // slow initial rebuild never blocks boot. func (w *Worker) Run(ctx context.Context) { - if err := w.rebuild(ctx); err != nil { - w.logger.Error("coplay: initial rebuild failed", "err", err) - } - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - if err := w.rebuild(ctx); err != nil { - w.logger.Error("coplay: rebuild failed", "err", err) - } + periodic.Run(ctx, w.logger, "coplay", w.tick, func(ctx context.Context) { + if err := w.rebuild(ctx); err != nil { + w.logger.Error("coplay: rebuild failed", "err", err) } - } + }) } // rebuild atomic-replaces the user_cooccurrence edge set inside one diff --git a/internal/coplay/worker_integration_test.go b/internal/coplay/worker_integration_test.go index e38475f0..67adb006 100644 --- a/internal/coplay/worker_integration_test.go +++ b/internal/coplay/worker_integration_test.go @@ -4,39 +4,16 @@ import ( "context" "io" "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func seedUser(t *testing.T, q *dbq.Queries, name string) pgtype.UUID { @@ -105,7 +82,7 @@ func coplayEdgeCount(t *testing.T, pool *pgxpool.Pool) int { // TestCoplayWorker_BuildsEdges: two users who both play two artists produce a // perfect-overlap co-play edge (Jaccard 1.0) in each direction. func TestCoplayWorker_BuildsEdges(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -143,7 +120,7 @@ func TestCoplayWorker_BuildsEdges(t *testing.T) { // TestCoplayWorker_SingleUserNoEdges: one user's own co-listening yields no // edges — the >= 2 distinct-co-player gate keeps single-user servers empty. func TestCoplayWorker_SingleUserNoEdges(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/coverart/artist_enricher.go b/internal/coverart/artist_enricher.go index 2af0a052..1a0b5738 100644 --- a/internal/coverart/artist_enricher.go +++ b/internal/coverart/artist_enricher.go @@ -10,7 +10,8 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // EnrichArtist runs the chain for a single artist. Parallel to @@ -115,9 +116,12 @@ func (e *Enricher) EnrichArtist(ctx context.Context, artistID pgtype.UUID, dataD // recordArtistArt writes the new artist_thumb_path / // artist_fanart_path / artist_art_source / artist_art_sources_version -// atomically. +// atomically. A picture found is logged as a change to the artist in the +// same transaction: the library sync sends the picture paths, and an app +// learns a row changed only from the change log, so without it an artist +// first synced before its picture arrived would stay pictureless there. +// Settling "none" changes nothing an app shows and isn't logged. func (e *Enricher) recordArtistArt(ctx context.Context, artistID pgtype.UUID, thumbPath, fanartPath, source string, version int32) error { - q := dbq.New(e.pool) src := source var thumbArg, fanartArg *string if thumbPath != "" { @@ -126,12 +130,20 @@ func (e *Enricher) recordArtistArt(ctx context.Context, artistID pgtype.UUID, th if fanartPath != "" { fanartArg = &fanartPath } - return q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ - ID: artistID, - ArtistThumbPath: thumbArg, - ArtistFanartPath: fanartArg, - ArtistArtSource: &src, - ArtistArtSourcesVersion: version, + return pgx.BeginFunc(ctx, e.pool, func(tx pgx.Tx) error { + if err := dbq.New(tx).SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ + ID: artistID, + ArtistThumbPath: thumbArg, + ArtistFanartPath: fanartArg, + ArtistArtSource: &src, + ArtistArtSourcesVersion: version, + }); err != nil { + return err + } + if thumbArg == nil && fanartArg == nil { + return nil + } + return syncpkg.LogChange(ctx, tx, syncpkg.EntityArtist, syncpkg.FormatUUID(artistID), syncpkg.OpUpsert) }) } diff --git a/internal/coverart/artist_enricher_test.go b/internal/coverart/artist_enricher_test.go index 2751eb49..84e2ac4b 100644 --- a/internal/coverart/artist_enricher_test.go +++ b/internal/coverart/artist_enricher_test.go @@ -2,13 +2,16 @@ package coverart import ( "context" + "fmt" "os" "path/filepath" "testing" "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // stubArtistProvider is a configurable ArtistArtProvider for artist enricher @@ -43,263 +46,122 @@ func insertArtist(t *testing.T, q *dbq.Queries, ctx context.Context, name, mbid return a.ID } -// --- Eligibility tests --- - -func TestEnrichArtist_NullSource_Eligible(t *testing.T) { - pool := newPool(t) +// An artist is asked about when it has no art source yet, or when it was +// settled as "none" under an older set of providers (the version counts +// provider changes). One with art, or settled "none" under the current +// providers, is left alone, and no file is written for it. +func TestEnrichArtist_WhichArtistsAreAsked(t *testing.T) { + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) - resetRegistryForTests() t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ + Register(&stubArtistProvider{ fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, thumb: []byte("thumb_bytes"), fanart: []byte("fanart_bytes"), - } - Register(stub) - + }) e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "Null Artist", "11111111-1111-1111-1111-111111111111") - + current := e.settings.CurrentVersion() dataDir := t.TempDir() - if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { - t.Fatalf("EnrichArtist: %v", err) - } - row, err := q.GetArtistByID(ctx, artistID) - if err != nil { - t.Fatalf("GetArtistByID: %v", err) - } - if row.ArtistArtSource == nil || *row.ArtistArtSource != "stub-artist" { - t.Errorf("source = %v, want 'stub-artist'", row.ArtistArtSource) - } -} - -func TestEnrichArtist_FoundSource_Skip(t *testing.T) { - pool := newPool(t) - ctx := context.Background() - q := dbq.New(pool) - - resetRegistryForTests() - t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ - fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, - thumb: []byte("should_not_write"), - } - Register(stub) - - e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "Found Artist", "22222222-2222-2222-2222-222222222222") - - // Pre-mark with a "found" source. - src := "theaudiodb" - if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ - ID: artistID, - ArtistArtSource: &src, - ArtistArtSourcesVersion: e.settings.CurrentVersion(), - }); err != nil { - t.Fatalf("set: %v", err) - } - - dataDir := t.TempDir() - if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { - t.Fatalf("EnrichArtist: %v", err) - } - - // Source must remain 'theaudiodb'; no files should have been written. - row, err := q.GetArtistByID(ctx, artistID) - if err != nil { - t.Fatalf("GetArtistByID: %v", err) - } - if row.ArtistArtSource == nil || *row.ArtistArtSource != "theaudiodb" { - t.Errorf("source = %v, want 'theaudiodb' (preserved)", row.ArtistArtSource) - } - thumbPath := filepath.Join(dataDir, "artist-art", uuidString(artistID), "thumb.jpg") - if _, err := os.Stat(thumbPath); !os.IsNotExist(err) { - t.Errorf("expected no thumb.jpg (skip), got stat err = %v", err) - } -} - -func TestEnrichArtist_NoneCurrentVersion_Skip(t *testing.T) { - pool := newPool(t) - ctx := context.Background() - q := dbq.New(pool) - - resetRegistryForTests() - t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ - fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, - thumb: []byte("should_not_write"), - } - Register(stub) - - e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "None Current Artist", "33333333-3333-3333-3333-333333333333") - - src := "none" - if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ - ID: artistID, - ArtistArtSource: &src, - ArtistArtSourcesVersion: e.settings.CurrentVersion(), - }); err != nil { - t.Fatalf("set: %v", err) - } - - dataDir := t.TempDir() - if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { - t.Fatalf("EnrichArtist: %v", err) - } - - // Source must remain 'none' at current version. - row, err := q.GetArtistByID(ctx, artistID) - if err != nil { - t.Fatalf("GetArtistByID: %v", err) - } - if row.ArtistArtSource == nil || *row.ArtistArtSource != "none" { - t.Errorf("source = %v, want 'none' (skip — current version)", row.ArtistArtSource) - } -} - -func TestEnrichArtist_NoneStaleVersion_FlipAndRetry(t *testing.T) { - pool := newPool(t) - ctx := context.Background() - q := dbq.New(pool) - - resetRegistryForTests() - t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ - fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, - thumb: []byte("retry_thumb"), - fanart: []byte("retry_fanart"), - } - Register(stub) - - e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "Stale None Artist", "44444444-4444-4444-4444-444444444444") - - // Set 'none' with a stale version (currentVersion - 1). - staleVersion := e.settings.CurrentVersion() - 1 - src := "none" - if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ - ID: artistID, - ArtistArtSource: &src, - ArtistArtSourcesVersion: staleVersion, - }); err != nil { - t.Fatalf("set stale none: %v", err) - } - - dataDir := t.TempDir() - if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { - t.Fatalf("EnrichArtist: %v", err) - } - - row, err := q.GetArtistByID(ctx, artistID) - if err != nil { - t.Fatalf("GetArtistByID: %v", err) - } - // Stale 'none' should be flipped and re-enriched; stub succeeds so - // source becomes the provider ID. - if row.ArtistArtSource == nil || *row.ArtistArtSource != "stub-artist" { - t.Errorf("source = %v, want 'stub-artist' (stale none flipped and retried)", row.ArtistArtSource) - } -} - -// --- Atomicity: thumb-only / fanart-only --- - -func TestEnrichArtist_ThumbOnly_ThumbPathSetFanartNull(t *testing.T) { - pool := newPool(t) - ctx := context.Background() - q := dbq.New(pool) - - resetRegistryForTests() - t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ - fakeProvider: fakeProvider{id: "thumb-only-provider", defaultOn: true}, - thumb: []byte("thumb_only"), - fanart: nil, - } - Register(stub) - - e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "Thumb Only Artist", "55555555-5555-5555-5555-555555555555") - - dataDir := t.TempDir() - if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { - t.Fatalf("EnrichArtist: %v", err) - } - - row, err := q.GetArtistByID(ctx, artistID) - if err != nil { - t.Fatalf("GetArtistByID: %v", err) - } - if row.ArtistArtSource == nil || *row.ArtistArtSource != "thumb-only-provider" { - t.Errorf("source = %v, want 'thumb-only-provider'", row.ArtistArtSource) - } - if row.ArtistThumbPath == nil { - t.Errorf("artist_thumb_path is nil, want a path") - } - if row.ArtistFanartPath != nil { - t.Errorf("artist_fanart_path = %v, want nil (fanart not provided)", row.ArtistFanartPath) - } - if row.ArtistThumbPath != nil { - body, rerr := os.ReadFile(*row.ArtistThumbPath) - if rerr != nil { - t.Fatalf("read thumb: %v", rerr) + for i, tc := range []struct { + name string + source string // "" leaves it NULL + version int32 + wantSource string + wantAsked bool + }{ + {"no source yet", "", 0, "stub-artist", true}, + {"art already found", "theaudiodb", current, "theaudiodb", false}, + {"none under the current providers", "none", current, "none", false}, + {"none under older providers", "none", current - 1, "stub-artist", true}, + } { + artistID := insertArtist(t, q, ctx, tc.name, fmt.Sprintf("0000000%d-1111-1111-1111-111111111111", i)) + if tc.source != "" { + src := tc.source + if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ + ID: artistID, ArtistArtSource: &src, ArtistArtSourcesVersion: tc.version, + }); err != nil { + t.Fatalf("%s: set: %v", tc.name, err) + } } - if string(body) != "thumb_only" { - t.Errorf("thumb content = %q, want 'thumb_only'", string(body)) + if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { + t.Fatalf("%s: EnrichArtist: %v", tc.name, err) + } + row, err := q.GetArtistByID(ctx, artistID) + if err != nil { + t.Fatal(err) + } + if row.ArtistArtSource == nil || *row.ArtistArtSource != tc.wantSource { + t.Errorf("%s: source = %v, want %q", tc.name, row.ArtistArtSource, tc.wantSource) + } + _, statErr := os.Stat(filepath.Join(dataDir, "artist-art", uuidString(artistID), "thumb.jpg")) + if asked := statErr == nil; asked != tc.wantAsked { + t.Errorf("%s: thumb written = %v, want %v", tc.name, asked, tc.wantAsked) } } } -func TestEnrichArtist_FanartOnly_FanartPathSetThumbNull(t *testing.T) { - pool := newPool(t) +// A provider with only one of the two pictures still settles the artist as +// found: the picture it has is written and its path set, and the other path +// stays NULL so the clients fall back rather than load a missing file. +func TestEnrichArtist_OnePictureOfTwo(t *testing.T) { + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) - resetRegistryForTests() t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ - fakeProvider: fakeProvider{id: "fanart-only-provider", defaultOn: true}, - thumb: nil, - fanart: []byte("fanart_only"), - } + stub := &stubArtistProvider{fakeProvider: fakeProvider{id: "one-picture", defaultOn: true}} Register(stub) - e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "Fanart Only Artist", "66666666-6666-6666-6666-666666666666") - dataDir := t.TempDir() - if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { - t.Fatalf("EnrichArtist: %v", err) - } - row, err := q.GetArtistByID(ctx, artistID) - if err != nil { - t.Fatalf("GetArtistByID: %v", err) - } - if row.ArtistArtSource == nil || *row.ArtistArtSource != "fanart-only-provider" { - t.Errorf("source = %v, want 'fanart-only-provider'", row.ArtistArtSource) - } - if row.ArtistThumbPath != nil { - t.Errorf("artist_thumb_path = %v, want nil (thumb not provided)", row.ArtistThumbPath) - } - if row.ArtistFanartPath == nil { - t.Errorf("artist_fanart_path is nil, want a path") + for i, tc := range []struct { + name string + thumb, fanart []byte + }{ + {"a thumbnail only", []byte("thumb_only"), nil}, + {"fanart only", nil, []byte("fanart_only")}, + } { + stub.thumb, stub.fanart = tc.thumb, tc.fanart + artistID := insertArtist(t, q, ctx, tc.name, fmt.Sprintf("5555555%d-5555-5555-5555-555555555555", i)) + if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { + t.Fatalf("%s: EnrichArtist: %v", tc.name, err) + } + row, err := q.GetArtistByID(ctx, artistID) + if err != nil { + t.Fatal(err) + } + if row.ArtistArtSource == nil || *row.ArtistArtSource != "one-picture" { + t.Errorf("%s: source = %v, want one-picture", tc.name, row.ArtistArtSource) + } + for _, pic := range []struct { + kind string + path *string + want []byte + }{{"thumbnail", row.ArtistThumbPath, tc.thumb}, {"fanart", row.ArtistFanartPath, tc.fanart}} { + if pic.want == nil { + if pic.path != nil { + t.Errorf("%s: %s path = %q, want NULL", tc.name, pic.kind, *pic.path) + } + continue + } + if pic.path == nil { + t.Errorf("%s: %s path is NULL", tc.name, pic.kind) + continue + } + if body, err := os.ReadFile(*pic.path); err != nil || string(body) != string(pic.want) { + t.Errorf("%s: %s file = %q, %v; want %q", tc.name, pic.kind, body, err, pic.want) + } + } } } // --- All-404 settles to 'none' --- func TestEnrichArtist_All404_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -335,7 +197,7 @@ func TestEnrichArtist_All404_SettlesNone(t *testing.T) { // --- Empty providers list settles vacuously to 'none' --- func TestEnrichArtist_EmptyProviders_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -365,7 +227,7 @@ func TestEnrichArtist_EmptyProviders_SettlesNone(t *testing.T) { // --- ErrTransient leaves row NULL --- func TestEnrichArtist_ErrTransient_LeavesNull(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -399,7 +261,7 @@ func TestEnrichArtist_ErrTransient_LeavesNull(t *testing.T) { // --- Filesystem layout --- func TestEnrichArtist_FilesystemLayout(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -497,7 +359,7 @@ func TestCleanupArtistArt_IdempotentMissingDir(t *testing.T) { // --- MBID guard --- func TestEnrichArtist_NoMBID_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -531,3 +393,52 @@ func TestEnrichArtist_NoMBID_SettlesNone(t *testing.T) { t.Errorf("source = %v, want 'none' (settled)", row.ArtistArtSource) } } + +// artistChanges counts the change-log rows for an artist: what tells a +// syncing app to fetch the artist again. +func artistChanges(t *testing.T, pool *pgxpool.Pool, artistID pgtype.UUID) int { + t.Helper() + var n int + if err := pool.QueryRow(context.Background(), + `SELECT count(*) FROM library_changes WHERE entity_type = 'artist' AND entity_id = $1`, + artistID.String()).Scan(&n); err != nil { + t.Fatalf("count changes: %v", err) + } + return n +} + +// A picture found for an artist is logged as a change to it, so an app that +// synced the artist before the picture arrived fetches it again. Settling +// "none" changes nothing an app shows and logs nothing. +func TestEnrichArtist_APictureFoundIsInTheSyncLog(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + q := dbq.New(pool) + resetRegistryForTests() + t.Cleanup(resetRegistryForTests) + stub := &stubArtistProvider{ + fakeProvider: fakeProvider{id: "sync-log-provider", defaultOn: true}, + thumb: []byte("thumb"), + } + Register(stub) + e := newTestEnricher(t, pool) + + found := insertArtist(t, q, ctx, "Pictured Artist", "88888888-8888-8888-8888-888888888888") + before := artistChanges(t, pool, found) + if err := e.EnrichArtist(ctx, found, t.TempDir()); err != nil { + t.Fatalf("EnrichArtist: %v", err) + } + if got := artistChanges(t, pool, found); got != before+1 { + t.Fatalf("change rows for the pictured artist = %d, want %d", got, before+1) + } + + stub.thumb, stub.err = nil, ErrNotFound + bare := insertArtist(t, q, ctx, "Unpictured Artist", "99999999-9999-9999-9999-999999999999") + before = artistChanges(t, pool, bare) + if err := e.EnrichArtist(ctx, bare, t.TempDir()); err != nil { + t.Fatalf("EnrichArtist: %v", err) + } + if got := artistChanges(t, pool, bare); got != before { + t.Fatalf("change rows for an artist settled none = %d, want %d", got, before) + } +} diff --git a/internal/coverart/content_type.go b/internal/coverart/content_type.go new file mode 100644 index 00000000..ba60985a --- /dev/null +++ b/internal/coverart/content_type.go @@ -0,0 +1,24 @@ +package coverart + +import ( + "path/filepath" + "strings" +) + +// ImageContentType is the Content-Type to serve a cover or artist image +// with, from its file extension. The native API and Subsonic both serve +// the same files, so they answer from this one table. An extension it +// doesn't know is application/octet-stream. +func ImageContentType(path string) string { + switch strings.ToLower(filepath.Ext(path)) { + case ".jpg", ".jpeg": + return "image/jpeg" + case ".png": + return "image/png" + case ".webp": + return "image/webp" + case ".gif": + return "image/gif" + } + return "application/octet-stream" +} diff --git a/internal/coverart/content_type_test.go b/internal/coverart/content_type_test.go new file mode 100644 index 00000000..35b7c872 --- /dev/null +++ b/internal/coverart/content_type_test.go @@ -0,0 +1,21 @@ +package coverart + +import "testing" + +func TestImageContentType(t *testing.T) { + cases := map[string]string{ + "/a/cover.jpg": "image/jpeg", + "/a/cover.JPG": "image/jpeg", + "/a/cover.jpeg": "image/jpeg", + "/a/cover.png": "image/png", + "/a/cover.webp": "image/webp", + "/a/cover.gif": "image/gif", + "/a/cover.bmp": "application/octet-stream", + "/a/cover": "application/octet-stream", + } + for in, want := range cases { + if got := ImageContentType(in); got != want { + t.Errorf("ImageContentType(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/coverart/embedded.go b/internal/coverart/embedded.go index f49ef1a9..57d72561 100644 --- a/internal/coverart/embedded.go +++ b/internal/coverart/embedded.go @@ -5,7 +5,7 @@ import ( "fmt" "os" - "github.com/dhowden/tag" + "github.com/Fabled-Sword/minstrel/internal/tagread" ) // ErrNoEmbeddedArt indicates the audio file has no embedded picture. @@ -33,7 +33,7 @@ func ExtractEmbeddedAlbumArt(path string) ([]byte, error) { } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { return nil, fmt.Errorf("tag read: %w", err) } diff --git a/internal/coverart/enricher.go b/internal/coverart/enricher.go index bcce89c1..14443e69 100644 --- a/internal/coverart/enricher.go +++ b/internal/coverart/enricher.go @@ -7,34 +7,50 @@ import ( "log/slog" "os" "path/filepath" + "strings" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // Enricher orchestrates the sidecar → provider chain → record cycle -// for one or many albums. Owns no DB pool itself; receives one per -// call so the boot backfill, post-scan trigger, and admin endpoints -// share state. +// for one or many albums. The boot backfill, the post-scan trigger and the +// admin endpoints share one. // -// DataDir is the optional managed-cache root. When set, sidecar writes -// that fail (e.g. read-only music mount) fall back to -// /album-art//cover.jpg so enrichment isn't gated -// on the music directory being writable. Empty disables fallback; -// tests use empty since they operate on writable tempdirs. +// It reads the library and never writes to it: other programs file music +// into the library, and a cover.jpg Minstrel dropped beside their files +// is one they did not put there. Art it pulls out of a file's tags or +// fetches from a provider goes into its own cache, +// /album-art//cover.jpg. type Enricher struct { pool *pgxpool.Pool logger *slog.Logger settings *SettingsService - DataDir string + dataDir string } -// NewEnricher constructs an Enricher. -func NewEnricher(pool *pgxpool.Pool, logger *slog.Logger, settings *SettingsService) *Enricher { - return &Enricher{pool: pool, logger: logger, settings: settings} +// NewEnricher constructs an Enricher that keeps the art it writes under +// dataDir. +func NewEnricher(pool *pgxpool.Pool, logger *slog.Logger, settings *SettingsService, dataDir string) *Enricher { + return &Enricher{pool: pool, logger: logger, settings: settings, dataDir: dataDir} +} + +// artCacheRoot is where the enricher keeps the album art it writes. +func (e *Enricher) artCacheRoot() string { + return filepath.Join(e.dataDir, "album-art") +} + +// inArtCache reports whether path is a file the enricher wrote into its +// own cache. Only those are its to remove. +func (e *Enricher) inArtCache(path string) bool { + if e.dataDir == "" || path == "" { + return false + } + rel, err := filepath.Rel(e.artCacheRoot(), path) + return err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) } // EnrichAlbum runs the chain for a single album. @@ -97,7 +113,7 @@ func (e *Enricher) EnrichAlbum(ctx context.Context, albumID pgtype.UUID) error { if row.TrackFilePath != nil && *row.TrackFilePath != "" { body, eerr := ExtractEmbeddedAlbumArt(*row.TrackFilePath) if eerr == nil { - dest, werr := e.writeAlbumArt(albumID, *row.TrackFilePath, body) + dest, werr := e.writeAlbumArt(albumID, body) if werr != nil { e.logger.Error("coverart: embedded write failed; leaving NULL", "album_id", uuidString(albumID), "err", werr) @@ -137,7 +153,7 @@ func (e *Enricher) EnrichAlbum(ctx context.Context, albumID pgtype.UUID) error { // crash. return e.recordAlbumCover(ctx, albumID, "", "none", currentVersion) } - dest, werr := e.writeAlbumArt(albumID, *row.TrackFilePath, body) + dest, werr := e.writeAlbumArt(albumID, body) if werr != nil { e.logger.Error("coverart: write file failed; leaving NULL", "album_id", uuidString(albumID), @@ -161,28 +177,21 @@ func (e *Enricher) EnrichAlbum(ctx context.Context, albumID pgtype.UUID) error { return nil // at least one transient failure; leave NULL for retry } -// writeAlbumArt persists art bytes for an album, preferring the sidecar -// location next to the track file. Falls back to the managed cache -// (/album-art//cover.jpg) when the sidecar location -// isn't writable (e.g. read-only music mount in a container) and -// DataDir is set. Returns the path that was actually written. -// -// Used by both the embedded-art layer and the external provider -// chain — both produce the same dest-and-fallback semantics. -func (e *Enricher) writeAlbumArt(albumID pgtype.UUID, trackFilePath string, body []byte) (string, error) { - albumDir := filepath.Dir(trackFilePath) - dest := filepath.Join(albumDir, "cover.jpg") - werr := os.WriteFile(dest, body, 0o644) - if werr != nil && e.DataDir != "" { - fallbackDir := filepath.Join(e.DataDir, "album-art", uuidString(albumID)) - if mkErr := os.MkdirAll(fallbackDir, 0o755); mkErr != nil { - return "", fmt.Errorf("managed-cache mkdir failed (sidecar: %v): %w", werr, mkErr) - } - dest = filepath.Join(fallbackDir, "cover.jpg") - werr = os.WriteFile(dest, body, 0o644) +// writeAlbumArt saves art for an album in the enricher's cache, +// /album-art//cover.jpg, and returns that path. The embedded-art +// layer and the provider chain both save through it. It never writes beside +// the music. +func (e *Enricher) writeAlbumArt(albumID pgtype.UUID, body []byte) (string, error) { + if e.dataDir == "" { + return "", errors.New("write cover: no data directory to keep album art in") } - if werr != nil { - return "", fmt.Errorf("write cover: %w", werr) + dir := filepath.Join(e.artCacheRoot(), uuidString(albumID)) + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", fmt.Errorf("write cover: %w", err) + } + dest := filepath.Join(dir, "cover.jpg") + if err := os.WriteFile(dest, body, 0o644); err != nil { + return "", fmt.Errorf("write cover: %w", err) } return dest, nil } @@ -345,11 +354,11 @@ func (e *Enricher) RetryAlbum(ctx context.Context, albumID pgtype.UUID) error { } return fmt.Errorf("get album: %w", err) } - // Delete the file only if we wrote it (mbcaa or theaudiodb). Sidecar - // images placed beside the music stay. - if row.CoverArtSource != nil && - (*row.CoverArtSource == "mbcaa" || *row.CoverArtSource == "theaudiodb") && - row.CoverArtPath != nil && *row.CoverArtPath != "" { + // Remove the old cover only when it is in the enricher's own cache. + // Anything else is a library file, even one an older Minstrel wrote + // beside the music, and stays: another program may have replaced it + // with its own since. + if row.CoverArtPath != nil && e.inArtCache(*row.CoverArtPath) { if err := os.Remove(*row.CoverArtPath); err != nil && !os.IsNotExist(err) { e.logger.Warn("coverart: remove old file failed", "album_id", uuidString(albumID), diff --git a/internal/coverart/enricher_test.go b/internal/coverart/enricher_test.go index 36e8c38a..7ccdbf15 100644 --- a/internal/coverart/enricher_test.go +++ b/internal/coverart/enricher_test.go @@ -13,32 +13,10 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } @@ -58,7 +36,21 @@ func newTestEnricher(t *testing.T, pool *pgxpool.Pool) *Enricher { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - return NewEnricher(pool, discardLogger(), s) + return NewEnricher(pool, discardLogger(), s, t.TempDir()) +} + +// cachedCover is where e keeps the cover it writes for an album. +func cachedCover(e *Enricher, albumID pgtype.UUID) string { + return filepath.Join(e.artCacheRoot(), uuidString(albumID), "cover.jpg") +} + +// assertNoCoverBeside fails when a cover.jpg sits in the album's folder: +// the enricher reads the library and never writes into it. +func assertNoCoverBeside(t *testing.T, albumDir string) { + t.Helper() + if _, err := os.Stat(filepath.Join(albumDir, "cover.jpg")); !os.IsNotExist(err) { + t.Errorf("a cover.jpg was written beside the music in %s (stat err %v)", albumDir, err) + } } // seedAlbumWithTrack creates an artist + album + track triple in a temp @@ -97,7 +89,7 @@ func seedAlbumWithTrack(t *testing.T, pool *pgxpool.Pool, title, artistName, mbi } func TestEnrichAlbum_SidecarFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Sid", "Artist", "") if err := os.WriteFile(filepath.Join(dir, "cover.jpg"), []byte("img"), 0o644); err != nil { t.Fatal(err) @@ -122,7 +114,7 @@ func TestEnrichAlbum_SidecarFound(t *testing.T) { } func TestEnrichAlbum_NoSidecarNoMBID_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, _ := seedAlbumWithTrack(t, pool, "NoMbid", "Artist", "") resetRegistryForTests() // deterministic empty registry (no provider can supply) t.Cleanup(resetRegistryForTests) @@ -143,7 +135,7 @@ func TestEnrichAlbum_NoSidecarNoMBID_SettlesNone(t *testing.T) { } func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Prov", "Artist", "test-mbid-123") upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -167,7 +159,7 @@ func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err) @@ -180,10 +172,11 @@ func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { if row.CoverArtSource == nil || *row.CoverArtSource != "mbcaa" { t.Errorf("source = %v, want 'mbcaa'", row.CoverArtSource) } - expectedPath := filepath.Join(dir, "cover.jpg") + expectedPath := cachedCover(e, id) if row.CoverArtPath == nil || *row.CoverArtPath != expectedPath { t.Errorf("path = %v, want %s", row.CoverArtPath, expectedPath) } + assertNoCoverBeside(t, dir) body, err := os.ReadFile(expectedPath) if err != nil { t.Fatalf("read file: %v", err) @@ -194,7 +187,7 @@ func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { } func TestEnrichAlbum_All404_RecordsNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, _ := seedAlbumWithTrack(t, pool, "Missing", "Artist", "missing-mbid") upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -215,7 +208,7 @@ func TestEnrichAlbum_All404_RecordsNone(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err) @@ -231,7 +224,7 @@ func TestEnrichAlbum_All404_RecordsNone(t *testing.T) { } func TestEnrichAlbum_AlreadySidecar_NoOp(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Already", "Artist", "") if err := os.WriteFile(filepath.Join(dir, "cover.jpg"), []byte("first"), 0o644); err != nil { t.Fatal(err) @@ -258,7 +251,7 @@ func TestEnrichAlbum_AlreadySidecar_NoOp(t *testing.T) { } func TestEnrichBatch_DrainsNullSourceOnly(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id1, dir1 := seedAlbumWithTrack(t, pool, "Drain1", "A", "") if err := os.WriteFile(filepath.Join(dir1, "cover.jpg"), []byte("c"), 0o644); err != nil { t.Fatal(err) @@ -305,7 +298,7 @@ func TestEnrichBatch_DrainsNullSourceOnly(t *testing.T) { } func TestRetryAlbum_DeletesWrittenFileAndRefetches(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Retry", "Artist", "retry-mbid") hits := 0 @@ -328,15 +321,16 @@ func TestRetryAlbum_DeletesWrittenFileAndRefetches(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("first enrich: %v", err) } - written := filepath.Join(dir, "cover.jpg") + written := cachedCover(e, id) if _, err := os.Stat(written); err != nil { t.Fatalf("expected file at %s: %v", written, err) } + assertNoCoverBeside(t, dir) if err := e.RetryAlbum(context.Background(), id); err != nil { t.Fatalf("retry: %v", err) @@ -350,8 +344,38 @@ func TestRetryAlbum_DeletesWrittenFileAndRefetches(t *testing.T) { } } +// A cover an older Minstrel wrote beside the music is recorded as fetched +// from a provider. Retrying the album leaves that file alone: it is in a +// folder another program files into, and may be that program's by now. +func TestRetryAlbum_LeavesACoverBesideTheMusic(t *testing.T) { + pool := dbtest.Pool(t) + id, dir := seedAlbumWithTrack(t, pool, "Beside", "Artist", "") + beside := filepath.Join(dir, "cover.jpg") + if err := os.WriteFile(beside, []byte("filed"), 0o644); err != nil { + t.Fatal(err) + } + mbcaa := "mbcaa" + if err := dbq.New(pool).SetAlbumCover(context.Background(), dbq.SetAlbumCoverParams{ + ID: id, Column2: beside, CoverArtSource: &mbcaa, + }); err != nil { + t.Fatal(err) + } + + e := newTestEnricher(t, pool) + if err := e.RetryAlbum(context.Background(), id); err != nil { + t.Fatalf("retry: %v", err) + } + if body, err := os.ReadFile(beside); err != nil || string(body) != "filed" { + t.Fatalf("the cover beside the music was removed or changed: body %q, err %v", body, err) + } + row, _ := dbq.New(pool).GetAlbumWithFirstTrackPath(context.Background(), id) + if row.CoverArtSource == nil || *row.CoverArtSource != "sidecar" { + t.Errorf("source after retry = %v, want 'sidecar' (the file is read as the library's own)", row.CoverArtSource) + } +} + func TestEnrichRetryMissing_DrainsNullAndNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) // Three albums: // id1: NULL source, has sidecar → drains, becomes 'sidecar'. // id2: 'none' source, has sidecar → cleared then drained, becomes 'sidecar'. @@ -412,7 +436,7 @@ func TestEnrichRetryMissing_DrainsNullAndNone(t *testing.T) { // TestEnrichAlbum_MultiProviderChain verifies that when provider A // returns ErrNotFound, the enricher continues to provider B. func TestEnrichAlbum_MultiProviderChain(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Multi", "Artist", "multi-mbid") // Provider A: always 404. @@ -452,7 +476,7 @@ func TestEnrichAlbum_MultiProviderChain(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err) @@ -465,15 +489,16 @@ func TestEnrichAlbum_MultiProviderChain(t *testing.T) { if row.CoverArtSource == nil || *row.CoverArtSource != "test-provider-b" { t.Errorf("source = %v, want 'test-provider-b' (provider B should win)", row.CoverArtSource) } - if body, err := os.ReadFile(filepath.Join(dir, "cover.jpg")); err != nil || string(body) != "PROVIDER_B_BYTES" { + if body, err := os.ReadFile(cachedCover(e, id)); err != nil || string(body) != "PROVIDER_B_BYTES" { t.Errorf("cover.jpg body = %q, err = %v", body, err) } + assertNoCoverBeside(t, dir) } // TestEnrichAlbum_TransientLeavesNull verifies that a transient error // from the provider leaves the row NULL for next-pass retry. func TestEnrichAlbum_TransientLeavesNull(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, _ := seedAlbumWithTrack(t, pool, "Transient", "Artist", "transient-mbid") upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -494,7 +519,7 @@ func TestEnrichAlbum_TransientLeavesNull(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err) @@ -514,7 +539,7 @@ func TestEnrichAlbum_TransientLeavesNull(t *testing.T) { // cover_art_source='none' and a stale version gets cleared and // re-enriched (sidecar wins because the album dir now has a cover file). func TestEnrichAlbum_StaleNoneFlipsAndRetries(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "StaleNone", "Artist", "") // Mark the album as 'none' (simulating a previous pass). diff --git a/internal/coverart/httpclient.go b/internal/coverart/httpclient.go deleted file mode 100644 index b9023dff..00000000 --- a/internal/coverart/httpclient.go +++ /dev/null @@ -1,207 +0,0 @@ -package coverart - -import ( - "context" - "encoding/json" - "fmt" - "io" - "math/rand" - "net/http" - "sync" - "time" -) - -// httpClientOptions configures a httpClient. Zero values get sensible -// defaults: 3 retries, 250ms base backoff, 1MB JSON body limit, 5MB -// image body limit, default http.Client with 30s timeout. -type httpClientOptions struct { - HTTPClient *http.Client - // Name is used as the prefix in wrapped error messages - // (e.g. "coverart lastfm: build request: ..."). Required. - Name string - // MinInterval throttles requests; 0 disables rate limiting. - MinInterval time.Duration - // MaxRetries is the number of retry attempts on 429 / 5xx. - MaxRetries int - // BaseBackoff is the base unit for exponential backoff; the - // helper sleeps 2^attempt × BaseBackoff ± 20% jitter. - BaseBackoff time.Duration - // TreatAuthAsTransient maps 401/403 responses to ErrTransient - // (vs. passing through as a generic non-2xx error). Providers - // with API keys (lastfm, theaudiodb) want this; key-less - // providers (deezer) leave it false. - TreatAuthAsTransient bool - // JSONBodyLimit and ImageBodyLimit cap the response body read - // to protect against runaway upstreams. - JSONBodyLimit int64 - ImageBodyLimit int64 -} - -// httpClient performs rate-limited, retrying GETs against an HTTP -// JSON or image upstream. Shared by the cover-art providers — each -// constructs its own client with provider-specific intervals and auth -// semantics, then calls getJSON/getImage with fully-formed URLs. -type httpClient struct { - opts httpClientOptions - - mu sync.Mutex - lastCall time.Time -} - -func newHTTPClient(opts httpClientOptions) *httpClient { - if opts.HTTPClient == nil { - opts.HTTPClient = &http.Client{Timeout: 30 * time.Second} - } - if opts.MaxRetries == 0 { - opts.MaxRetries = 3 - } - if opts.BaseBackoff == 0 { - opts.BaseBackoff = 250 * time.Millisecond - } - if opts.JSONBodyLimit == 0 { - opts.JSONBodyLimit = 1 * 1024 * 1024 - } - if opts.ImageBodyLimit == 0 { - opts.ImageBodyLimit = 5 * 1024 * 1024 - } - return &httpClient{opts: opts} -} - -// getJSON sends GET fullURL, decodes the 200 body into out (capped at -// JSONBodyLimit). Retries 429/5xx with exponential backoff up to -// MaxRetries. 404 → ErrNotFound. Non-2xx → wrapped ErrTransient. -func (c *httpClient) getJSON(ctx context.Context, fullURL string, out any) error { - for attempt := 0; attempt <= c.opts.MaxRetries; attempt++ { - if err := c.rateLimitWait(ctx); err != nil { - return err - } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil) - if err != nil { - return fmt.Errorf("coverart %s: build request: %w", c.opts.Name, err) - } - req.Header.Set("Accept", "application/json") - - resp, err := c.opts.HTTPClient.Do(req) - if err != nil { - if attempt < c.opts.MaxRetries { - if waitErr := c.backoff(ctx, attempt); waitErr != nil { - return waitErr - } - continue - } - return fmt.Errorf("%w: %v", ErrTransient, err) - } - - switch { - case resp.StatusCode == http.StatusNotFound: - _ = resp.Body.Close() - return ErrNotFound - case c.opts.TreatAuthAsTransient && - (resp.StatusCode == http.StatusUnauthorized || - resp.StatusCode == http.StatusForbidden): - _ = resp.Body.Close() - return fmt.Errorf("%w: status %d (auth)", ErrTransient, resp.StatusCode) - case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500: - _ = resp.Body.Close() - if attempt < c.opts.MaxRetries { - if waitErr := c.backoff(ctx, attempt); waitErr != nil { - return waitErr - } - continue - } - return fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode) - case resp.StatusCode != http.StatusOK: - _ = resp.Body.Close() - return fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode) - } - - body, err := io.ReadAll(io.LimitReader(resp.Body, c.opts.JSONBodyLimit)) - _ = resp.Body.Close() - if err != nil { - return fmt.Errorf("%w: read body: %v", ErrTransient, err) - } - if err := json.Unmarshal(body, out); err != nil { - return fmt.Errorf("%w: decode body: %v", ErrTransient, err) - } - return nil - } - return fmt.Errorf("%w: exhausted retries", ErrTransient) -} - -// getImage sends GET imgURL, returns the body bytes (capped at -// ImageBodyLimit). 404 → ErrNotFound; non-2xx / network → ErrTransient. -// No retry — image endpoints are typically CDN-backed and 429s are rare. -func (c *httpClient) getImage(ctx context.Context, imgURL string) ([]byte, error) { - if err := c.rateLimitWait(ctx); err != nil { - return nil, err - } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, imgURL, nil) - if err != nil { - return nil, fmt.Errorf("coverart %s: build request: %w", c.opts.Name, err) - } - req.Header.Set("Accept", "image/*") - resp, err := c.opts.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("%w: %v", ErrTransient, err) - } - defer func() { _ = resp.Body.Close() }() - - switch { - case resp.StatusCode == http.StatusNotFound: - return nil, ErrNotFound - case resp.StatusCode != http.StatusOK: - return nil, fmt.Errorf("%w: status %d", ErrTransient, resp.StatusCode) - } - - body, err := io.ReadAll(io.LimitReader(resp.Body, c.opts.ImageBodyLimit)) - if err != nil { - return nil, fmt.Errorf("%w: read body: %v", ErrTransient, err) - } - return body, nil -} - -// rateLimitWait blocks until at least MinInterval has elapsed since the -// last call, then claims the slot. Disabled when MinInterval is 0. -func (c *httpClient) rateLimitWait(ctx context.Context) error { - if c.opts.MinInterval <= 0 { - return nil - } - c.mu.Lock() - wait := time.Until(c.lastCall.Add(c.opts.MinInterval)) - if wait > 0 { - timer := time.NewTimer(wait) - c.mu.Unlock() - select { - case <-ctx.Done(): - timer.Stop() - return ctx.Err() - case <-timer.C: - } - c.mu.Lock() - } - c.lastCall = time.Now() - c.mu.Unlock() - return nil -} - -// backoff sleeps for 2^attempt × BaseBackoff ± 20% jitter, or until ctx is done. -func (c *httpClient) backoff(ctx context.Context, attempt int) error { - base := time.Duration(1<, parses strArtistThumb + @@ -140,7 +140,7 @@ func (p *theAudioDBProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) StrArtistFanart *string `json:"strArtistFanart"` } `json:"artists"` } - if err := p.client.getJSON(ctx, p.jsonURL("artist-mb.php?i="+ref.MBID), &resp); err != nil { + if err := p.client.GetJSON(ctx, p.jsonURL("artist-mb.php?i="+ref.MBID), &resp); err != nil { return nil, nil, err } if len(resp.Artists) == 0 { @@ -160,7 +160,7 @@ func (p *theAudioDBProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) } if thumbURL != "" { - thumb, err = p.client.getImage(ctx, thumbURL) + thumb, err = p.client.GetImage(ctx, thumbURL) if err != nil && !errors.Is(err, ErrTransient) && !errors.Is(err, ErrNotFound) { return nil, nil, err } @@ -170,7 +170,7 @@ func (p *theAudioDBProvider) FetchArtistArt(ctx context.Context, ref ArtistRef) } } if fanartURL != "" { - fanart, err = p.client.getImage(ctx, fanartURL) + fanart, err = p.client.GetImage(ctx, fanartURL) if err != nil && !errors.Is(err, ErrTransient) && !errors.Is(err, ErrNotFound) { return thumb, nil, err } @@ -202,5 +202,5 @@ func (p *theAudioDBProvider) TestConnection(ctx context.Context) error { IDAlbum *string `json:"idAlbum"` } `json:"album"` } - return p.client.getJSON(ctx, p.jsonURL("album-mb.php?i="+theAudioDBTestSampleMBID), &resp) + return p.client.GetJSON(ctx, p.jsonURL("album-mb.php?i="+theAudioDBTestSampleMBID), &resp) } diff --git a/internal/coverart/provider_theaudiodb_test.go b/internal/coverart/provider_theaudiodb_test.go index 471688a9..1d952c45 100644 --- a/internal/coverart/provider_theaudiodb_test.go +++ b/internal/coverart/provider_theaudiodb_test.go @@ -10,6 +10,8 @@ import ( "sync/atomic" "testing" "time" + + "github.com/Fabled-Sword/minstrel/internal/providers" ) // withTheAudioDBBaseURL temporarily redirects theAudioDBBaseURL to a @@ -28,7 +30,7 @@ func newTheAudioDBProviderForTest(t *testing.T, mockURL string) *theAudioDBProvi withTheAudioDBBaseURL(t, mockURL) p := &theAudioDBProvider{ - client: newHTTPClient(httpClientOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond}), + client: providers.NewHTTPClient(providers.HTTPOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond}), } Register(p) p.enabled.Store(true) @@ -37,21 +39,6 @@ func newTheAudioDBProviderForTest(t *testing.T, mockURL string) *theAudioDBProvi return p } -func TestTheAudioDB_ID(t *testing.T) { - resetRegistryForTests() - defer resetRegistryForTests() - p := &theAudioDBProvider{} - if p.ID() != "theaudiodb" { - t.Errorf("ID = %q, want theaudiodb", p.ID()) - } - if !p.RequiresAPIKey() { - t.Error("RequiresAPIKey = false, want true") - } - if !p.DefaultEnabled() { - t.Error("DefaultEnabled = false, want true") - } -} - func TestTheAudioDB_FetchAlbumCover_Success(t *testing.T) { imageBody := []byte("FAKE_JPEG") srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -234,7 +221,7 @@ func TestTheAudioDB_DefaultsToTestKeyOnEmpty(t *testing.T) { defer resetRegistryForTests() withTheAudioDBBaseURL(t, srv.URL) - p := &theAudioDBProvider{client: newHTTPClient(httpClientOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})} + p := &theAudioDBProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "theaudiodb", HTTPClient: &http.Client{Timeout: 5 * time.Second}, BaseBackoff: time.Millisecond})} Register(p) // Configure with empty key — should fall back to test key. if err := p.Configure(ProviderSettings{Enabled: true, APIKey: ""}); err != nil { diff --git a/internal/coverart/settings.go b/internal/coverart/settings.go index d2e51b14..707ba2bb 100644 --- a/internal/coverart/settings.go +++ b/internal/coverart/settings.go @@ -2,378 +2,108 @@ package coverart import ( "context" - "crypto/sha256" - "encoding/hex" "fmt" "log/slog" - "sort" - "strings" - "sync" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/providers" + "github.com/Fabled-Sword/minstrel/internal/secret" ) -// SettingsService reconciles the registry of compiled-in providers -// with the cover_art_provider_settings table at boot, and on every -// admin-initiated update. It owns the cover_art_sources_meta -// singleton's current_version stamp, bumping it whenever the -// *enabled set* of providers changes. +// ProviderUpdatePatch is the admin PATCH body; see providers.UpdatePatch. +type ProviderUpdatePatch = providers.UpdatePatch + +// ProviderInfo is a provider as GET /api/admin/cover-sources shows it. +type ProviderInfo = providers.Info + +// SettingsService is the cover-art providers' settings: the shared +// providers.Service over cover_art_provider_settings and the +// cover_art_sources_meta version, plus the cover-art capability views. type SettingsService struct { - pool *pgxpool.Pool - logger *slog.Logger - - mu sync.RWMutex - enabledIDs map[string]bool // provider_id → enabled - apiKeys map[string]string // provider_id → api_key (empty if NULL) - currentVersion int32 + *providers.Service } -// ProviderUpdatePatch is the admin-PATCH body shape. nil pointers -// mean "leave unchanged"; non-nil means "set to this value (which -// may be empty string for api_key clearing)". -type ProviderUpdatePatch struct { - Enabled *bool - APIKey *string -} - -// ProviderInfo is the SettingsService's view of a provider for the -// admin GET handler. Combines registry metadata with DB settings. -type ProviderInfo struct { - ID string - DisplayName string - RequiresAPIKey bool - Supports []string // "album_cover", "artist_thumb", "artist_fanart" - Enabled bool - APIKeySet bool - DisplayOrder int32 - Testable bool -} - -// NewSettingsService boots the service: reads the DB rows, INSERTs -// defaults for any registered provider missing a row, calls -// Configure() on every registered provider with the row data, and -// loads the current_version. Returns the populated service. +// NewSettingsService reconciles the registry with the settings table and +// Configures every provider. func NewSettingsService(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) (*SettingsService, error) { - s := &SettingsService{ - pool: pool, - logger: logger, - enabledIDs: map[string]bool{}, - apiKeys: map[string]string{}, + svc, err := providers.NewService(ctx, providers.Config{ + Registry: registry, + Store: settingsStore{q: dbq.New(pool)}, + KeyColumn: secret.CoverArtAPIKey, + Supports: supports, + Logger: logger, + }) + if err != nil { + return nil, fmt.Errorf("cover art settings boot: %w", err) } - if err := s.reconcile(ctx); err != nil { - return nil, fmt.Errorf("settings service boot: %w", err) - } - return s, nil + return &SettingsService{svc}, nil } -// reconcile reads the DB, INSERTs defaults for missing providers, -// calls Configure() on each registered provider, and loads the -// current_version into the cache. -func (s *SettingsService) reconcile(ctx context.Context) error { - q := dbq.New(s.pool) - - // Insert defaults for any registered provider missing a row. - registered := AllProviders() - for i, p := range registered { - if err := q.UpsertProviderSettings(ctx, dbq.UpsertProviderSettingsParams{ - ProviderID: p.ID(), - Enabled: p.DefaultEnabled(), - DisplayOrder: int32(i), - }); err != nil { - return fmt.Errorf("upsert provider %q: %w", p.ID(), err) - } - } - - // Read all rows back. - rows, err := q.ListProviderSettings(ctx) - if err != nil { - return fmt.Errorf("list provider settings: %w", err) - } - - // Build the lookup maps and call Configure on each registered - // provider with the corresponding row data. - settingsByID := map[string]dbq.CoverArtProviderSetting{} - for _, r := range rows { - settingsByID[r.ProviderID] = r - } - - s.mu.Lock() - defer s.mu.Unlock() - - s.enabledIDs = map[string]bool{} - s.apiKeys = map[string]string{} - for _, p := range registered { - row, ok := settingsByID[p.ID()] - if !ok { - s.logger.Warn("settings: missing row after upsert", "provider", p.ID()) - continue - } - key := "" - if row.ApiKey != nil { - key = *row.ApiKey - } - s.enabledIDs[p.ID()] = row.Enabled - s.apiKeys[p.ID()] = key - if err := p.Configure(ProviderSettings{Enabled: row.Enabled, APIKey: key}); err != nil { - s.logger.Warn("settings: provider Configure failed", - "provider", p.ID(), "err", err) - } - } - - v, err := q.GetCurrentSourcesVersion(ctx) - if err != nil { - return fmt.Errorf("get current sources version: %w", err) - } - s.currentVersion = v - return nil -} - -// EnabledAlbumProviders returns the enabled providers that implement -// AlbumCoverProvider, in registration order. Snapshot — caller must -// not mutate. +// EnabledAlbumProviders returns the enabled album-cover providers, in +// registration order. func (s *SettingsService) EnabledAlbumProviders() []AlbumCoverProvider { - s.mu.RLock() - defer s.mu.RUnlock() - var out []AlbumCoverProvider - for _, p := range AllProviders() { - if !s.enabledIDs[p.ID()] { - continue - } - if ap, ok := p.(AlbumCoverProvider); ok { - out = append(out, ap) - } - } - return out + return providers.EnabledAs[AlbumCoverProvider](s.Service) } -// EnabledArtistProviders is the parallel for ArtistArtProvider. +// EnabledArtistProviders returns the enabled artist-image providers, in +// registration order. func (s *SettingsService) EnabledArtistProviders() []ArtistArtProvider { - s.mu.RLock() - defer s.mu.RUnlock() - var out []ArtistArtProvider - for _, p := range AllProviders() { - if !s.enabledIDs[p.ID()] { - continue - } - if ap, ok := p.(ArtistArtProvider); ok { - out = append(out, ap) - } + return providers.EnabledAs[ArtistArtProvider](s.Service) +} + +// supports names what p can fetch, for the admin view. +func supports(p Provider) []string { + var out []string + if _, ok := p.(AlbumCoverProvider); ok { + out = append(out, "album_cover") + } + if _, ok := p.(ArtistArtProvider); ok { + out = append(out, "artist_thumb", "artist_fanart") } return out } -// CurrentVersion returns the current sources-set version (the stamp -// the enricher writes onto rows it processes). -func (s *SettingsService) CurrentVersion() int32 { - s.mu.RLock() - defer s.mu.RUnlock() - return s.currentVersion +// settingsStore is cover art's providers.Store. +type settingsStore struct{ q *dbq.Queries } + +func (st settingsStore) EnsureRow(ctx context.Context, id string, enabled bool, order int32) error { + return st.q.UpsertProviderSettings(ctx, dbq.UpsertProviderSettingsParams{ + ProviderID: id, Enabled: enabled, DisplayOrder: order, + }) } -// UpdateProvider applies an admin-UI patch. Returns versionBumped=true -// if the change altered the *enabled set* (not on key changes). -// Re-runs the provider's Configure() with the new settings. -func (s *SettingsService) UpdateProvider(ctx context.Context, providerID string, patch ProviderUpdatePatch) (bool, error) { - p, err := ProviderByID(providerID) +func (st settingsStore) List(ctx context.Context) ([]providers.Row, error) { + rows, err := st.q.ListProviderSettings(ctx) if err != nil { - return false, err + return nil, err } - - q := dbq.New(s.pool) - - // Compute current enabled-set signature before applying the patch. - s.mu.RLock() - beforeSig := enabledSetSignature(s.enabledIDs) - // Use the cached enabled value when the patch doesn't specify it, - // since the sqlc-generated Enabled field is bool (not *bool) and - // COALESCE($2, enabled) only works with a nullable param. Passing - // the current value when nil achieves the same "leave unchanged" - // semantics. - currentEnabled := s.enabledIDs[providerID] - s.mu.RUnlock() - - enabledVal := currentEnabled - if patch.Enabled != nil { - enabledVal = *patch.Enabled + out := make([]providers.Row, len(rows)) + for i, r := range rows { + out[i] = providers.Row{ProviderID: r.ProviderID, Enabled: r.Enabled, APIKey: r.ApiKey} } - - // Apply DB update. The sqlc-generated UpdateProviderSettingsParams - // uses Column3/ApiKey because the underlying SQL has $3::boolean - // (apiKeyChanged flag) and $4 (api_key value). The actual generated - // field for $4 is ApiKey *string. - apiKeyChanged := patch.APIKey != nil - if err := q.UpdateProviderSettings(ctx, dbq.UpdateProviderSettingsParams{ - ProviderID: providerID, - Enabled: enabledVal, - Column3: apiKeyChanged, - ApiKey: patch.APIKey, - }); err != nil { - return false, fmt.Errorf("update provider settings: %w", err) - } - - // Re-read rows + re-cache + Configure the changed provider. - rows, err := q.ListProviderSettings(ctx) - if err != nil { - return false, fmt.Errorf("re-list provider settings: %w", err) - } - - s.mu.Lock() - defer s.mu.Unlock() - - for _, r := range rows { - key := "" - if r.ApiKey != nil { - key = *r.ApiKey - } - s.enabledIDs[r.ProviderID] = r.Enabled - s.apiKeys[r.ProviderID] = key - if r.ProviderID == providerID { - if err := p.Configure(ProviderSettings{Enabled: r.Enabled, APIKey: key}); err != nil { - s.logger.Warn("provider Configure failed after update", - "provider", providerID, "err", err) - } - } - } - - afterSig := enabledSetSignature(s.enabledIDs) - if beforeSig == afterSig { - return false, nil - } - - newVersion, err := q.BumpSourcesVersion(ctx) - if err != nil { - return false, fmt.Errorf("bump sources version: %w", err) - } - s.currentVersion = newVersion - return true, nil + return out, nil } -// enabledSetSignature returns a deterministic string of the -// currently-enabled provider IDs. -func enabledSetSignature(enabledIDs map[string]bool) string { - ids := make([]string, 0, len(enabledIDs)) - for id, on := range enabledIDs { - if on { - ids = append(ids, id) - } - } - sort.Strings(ids) - return strings.Join(ids, ",") +func (st settingsStore) Save(ctx context.Context, id string, enabled, keyChanged bool, sealedKey *string) error { + return st.q.UpdateProviderSettings(ctx, dbq.UpdateProviderSettingsParams{ + ProviderID: id, Enabled: enabled, Column3: keyChanged, ApiKey: sealedKey, + }) } -// BumpVersionIfProvidersChanged compares the current registered-provider -// set (by ID) to the last set seen on a prior successful boot. If -// different, it atomically increments cover_art_sources_meta.current_version -// and stores the new hash, returning (newVersion, true, nil). If -// unchanged, returns (currentVersion, false, nil) without touching the DB. -// -// Used at boot to ensure rows previously settled to 'none' get re-tried -// once after a provider chain change (an update registers a new provider, -// or removes one). The version bump makes 'none' rows eligible on the next -// enrichment pass with no manual step. -func (s *SettingsService) BumpVersionIfProvidersChanged(ctx context.Context) (version int32, bumped bool, err error) { - hash := registeredProvidersHash() - q := dbq.New(s.pool) - - stored, qerr := q.GetCoverArtProvidersHash(ctx) - if qerr != nil { - return 0, false, fmt.Errorf("get providers hash: %w", qerr) - } - if stored == hash { - return s.CurrentVersion(), false, nil - } - - newVer, berr := q.BumpVersionAndSetProvidersHash(ctx, hash) - if berr != nil { - return 0, false, fmt.Errorf("bump version: %w", berr) - } - // Update the in-memory version so the next enrichment pass sees the new value. - s.mu.Lock() - s.currentVersion = newVer - s.mu.Unlock() - return newVer, true, nil +func (st settingsStore) Version(ctx context.Context) (int32, error) { + return st.q.GetCurrentSourcesVersion(ctx) } -// registeredProvidersHash returns the SHA-256 hex of the sorted, -// colon-joined registered provider IDs. -func registeredProvidersHash() string { - provs := AllProviders() - ids := make([]string, 0, len(provs)) - for _, p := range provs { - ids = append(ids, p.ID()) - } - sort.Strings(ids) - joined := strings.Join(ids, ":") - sum := sha256.Sum256([]byte(joined)) - return hex.EncodeToString(sum[:]) +func (st settingsStore) BumpVersion(ctx context.Context) (int32, error) { + return st.q.BumpSourcesVersion(ctx) } -// BumpVersion unconditionally increments cover_art_sources_meta.current_version -// and returns the new value. Used by the manual "Re-search missing art" -// admin endpoint, to re-attempt every 'none' row -// on the next enrichment pass. -// -// Distinct from BumpVersionIfProvidersChanged: that method is the boot- -// time auto-bump and skips the DB write when the registered-provider -// hash matches. This method always writes. -func (s *SettingsService) BumpVersion(ctx context.Context) (int32, error) { - q := dbq.New(s.pool) - // Reuse BumpVersionAndSetProvidersHash with the current registered- - // providers hash; this keeps the stored hash consistent (a manual - // bump is conceptually equivalent to "force the auto-bump path"). - newVer, err := q.BumpVersionAndSetProvidersHash(ctx, registeredProvidersHash()) - if err != nil { - return 0, fmt.Errorf("bump version: %w", err) - } - s.mu.Lock() - s.currentVersion = newVer - s.mu.Unlock() - return newVer, nil +func (st settingsStore) ProvidersHash(ctx context.Context) (string, error) { + return st.q.GetCoverArtProvidersHash(ctx) } -// TestProvider invokes TestConnection on the named provider if it -// implements TestableProvider. Returns ErrNotTestable if the -// provider doesn't, ErrProviderNotFound if not registered. -func (s *SettingsService) TestProvider(ctx context.Context, providerID string) error { - p, err := ProviderByID(providerID) - if err != nil { - return err - } - tp, ok := p.(TestableProvider) - if !ok { - return ErrNotTestable - } - return tp.TestConnection(ctx) -} - -// ListProviderInfo builds the wire-shaped slice for GET -// /api/admin/cover-sources. Returns providers in registration order. -func (s *SettingsService) ListProviderInfo() []ProviderInfo { - s.mu.RLock() - defer s.mu.RUnlock() - - var out []ProviderInfo - for i, p := range AllProviders() { - info := ProviderInfo{ - ID: p.ID(), - DisplayName: p.DisplayName(), - RequiresAPIKey: p.RequiresAPIKey(), - Enabled: s.enabledIDs[p.ID()], - APIKeySet: s.apiKeys[p.ID()] != "", - DisplayOrder: int32(i), - } - if _, ok := p.(AlbumCoverProvider); ok { - info.Supports = append(info.Supports, "album_cover") - } - if _, ok := p.(ArtistArtProvider); ok { - info.Supports = append(info.Supports, "artist_thumb", "artist_fanart") - } - if _, ok := p.(TestableProvider); ok { - info.Testable = true - } - out = append(out, info) - } - return out +func (st settingsStore) BumpVersionForProviders(ctx context.Context, hash string) (int32, error) { + return st.q.BumpVersionAndSetProvidersHash(ctx, hash) } diff --git a/internal/coverart/settings_test.go b/internal/coverart/settings_test.go index a43496cb..0c979690 100644 --- a/internal/coverart/settings_test.go +++ b/internal/coverart/settings_test.go @@ -4,6 +4,8 @@ import ( "context" "errors" "testing" + + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // fakeArtistProvider opts into ArtistArtProvider for capability tests. @@ -27,7 +29,7 @@ func (f *fakeTestableAlbumProvider) TestConnection(_ context.Context) error { } func TestSettingsService_BootInsertsDefaultRows(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -60,7 +62,7 @@ func TestSettingsService_BootInsertsDefaultRows(t *testing.T) { } func TestSettingsService_UpdateProvider_FlippingEnabledBumpsVersion(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -91,8 +93,8 @@ func TestSettingsService_UpdateProvider_FlippingEnabledBumpsVersion(t *testing.T } } -func TestSettingsService_UpdateProvider_KeyOnlyDoesNotBumpVersion(t *testing.T) { - pool := newPool(t) +func TestSettingsService_UpdateProvider_ReplacingAKeyDoesNotBumpVersion(t *testing.T) { + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -103,6 +105,11 @@ func TestSettingsService_UpdateProvider_KeyOnlyDoesNotBumpVersion(t *testing.T) t.Fatal(err) } + // The first key moves the version: the source searched without one. + firstKey := "first1" + if bumped, err := s.UpdateProvider(context.Background(), "fake-album", ProviderUpdatePatch{APIKey: &firstKey}); err != nil || !bumped { + t.Fatalf("first key: bumped=%v err=%v, want true nil", bumped, err) + } startVersion := s.CurrentVersion() newKey := "abc123" @@ -111,7 +118,7 @@ func TestSettingsService_UpdateProvider_KeyOnlyDoesNotBumpVersion(t *testing.T) t.Fatalf("UpdateProvider: %v", err) } if bumped { - t.Error("versionBumped = true, want false for key-only change") + t.Error("versionBumped = true, want false for a replaced key") } if s.CurrentVersion() != startVersion { t.Errorf("CurrentVersion changed: %d → %d, want unchanged", startVersion, s.CurrentVersion()) @@ -131,7 +138,7 @@ func TestSettingsService_UpdateProvider_KeyOnlyDoesNotBumpVersion(t *testing.T) } func TestSettingsService_UpdateProvider_ClearKey(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -161,7 +168,7 @@ func TestSettingsService_UpdateProvider_ClearKey(t *testing.T) { } func TestSettingsService_TestProvider_Routing(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -195,7 +202,7 @@ func TestSettingsService_TestProvider_Routing(t *testing.T) { } func TestSettingsService_ListProviderInfo_Capabilities(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -235,7 +242,7 @@ func TestSettingsService_ListProviderInfo_Capabilities(t *testing.T) { // TestSettingsService_BumpVersionIfProvidersChanged_FirstBoot: stored // hash is empty (column default ""), so a real provider set produces a bump. func TestSettingsService_BumpVersionIfProvidersChanged_FirstBoot(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -266,7 +273,7 @@ func TestSettingsService_BumpVersionIfProvidersChanged_FirstBoot(t *testing.T) { // call back-to-back returns bumped=false because the stored hash now // matches the registered set. func TestSettingsService_BumpVersionIfProvidersChanged_NoChange(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -299,7 +306,7 @@ func TestSettingsService_BumpVersionIfProvidersChanged_NoChange(t *testing.T) { // path. Distinct from BumpVersionIfProvidersChanged, this always writes // regardless of the stored provider-set hash. func TestSettingsService_BumpVersion_Increments(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -332,21 +339,3 @@ func TestSettingsService_BumpVersion_Increments(t *testing.T) { t.Errorf("second newVer = %d, want %d", newVer2, afterFirst+1) } } - -// TestRegisteredProvidersHash_StableAcrossOrder: registry order -// shouldn't matter because we sort before hashing. -func TestRegisteredProvidersHash_StableAcrossOrder(t *testing.T) { - // Hash is a function of the registered set; in this test it just - // needs to be deterministic and non-empty. - h1 := registeredProvidersHash() - h2 := registeredProvidersHash() - if h1 != h2 { - t.Errorf("hash is not deterministic: %q vs %q", h1, h2) - } - if h1 == "" { - t.Errorf("hash empty; expected at least one provider registered (or empty set is valid)") - } - if len(h1) != 64 { - t.Errorf("hash length = %d, want 64 (SHA-256 hex)", len(h1)) - } -} diff --git a/internal/coverart/sidecar.go b/internal/coverart/sidecar.go index 84b8e67a..2488a557 100644 --- a/internal/coverart/sidecar.go +++ b/internal/coverart/sidecar.go @@ -7,11 +7,13 @@ package coverart import ( + "cmp" "context" "os" "path/filepath" + "slices" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // SidecarNames is the lookup order for cover art living next to audio files. @@ -57,3 +59,36 @@ func ResolveAlbumPath(ctx context.Context, q *dbq.Queries, album dbq.Album) stri } return FindSidecar(filepath.Dir(tracks[0].FilePath)) } + +// artistAlbumsTried bounds how many of an artist's albums ResolveArtistPath +// looks through for a cover, so an artist with many coverless albums costs a +// few lookups rather than one per album. +const artistAlbumsTried = 10 + +// ResolveArtistPath returns the image file to show for an artist: the +// artist picture the artist-art providers fetched, if its file is there, or +// else the cover of the artist's most recently added album that has one, +// which is what Minstrel's artist cards show. "" means no image was found. +func ResolveArtistPath(ctx context.Context, q *dbq.Queries, artist dbq.Artist) string { + if artist.ArtistThumbPath != nil && *artist.ArtistThumbPath != "" { + if _, err := os.Stat(*artist.ArtistThumbPath); err == nil { + return *artist.ArtistThumbPath + } + } + albums, err := q.ListAlbumsByArtist(ctx, artist.ID) + if err != nil { + return "" + } + slices.SortStableFunc(albums, func(a, b dbq.Album) int { + return cmp.Compare(b.CreatedAt.Time.UnixNano(), a.CreatedAt.Time.UnixNano()) + }) + for i, album := range albums { + if i == artistAlbumsTried { + break + } + if path := ResolveAlbumPath(ctx, q, album); path != "" { + return path + } + } + return "" +} diff --git a/internal/db/artistnames.go b/internal/db/artistnames.go new file mode 100644 index 00000000..34e3cb7f --- /dev/null +++ b/internal/db/artistnames.go @@ -0,0 +1,47 @@ +package db + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" +) + +// ArtistNames names the artists credited on an album's tracks. A track's own +// artist differs from its album's on a compilation (Various Artists), so an +// album's track list names each track by its own artist. +type ArtistNames map[pgtype.UUID]string + +// TrackArtistNames reads the artists credited on the album's tracks. +func TrackArtistNames(ctx context.Context, q *dbq.Queries, albumID pgtype.UUID) (ArtistNames, error) { + rows, err := q.ListTrackArtistsForAlbum(ctx, albumID) + if err != nil { + return nil, err + } + out := make(ArtistNames, len(rows)) + for _, r := range rows { + out[r.ID] = r.Name + } + return out, nil +} + +// For is the name of artist id, or fallback when it is unknown (including on +// a nil ArtistNames, as a failed lookup returns). +func (n ArtistNames) For(id pgtype.UUID, fallback string) string { + if name, ok := n[id]; ok && name != "" { + return name + } + return fallback +} + +// TrackCredit is the artist credit to show beside track t, whose filing +// artist is named artistName: the track's full credit when its tags name a +// guest or several artists ("Low Tide Choir feat. Ruby Calloway"), else +// artistName. +func TrackCredit(t dbq.Track, artistName string) string { + if t.ArtistCredit != nil && *t.ArtistCredit != "" { + return *t.ArtistCredit + } + return artistName +} diff --git a/internal/db/db.go b/internal/db/db.go index dc63596c..e6f84a80 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -5,7 +5,6 @@ import ( "embed" "errors" "fmt" - "io/fs" "log/slog" "github.com/golang-migrate/migrate/v4" @@ -17,16 +16,6 @@ import ( //go:embed migrations/*.sql var migrationsFS embed.FS -// MigrationsFS exposes the embedded migration set for callers that need -// raw access (e.g. tests that construct their own migration runner). -func MigrationsFS() fs.FS { - sub, err := fs.Sub(migrationsFS, "migrations") - if err != nil { - panic(fmt.Sprintf("db: sub fs: %v", err)) - } - return sub -} - // Open establishes a pgx connection pool. The caller owns the returned pool // and must Close() it on shutdown. func Open(ctx context.Context, dsn string) (*pgxpool.Pool, error) { diff --git a/internal/db/dbq/acoustid.sql.go b/internal/db/dbq/acoustid.sql.go index 6315d96e..558a1088 100644 --- a/internal/db/dbq/acoustid.sql.go +++ b/internal/db/dbq/acoustid.sql.go @@ -120,8 +120,8 @@ type ListTracksNeedingAcoustIDLookupRow struct { DurationMs int32 } -// AcoustID recording-id lookup. Migration 0069 says what each -// lookup state means. +// AcoustID recording-id lookup. The CHECK on track_acoustid_lookups.state +// lists the lookup states. // The lookup worker's queue: present tracks with no tag MBID and no lookup // since their file last changed. A looked-up id is included once its row is // gone (the file changed), so the new bytes are checked rather than trusted. diff --git a/internal/db/dbq/acquisition.sql.go b/internal/db/dbq/acquisition.sql.go deleted file mode 100644 index d5ff1b48..00000000 --- a/internal/db/dbq/acquisition.sql.go +++ /dev/null @@ -1,362 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: acquisition.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const createAcquisitionService = `-- name: CreateAcquisitionService :one -INSERT INTO acquisition_services - (code, kind, protocol, label, category, timeout_ms, searches_per_hour) -VALUES - ($1, $2, $3, $4, - $5, $6, $7) -ON CONFLICT (code) DO NOTHING -RETURNING code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at -` - -type CreateAcquisitionServiceParams struct { - Code string - Kind string - Protocol string - Label string - Category string - TimeoutMs int32 - SearchesPerHour int32 -} - -// ON CONFLICT so the caller can try the next code when this one is taken. -func (q *Queries) CreateAcquisitionService(ctx context.Context, arg CreateAcquisitionServiceParams) (AcquisitionService, error) { - row := q.db.QueryRow(ctx, createAcquisitionService, - arg.Code, - arg.Kind, - arg.Protocol, - arg.Label, - arg.Category, - arg.TimeoutMs, - arg.SearchesPerHour, - ) - var i AcquisitionService - err := row.Scan( - &i.Code, - &i.Kind, - &i.Protocol, - &i.Label, - &i.Enabled, - &i.BaseUrl, - &i.ApiKey, - &i.Username, - &i.Password, - &i.Category, - &i.TimeoutMs, - &i.ServesSearch, - &i.ServesDownloads, - &i.ServesEnrichment, - &i.LocalPath, - &i.RemotePath, - &i.SearchesPerHour, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} - -const deleteAcquisitionService = `-- name: DeleteAcquisitionService :execrows -DELETE FROM acquisition_services WHERE code = $1 -` - -func (q *Queries) DeleteAcquisitionService(ctx context.Context, code string) (int64, error) { - result, err := q.db.Exec(ctx, deleteAcquisitionService, code) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const getAcquisitionService = `-- name: GetAcquisitionService :one -SELECT code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at FROM acquisition_services WHERE code = $1 -` - -// The full row, credentials included. For building a client, never for a -// response. -func (q *Queries) GetAcquisitionService(ctx context.Context, code string) (AcquisitionService, error) { - row := q.db.QueryRow(ctx, getAcquisitionService, code) - var i AcquisitionService - err := row.Scan( - &i.Code, - &i.Kind, - &i.Protocol, - &i.Label, - &i.Enabled, - &i.BaseUrl, - &i.ApiKey, - &i.Username, - &i.Password, - &i.Category, - &i.TimeoutMs, - &i.ServesSearch, - &i.ServesDownloads, - &i.ServesEnrichment, - &i.LocalPath, - &i.RemotePath, - &i.SearchesPerHour, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} - -const listAcquisitionServices = `-- name: ListAcquisitionServices :many - -SELECT code, kind, protocol, label, enabled, base_url, - (api_key <> '')::boolean AS has_api_key, - (password <> '')::boolean AS has_password, - username, category, timeout_ms, - serves_search, serves_downloads, serves_enrichment, - local_path, remote_path, searches_per_hour, - created_at, updated_at -FROM acquisition_services -ORDER BY kind, label, code -` - -type ListAcquisitionServicesRow struct { - Code string - Kind string - Protocol string - Label string - Enabled bool - BaseUrl string - HasApiKey bool - HasPassword bool - Username string - Category string - TimeoutMs int32 - ServesSearch bool - ServesDownloads bool - ServesEnrichment bool - LocalPath string - RemotePath string - SearchesPerHour int32 - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz -} - -// Indexers and download clients. -// Returns no secret, only whether one is set: this feeds the settings page. -func (q *Queries) ListAcquisitionServices(ctx context.Context) ([]ListAcquisitionServicesRow, error) { - rows, err := q.db.Query(ctx, listAcquisitionServices) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListAcquisitionServicesRow - for rows.Next() { - var i ListAcquisitionServicesRow - if err := rows.Scan( - &i.Code, - &i.Kind, - &i.Protocol, - &i.Label, - &i.Enabled, - &i.BaseUrl, - &i.HasApiKey, - &i.HasPassword, - &i.Username, - &i.Category, - &i.TimeoutMs, - &i.ServesSearch, - &i.ServesDownloads, - &i.ServesEnrichment, - &i.LocalPath, - &i.RemotePath, - &i.SearchesPerHour, - &i.CreatedAt, - &i.UpdatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listUsableAcquisitionServices = `-- name: ListUsableAcquisitionServices :many -SELECT code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at FROM acquisition_services -WHERE enabled AND base_url <> '' - AND CASE WHEN protocol = 'exchange' THEN - CASE $1::text - WHEN 'search' THEN serves_search - WHEN 'download' THEN serves_downloads - WHEN 'enrichment' THEN serves_enrichment - ELSE false - END - ELSE kind = $1::text - END -ORDER BY code -` - -// Every enabled, addressed service doing one job. An exchange row does a job -// when its switch for it is on; any other row does the job its kind names. -// Ordered by code so a fan-out is deterministic. -func (q *Queries) ListUsableAcquisitionServices(ctx context.Context, job string) ([]AcquisitionService, error) { - rows, err := q.db.Query(ctx, listUsableAcquisitionServices, job) - if err != nil { - return nil, err - } - defer rows.Close() - var items []AcquisitionService - for rows.Next() { - var i AcquisitionService - if err := rows.Scan( - &i.Code, - &i.Kind, - &i.Protocol, - &i.Label, - &i.Enabled, - &i.BaseUrl, - &i.ApiKey, - &i.Username, - &i.Password, - &i.Category, - &i.TimeoutMs, - &i.ServesSearch, - &i.ServesDownloads, - &i.ServesEnrichment, - &i.LocalPath, - &i.RemotePath, - &i.SearchesPerHour, - &i.CreatedAt, - &i.UpdatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const setAcquisitionServiceAPIKey = `-- name: SetAcquisitionServiceAPIKey :execrows -UPDATE acquisition_services SET api_key = $1, updated_at = now() -WHERE code = $2 -` - -type SetAcquisitionServiceAPIKeyParams struct { - ApiKey string - Code string -} - -func (q *Queries) SetAcquisitionServiceAPIKey(ctx context.Context, arg SetAcquisitionServiceAPIKeyParams) (int64, error) { - result, err := q.db.Exec(ctx, setAcquisitionServiceAPIKey, arg.ApiKey, arg.Code) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const setAcquisitionServicePassword = `-- name: SetAcquisitionServicePassword :execrows -UPDATE acquisition_services SET password = $1, updated_at = now() -WHERE code = $2 -` - -type SetAcquisitionServicePasswordParams struct { - Password string - Code string -} - -func (q *Queries) SetAcquisitionServicePassword(ctx context.Context, arg SetAcquisitionServicePasswordParams) (int64, error) { - result, err := q.db.Exec(ctx, setAcquisitionServicePassword, arg.Password, arg.Code) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const updateAcquisitionService = `-- name: UpdateAcquisitionService :one -UPDATE acquisition_services SET - label = $1, - enabled = $2, - base_url = $3, - username = $4, - category = $5, - timeout_ms = $6, - serves_search = $7, - serves_downloads = $8, - serves_enrichment = $9, - local_path = $10, - remote_path = $11, - searches_per_hour = $12, - updated_at = now() -WHERE code = $13 -RETURNING code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at -` - -type UpdateAcquisitionServiceParams struct { - Label string - Enabled bool - BaseUrl string - Username string - Category string - TimeoutMs int32 - ServesSearch bool - ServesDownloads bool - ServesEnrichment bool - LocalPath string - RemotePath string - SearchesPerHour int32 - Code string -} - -// Everything on the settings form except the credentials, which have their -// own write-only calls. -func (q *Queries) UpdateAcquisitionService(ctx context.Context, arg UpdateAcquisitionServiceParams) (AcquisitionService, error) { - row := q.db.QueryRow(ctx, updateAcquisitionService, - arg.Label, - arg.Enabled, - arg.BaseUrl, - arg.Username, - arg.Category, - arg.TimeoutMs, - arg.ServesSearch, - arg.ServesDownloads, - arg.ServesEnrichment, - arg.LocalPath, - arg.RemotePath, - arg.SearchesPerHour, - arg.Code, - ) - var i AcquisitionService - err := row.Scan( - &i.Code, - &i.Kind, - &i.Protocol, - &i.Label, - &i.Enabled, - &i.BaseUrl, - &i.ApiKey, - &i.Username, - &i.Password, - &i.Category, - &i.TimeoutMs, - &i.ServesSearch, - &i.ServesDownloads, - &i.ServesEnrichment, - &i.LocalPath, - &i.RemotePath, - &i.SearchesPerHour, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} diff --git a/internal/db/dbq/admin_status.sql.go b/internal/db/dbq/admin_status.sql.go index 84b47755..8446813d 100644 --- a/internal/db/dbq/admin_status.sql.go +++ b/internal/db/dbq/admin_status.sql.go @@ -11,42 +11,6 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) -const downloadsStatus = `-- name: DownloadsStatus :one -SELECT COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting', 'importing'))::bigint AS running, - COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::bigint AS needs_you, - MIN(COALESCE(import_updated_at, grabbed_at)) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::timestamptz AS needs_you_since, - COUNT(*) FILTER (WHERE imported_at > now() - INTERVAL '24 hours')::bigint AS imported_day, - COUNT(*) FILTER (WHERE ended_at > now() - INTERVAL '24 hours' - AND end_reason IN ('stalled', 'failed', 'gone', 'abandoned'))::bigint AS given_up_day - FROM grabs - WHERE ended_at IS NULL - OR ended_at > now() - INTERVAL '24 hours' - OR imported_at > now() - INTERVAL '24 hours' -` - -type DownloadsStatusRow struct { - Running int64 - NeedsYou int64 - NeedsYouSince pgtype.Timestamptz - ImportedDay int64 - GivenUpDay int64 -} - -// Downloads at a glance: running, waiting on a person (and since when), and -// the last day's imports and give-ups. -func (q *Queries) DownloadsStatus(ctx context.Context) (DownloadsStatusRow, error) { - row := q.db.QueryRow(ctx, downloadsStatus) - var i DownloadsStatusRow - err := row.Scan( - &i.Running, - &i.NeedsYou, - &i.NeedsYouSince, - &i.ImportedDay, - &i.GivenUpDay, - ) - return i, err -} - const libraryStatus = `-- name: LibraryStatus :one SELECT COUNT(*)::bigint AS tracks, COUNT(DISTINCT album_id)::bigint AS albums, @@ -109,8 +73,8 @@ type ListListeningNowRow struct { AlbumTitle string } -// The admin Overview's status sections: who is listening, what is -// downloading, what the library holds. Each is one cheap read. +// The admin Overview's status sections: who is listening and what the +// library holds. Each is one cheap read. // Plays in progress: open play events still inside their track's length, // with a few minutes' grace for a pause. A client that never says a play // ended would otherwise read as listening until the 24-hour sweep closes it. diff --git a/internal/db/dbq/admin_summary.sql.go b/internal/db/dbq/admin_summary.sql.go index 91860ec5..95d1ee77 100644 --- a/internal/db/dbq/admin_summary.sql.go +++ b/internal/db/dbq/admin_summary.sql.go @@ -13,8 +13,6 @@ import ( const adminSummary = `-- name: AdminSummary :one SELECT - (SELECT count(*) FROM requests WHERE status = 'pending')::bigint AS requests, - (SELECT min(requested_at) FROM requests WHERE status = 'pending')::timestamptz AS requests_since, -- A broken track is one report however it was found: a listener flagged -- it, or it failed to play. Counted by track, as the Reports -- page lists them. @@ -41,8 +39,6 @@ SELECT ` type AdminSummaryRow struct { - Requests int64 - RequestsSince pgtype.Timestamptz Reports int64 ReportsSince pgtype.Timestamptz Duplicates int64 @@ -62,8 +58,6 @@ func (q *Queries) AdminSummary(ctx context.Context) (AdminSummaryRow, error) { row := q.db.QueryRow(ctx, adminSummary) var i AdminSummaryRow err := row.Scan( - &i.Requests, - &i.RequestsSince, &i.Reports, &i.ReportsSince, &i.Duplicates, diff --git a/internal/db/dbq/albums.sql.go b/internal/db/dbq/albums.sql.go index fc3c8768..4dc54cc6 100644 --- a/internal/db/dbq/albums.sql.go +++ b/internal/db/dbq/albums.sql.go @@ -11,6 +11,72 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const anyAlbumAnnounced = `-- name: AnyAlbumAnnounced :one +SELECT EXISTS (SELECT 1 FROM albums WHERE announced_at IS NOT NULL) +` + +// False on a library no scan has announced yet: its first import is the +// library being set up, not new music arriving. +func (q *Queries) AnyAlbumAnnounced(ctx context.Context) (bool, error) { + row := q.db.QueryRow(ctx, anyAlbumAnnounced) + var exists bool + err := row.Scan(&exists) + return exists, err +} + +const claimUnannouncedAlbums = `-- name: ClaimUnannouncedAlbums :many +WITH claimed AS ( + UPDATE albums SET announced_at = now() + WHERE announced_at IS NULL + RETURNING id, title, artist_id, created_at +) +SELECT c.id, c.title, ar.id AS artist_id, ar.name AS artist_name, + (EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = c.id AND t.missing_since IS NULL) + AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = c.id AND t.added_at < c.created_at))::boolean AS arrived + FROM claimed c + JOIN artists ar ON ar.id = c.artist_id + ORDER BY c.created_at, c.id +` + +type ClaimUnannouncedAlbumsRow struct { + ID pgtype.UUID + Title string + ArtistID pgtype.UUID + ArtistName string + Arrived bool +} + +// Stamps every album not yet announced and returns them, so each album is +// claimed by exactly one scan even when a full scan and the watcher overlap. +// arrived is whether it is news: it has a track on disk, and none of its +// tracks is older than the album. An album that formed because files already +// in the library were retagged holds older tracks, and is not new music. +func (q *Queries) ClaimUnannouncedAlbums(ctx context.Context) ([]ClaimUnannouncedAlbumsRow, error) { + rows, err := q.db.Query(ctx, claimUnannouncedAlbums) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ClaimUnannouncedAlbumsRow + for rows.Next() { + var i ClaimUnannouncedAlbumsRow + if err := rows.Scan( + &i.ID, + &i.Title, + &i.ArtistID, + &i.ArtistName, + &i.Arrived, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const countAlbums = `-- name: CountAlbums :one SELECT COUNT(*) FROM albums ` @@ -23,19 +89,6 @@ func (q *Queries) CountAlbums(ctx context.Context) (int64, error) { return count, err } -const countAlbumsByArtist = `-- name: CountAlbumsByArtist :one -SELECT COUNT(*) FROM albums WHERE artist_id = $1 -` - -// Used by request-progress reporting to count how many albums have been -// ingested for a matched artist while a request is still in flight. -func (q *Queries) CountAlbumsByArtist(ctx context.Context, artistID pgtype.UUID) (int64, error) { - row := q.db.QueryRow(ctx, countAlbumsByArtist, artistID) - var count int64 - err := row.Scan(&count) - return count, err -} - const countAlbumsMatching = `-- name: CountAlbumsMatching :one SELECT COUNT(*) FROM albums WHERE title ILIKE '%' || $1::text || '%' ` @@ -71,8 +124,39 @@ func (q *Queries) DeleteAlbumIfEmpty(ctx context.Context, id pgtype.UUID) (Delet return i, err } +const deleteEmptyAlbums = `-- name: DeleteEmptyAlbums :many +DELETE FROM albums a +WHERE NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) + AND a.created_at < now() - interval '10 minutes' +RETURNING a.id +` + +// The scan's tidy-up: removes every album no track points to, missing or +// not. A row made in the last ten minutes is left alone, so a file being +// added right now (its album created, its track not yet written) is never +// caught between the two. +func (q *Queries) DeleteEmptyAlbums(ctx context.Context) ([]pgtype.UUID, error) { + rows, err := q.db.Query(ctx, deleteEmptyAlbums) + if err != nil { + return nil, err + } + defer rows.Close() + var items []pgtype.UUID + for rows.Next() { + var id pgtype.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + items = append(items, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const getAlbumByArtistAndTitle = `-- name: GetAlbumByArtistAndTitle :one -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid FROM albums +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at FROM albums WHERE albums.artist_id = $1 AND albums.title = $2 AND ($3::text IS NULL OR albums.release_group_mbid IS NULL OR albums.release_group_mbid = $3) @@ -119,12 +203,13 @@ func (q *Queries) GetAlbumByArtistAndTitle(ctx context.Context, arg GetAlbumByAr &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ) return i, err } const getAlbumByID = `-- name: GetAlbumByID :one -SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid FROM albums WHERE id = $1 +SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums WHERE id = $1 ` func (q *Queries) GetAlbumByID(ctx context.Context, id pgtype.UUID) (Album, error) { @@ -143,6 +228,7 @@ func (q *Queries) GetAlbumByID(ctx context.Context, id pgtype.UUID) (Album, erro &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ) return i, err } @@ -193,7 +279,7 @@ func (q *Queries) GetAlbumCoverageRollup(ctx context.Context) (GetAlbumCoverageR } const getAlbumWithArtist = `-- name: GetAlbumWithArtist :one -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM albums JOIN artists ON artists.id = albums.artist_id WHERE albums.id = $1 @@ -223,13 +309,14 @@ func (q *Queries) GetAlbumWithArtist(ctx context.Context, id pgtype.UUID) (GetAl &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ) return i, err } const getAlbumsByIDs = `-- name: GetAlbumsByIDs :many -SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid FROM albums WHERE id = ANY($1::uuid[]) +SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums WHERE id = ANY($1::uuid[]) ` // Batched lookup used by /api/library/sync to hydrate upsert payloads @@ -256,6 +343,7 @@ func (q *Queries) GetAlbumsByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([ &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -267,24 +355,8 @@ func (q *Queries) GetAlbumsByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([ return items, nil } -const getReleaseGroupForReleaseMbid = `-- name: GetReleaseGroupForReleaseMbid :one -SELECT release_group_mbid::text - FROM albums - WHERE mbid = $1 AND release_group_mbid IS NOT NULL - LIMIT 1 -` - -// The release group the library already knows for a release id, so a -// request carrying a release id can be repaired without asking MusicBrainz. -func (q *Queries) GetReleaseGroupForReleaseMbid(ctx context.Context, mbid *string) (string, error) { - row := q.db.QueryRow(ctx, getReleaseGroupForReleaseMbid, mbid) - var release_group_mbid string - err := row.Scan(&release_group_mbid) - return release_group_mbid, err -} - const listAlbumsAlphaByArtist = `-- name: ListAlbumsAlphaByArtist :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.sort_name AS artist_sort_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.sort_name AS artist_sort_name FROM albums JOIN artists ON artists.id = albums.artist_id ORDER BY artists.sort_name, albums.sort_title @@ -325,6 +397,7 @@ func (q *Queries) ListAlbumsAlphaByArtist(ctx context.Context, arg ListAlbumsAlp &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistSortName, ); err != nil { return nil, err @@ -338,7 +411,7 @@ func (q *Queries) ListAlbumsAlphaByArtist(ctx context.Context, arg ListAlbumsAlp } const listAlbumsAlphaByName = `-- name: ListAlbumsAlphaByName :many -SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid FROM albums ORDER BY sort_title LIMIT $1 OFFSET $2 +SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums ORDER BY sort_title LIMIT $1 OFFSET $2 ` type ListAlbumsAlphaByNameParams struct { @@ -368,6 +441,7 @@ func (q *Queries) ListAlbumsAlphaByName(ctx context.Context, arg ListAlbumsAlpha &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -380,7 +454,7 @@ func (q *Queries) ListAlbumsAlphaByName(ctx context.Context, arg ListAlbumsAlpha } const listAlbumsAlphaWithArtist = `-- name: ListAlbumsAlphaWithArtist :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM albums JOIN artists ON artists.id = albums.artist_id ORDER BY albums.sort_title, albums.id @@ -421,6 +495,7 @@ func (q *Queries) ListAlbumsAlphaWithArtist(ctx context.Context, arg ListAlbumsA &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err @@ -434,7 +509,7 @@ func (q *Queries) ListAlbumsAlphaWithArtist(ctx context.Context, arg ListAlbumsA } const listAlbumsByArtist = `-- name: ListAlbumsByArtist :many -SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid FROM albums WHERE artist_id = $1 ORDER BY release_date NULLS LAST, sort_title +SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums WHERE artist_id = $1 ORDER BY release_date NULLS LAST, sort_title ` func (q *Queries) ListAlbumsByArtist(ctx context.Context, artistID pgtype.UUID) ([]Album, error) { @@ -459,6 +534,7 @@ func (q *Queries) ListAlbumsByArtist(ctx context.Context, artistID pgtype.UUID) &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -471,7 +547,7 @@ func (q *Queries) ListAlbumsByArtist(ctx context.Context, artistID pgtype.UUID) } const listAlbumsByArtistWithTrackCount = `-- name: ListAlbumsByArtistWithTrackCount :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, (SELECT count(*) FROM tracks t WHERE t.album_id = albums.id)::bigint AS track_count FROM albums @@ -509,6 +585,7 @@ func (q *Queries) ListAlbumsByArtistWithTrackCount(ctx context.Context, artistID &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.TrackCount, ); err != nil { return nil, err @@ -522,7 +599,7 @@ func (q *Queries) ListAlbumsByArtistWithTrackCount(ctx context.Context, artistID } const listAlbumsByGenre = `-- name: ListAlbumsByGenre :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at FROM albums WHERE EXISTS ( SELECT 1 @@ -574,6 +651,7 @@ func (q *Queries) ListAlbumsByGenre(ctx context.Context, arg ListAlbumsByGenrePa &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -598,7 +676,7 @@ WITH plays AS ( WHERE t.missing_since IS NULL GROUP BY t.album_id ) -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at FROM per_album pa JOIN albums ON albums.id = pa.album_id ORDER BY pa.cnt DESC, albums.id @@ -637,6 +715,7 @@ func (q *Queries) ListAlbumsFrequentlyPlayedByUser(ctx context.Context, arg List &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -705,7 +784,7 @@ func (q *Queries) ListAlbumsMissingMbidWithTrack(ctx context.Context, limit int3 } const listAlbumsNewest = `-- name: ListAlbumsNewest :many -SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid FROM albums ORDER BY created_at DESC LIMIT $1 OFFSET $2 +SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums ORDER BY created_at DESC LIMIT $1 OFFSET $2 ` type ListAlbumsNewestParams struct { @@ -735,6 +814,7 @@ func (q *Queries) ListAlbumsNewest(ctx context.Context, arg ListAlbumsNewestPara &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -747,7 +827,7 @@ func (q *Queries) ListAlbumsNewest(ctx context.Context, arg ListAlbumsNewestPara } const listAlbumsRandom = `-- name: ListAlbumsRandom :many -SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid FROM albums ORDER BY random() LIMIT $1 +SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums ORDER BY random() LIMIT $1 ` func (q *Queries) ListAlbumsRandom(ctx context.Context, limit int32) ([]Album, error) { @@ -772,6 +852,7 @@ func (q *Queries) ListAlbumsRandom(ctx context.Context, limit int32) ([]Album, e &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -796,7 +877,7 @@ WITH plays AS ( WHERE t.missing_since IS NULL GROUP BY t.album_id ) -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at FROM per_album pa JOIN albums ON albums.id = pa.album_id ORDER BY pa.last_played DESC, albums.id @@ -839,6 +920,7 @@ func (q *Queries) ListAlbumsRecentlyPlayedByUser(ctx context.Context, arg ListAl &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -851,7 +933,7 @@ func (q *Queries) ListAlbumsRecentlyPlayedByUser(ctx context.Context, arg ListAl } const listRecentlyAddedAlbumsWithArtist = `-- name: ListRecentlyAddedAlbumsWithArtist :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM albums JOIN artists ON artists.id = albums.artist_id ORDER BY albums.created_at DESC, albums.id @@ -889,6 +971,7 @@ func (q *Queries) ListRecentlyAddedAlbumsWithArtist(ctx context.Context, limit i &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err @@ -902,9 +985,9 @@ func (q *Queries) ListRecentlyAddedAlbumsWithArtist(ctx context.Context, limit i } const searchAlbums = `-- name: SearchAlbums :many -SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid FROM albums +SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at FROM albums WHERE title ILIKE '%' || $1 || '%' -ORDER BY sort_title +ORDER BY sort_title, id LIMIT $2 OFFSET $3 ` @@ -936,6 +1019,7 @@ func (q *Queries) SearchAlbums(ctx context.Context, arg SearchAlbumsParams) ([]A &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -1007,33 +1091,13 @@ type SetAlbumReleaseGroupMbidIfNullParams struct { ReleaseGroupMbid *string } -// Heal the release-group id on an existing album row, from a rescan's -// tags or from the re-acquisition sweeper's MusicBrainz lookup. Only fills a -// NULL, so a tag never gets overwritten by a later guess or vice versa. +// Heal the release-group id on an existing album row from a rescan's tags. +// Only fills a NULL, so a stored id is never overwritten. func (q *Queries) SetAlbumReleaseGroupMbidIfNull(ctx context.Context, arg SetAlbumReleaseGroupMbidIfNullParams) error { _, err := q.db.Exec(ctx, setAlbumReleaseGroupMbidIfNull, arg.ID, arg.ReleaseGroupMbid) return err } -const setReleaseGroupForReleaseMbidIfNull = `-- name: SetReleaseGroupForReleaseMbidIfNull :exec -UPDATE albums - SET release_group_mbid = $1::text, - updated_at = now() - WHERE mbid = $2::text AND release_group_mbid IS NULL -` - -type SetReleaseGroupForReleaseMbidIfNullParams struct { - ReleaseGroupMbid string - ReleaseMbid string -} - -// Cache a MusicBrainz-resolved release group onto the album row that -// holds the release, filling only a NULL. -func (q *Queries) SetReleaseGroupForReleaseMbidIfNull(ctx context.Context, arg SetReleaseGroupForReleaseMbidIfNullParams) error { - _, err := q.db.Exec(ctx, setReleaseGroupForReleaseMbidIfNull, arg.ReleaseGroupMbid, arg.ReleaseMbid) - return err -} - const upsertAlbum = `-- name: UpsertAlbum :one INSERT INTO albums (title, sort_title, artist_id, release_date, mbid, cover_art_path, release_group_mbid) VALUES ($1, $2, $3, $4, $5, $6, $7) @@ -1046,7 +1110,7 @@ DO UPDATE SET cover_art_path = EXCLUDED.cover_art_path, release_group_mbid = COALESCE(EXCLUDED.release_group_mbid, albums.release_group_mbid), updated_at = now() -RETURNING id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid +RETURNING id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version, release_group_mbid, announced_at ` type UpsertAlbumParams struct { @@ -1083,6 +1147,7 @@ func (q *Queries) UpsertAlbum(ctx context.Context, arg UpsertAlbumParams) (Album &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ) return i, err } diff --git a/internal/db/dbq/artists.sql.go b/internal/db/dbq/artists.sql.go index 9011384a..4f10514e 100644 --- a/internal/db/dbq/artists.sql.go +++ b/internal/db/dbq/artists.sql.go @@ -66,6 +66,40 @@ func (q *Queries) DeleteArtistIfEmpty(ctx context.Context, id pgtype.UUID) (pgty return id_2, err } +const deleteEmptyArtists = `-- name: DeleteEmptyArtists :many +DELETE FROM artists a +WHERE NOT EXISTS (SELECT 1 FROM albums al WHERE al.artist_id = a.id) + AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.artist_id = a.id) + AND NOT EXISTS (SELECT 1 FROM playlists p WHERE p.seed_artist_id = a.id) + AND a.created_at < now() - interval '10 minutes' +RETURNING a.id +` + +// The scan's tidy-up: removes every artist with no albums and no tracks. +// An artist a Songs like playlist is seeded from is kept, since that +// playlist must always name its seed; it goes when the playlist is next +// rebuilt without it. Rows made in the last ten minutes are left alone, as +// in DeleteEmptyAlbums. +func (q *Queries) DeleteEmptyArtists(ctx context.Context) ([]pgtype.UUID, error) { + rows, err := q.db.Query(ctx, deleteEmptyArtists) + if err != nil { + return nil, err + } + defer rows.Close() + var items []pgtype.UUID + for rows.Next() { + var id pgtype.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + items = append(items, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const getArtistByID = `-- name: GetArtistByID :one SELECT id, name, sort_name, mbid, created_at, updated_at, artist_thumb_path, artist_fanart_path, artist_art_source, artist_art_sources_version FROM artists WHERE id = $1 ` @@ -184,46 +218,6 @@ func (q *Queries) ListArtists(ctx context.Context) ([]Artist, error) { return items, nil } -const listArtistsAlpha = `-- name: ListArtistsAlpha :many -SELECT id, name, sort_name, mbid, created_at, updated_at, artist_thumb_path, artist_fanart_path, artist_art_source, artist_art_sources_version FROM artists ORDER BY sort_name, name, id LIMIT $1 OFFSET $2 -` - -type ListArtistsAlphaParams struct { - Limit int32 - Offset int32 -} - -func (q *Queries) ListArtistsAlpha(ctx context.Context, arg ListArtistsAlphaParams) ([]Artist, error) { - rows, err := q.db.Query(ctx, listArtistsAlpha, arg.Limit, arg.Offset) - if err != nil { - return nil, err - } - defer rows.Close() - var items []Artist - for rows.Next() { - var i Artist - if err := rows.Scan( - &i.ID, - &i.Name, - &i.SortName, - &i.Mbid, - &i.CreatedAt, - &i.UpdatedAt, - &i.ArtistThumbPath, - &i.ArtistFanartPath, - &i.ArtistArtSource, - &i.ArtistArtSourcesVersion, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const listArtistsAlphaWithCovers = `-- name: ListArtistsAlphaWithCovers :many SELECT artists.id, artists.name, artists.sort_name, artists.mbid, artists.created_at, artists.updated_at, artists.artist_thumb_path, artists.artist_fanart_path, artists.artist_art_source, artists.artist_art_sources_version, cov.id AS cover_album_id, @@ -370,10 +364,44 @@ func (q *Queries) ListArtistsNewest(ctx context.Context, arg ListArtistsNewestPa return items, nil } +const listTrackArtistsForAlbum = `-- name: ListTrackArtistsForAlbum :many +SELECT DISTINCT ar.id, ar.name + FROM artists ar + JOIN tracks t ON t.artist_id = ar.id + WHERE t.album_id = $1 +` + +type ListTrackArtistsForAlbumRow struct { + ID pgtype.UUID + Name string +} + +// The artists credited on an album's tracks. They differ from the album's own +// artist on a compilation and on a track with a featured guest. +func (q *Queries) ListTrackArtistsForAlbum(ctx context.Context, albumID pgtype.UUID) ([]ListTrackArtistsForAlbumRow, error) { + rows, err := q.db.Query(ctx, listTrackArtistsForAlbum, albumID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListTrackArtistsForAlbumRow + for rows.Next() { + var i ListTrackArtistsForAlbumRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const searchArtists = `-- name: SearchArtists :many SELECT id, name, sort_name, mbid, created_at, updated_at, artist_thumb_path, artist_fanart_path, artist_art_source, artist_art_sources_version FROM artists WHERE name ILIKE '%' || $1 || '%' -ORDER BY sort_name +ORDER BY sort_name, id LIMIT $2 OFFSET $3 ` @@ -485,7 +513,10 @@ type UpsertArtistParams struct { Mbid *string } -// Insert or update by mbid when present; otherwise by (name, sort_name). +// Inserts an artist, or updates the row that already has this mbid. Only +// the mbid is matched: called without one, it inserts a new row every time, +// so a caller that may meet the same artist again looks it up by name first +// (the scanner's resolveArtist does). // Callers pass the canonical sort_name; scanner is responsible for derivation. func (q *Queries) UpsertArtist(ctx context.Context, arg UpsertArtistParams) (Artist, error) { row := q.db.QueryRow(ctx, upsertArtist, arg.Name, arg.SortName, arg.Mbid) diff --git a/internal/db/dbq/audit_log.sql.go b/internal/db/dbq/audit_log.sql.go index 873c0c4d..8c1c3f86 100644 --- a/internal/db/dbq/audit_log.sql.go +++ b/internal/db/dbq/audit_log.sql.go @@ -30,44 +30,6 @@ func (q *Queries) CountAuditLogByActions(ctx context.Context, arg CountAuditLogB return column_1, err } -const listAuditLog = `-- name: ListAuditLog :many -SELECT id, actor_id, target_id, action, metadata, created_at FROM audit_log - ORDER BY created_at DESC - LIMIT $1 OFFSET $2 -` - -type ListAuditLogParams struct { - Limit int32 - Offset int32 -} - -func (q *Queries) ListAuditLog(ctx context.Context, arg ListAuditLogParams) ([]AuditLog, error) { - rows, err := q.db.Query(ctx, listAuditLog, arg.Limit, arg.Offset) - if err != nil { - return nil, err - } - defer rows.Close() - var items []AuditLog - for rows.Next() { - var i AuditLog - if err := rows.Scan( - &i.ID, - &i.ActorID, - &i.TargetID, - &i.Action, - &i.Metadata, - &i.CreatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const listAuditLogByActions = `-- name: ListAuditLogByActions :many SELECT id, actor_id, target_id, action, metadata, created_at FROM audit_log WHERE action = ANY($1::text[]) diff --git a/internal/db/dbq/backups.sql.go b/internal/db/dbq/backups.sql.go new file mode 100644 index 00000000..e886bef4 --- /dev/null +++ b/internal/db/dbq/backups.sql.go @@ -0,0 +1,389 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: backups.sql + +package dbq + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const backupMusicProgress = `-- name: BackupMusicProgress :one +SELECT count(*)::bigint AS total_files, + COALESCE(sum(t.file_size), 0)::bigint AS total_bytes, + count(*) FILTER (WHERE m.error = '' AND m.size = t.file_size AND t.updated_at <= m.checked_at)::bigint AS sent_files, + COALESCE(sum(t.file_size) FILTER (WHERE m.error = '' AND m.size = t.file_size AND t.updated_at <= m.checked_at), 0)::bigint AS sent_bytes, + count(*) FILTER (WHERE m.error <> '' AND m.size = t.file_size AND t.updated_at <= m.checked_at)::bigint AS refused_files + FROM tracks t + LEFT JOIN backup_music_files m ON m.track_id = t.id + WHERE t.missing_since IS NULL +` + +type BackupMusicProgressRow struct { + TotalFiles int64 + TotalBytes int64 + SentFiles int64 + SentBytes int64 + RefusedFiles int64 +} + +// How much of the library the backup holds as it is now. +func (q *Queries) BackupMusicProgress(ctx context.Context) (BackupMusicProgressRow, error) { + row := q.db.QueryRow(ctx, backupMusicProgress) + var i BackupMusicProgressRow + err := row.Scan( + &i.TotalFiles, + &i.TotalBytes, + &i.SentFiles, + &i.SentBytes, + &i.RefusedFiles, + ) + return i, err +} + +const backupRunTimes = `-- name: BackupRunTimes :one +SELECT + COALESCE((SELECT max(started_at) FROM backup_runs WHERE status = 'succeeded'), + 'epoch'::timestamptz)::timestamptz AS last_success, + COALESCE((SELECT max(started_at) FROM backup_runs), + 'epoch'::timestamptz)::timestamptz AS last_attempt, + COALESCE((SELECT min(started_at) FROM backup_runs + WHERE status = 'failed' + AND started_at > COALESCE((SELECT max(started_at) FROM backup_runs WHERE status = 'succeeded'), + 'epoch'::timestamptz)), + 'epoch'::timestamptz)::timestamptz AS failing_since +` + +type BackupRunTimesRow struct { + LastSuccess pgtype.Timestamptz + LastAttempt pgtype.Timestamptz + FailingSince pgtype.Timestamptz +} + +// The times the verdict turns on. A run that never happened is the epoch, +// so the row always exists. failing_since is the first failure after the last +// success, and the epoch when the latest finished run succeeded. +func (q *Queries) BackupRunTimes(ctx context.Context) (BackupRunTimesRow, error) { + row := q.db.QueryRow(ctx, backupRunTimes) + var i BackupRunTimesRow + err := row.Scan(&i.LastSuccess, &i.LastAttempt, &i.FailingSince) + return i, err +} + +const failUnfinishedBackupRuns = `-- name: FailUnfinishedBackupRuns :execrows +UPDATE backup_runs + SET status = 'failed', finished_at = now(), + error = 'The server stopped while the backup was running.' + WHERE status = 'running' +` + +func (q *Queries) FailUnfinishedBackupRuns(ctx context.Context) (int64, error) { + result, err := q.db.Exec(ctx, failUnfinishedBackupRuns) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const finishBackupRun = `-- name: FinishBackupRun :exec +UPDATE backup_runs + SET status = $2, + finished_at = now(), + location = $3, + bytes = $4, + error = $5, + music_files = $6, + music_bytes = $7, + music_note = $8 + WHERE id = $1 +` + +type FinishBackupRunParams struct { + ID pgtype.UUID + Status string + Location string + Bytes int64 + Error string + MusicFiles int32 + MusicBytes int64 + MusicNote string +} + +func (q *Queries) FinishBackupRun(ctx context.Context, arg FinishBackupRunParams) error { + _, err := q.db.Exec(ctx, finishBackupRun, + arg.ID, + arg.Status, + arg.Location, + arg.Bytes, + arg.Error, + arg.MusicFiles, + arg.MusicBytes, + arg.MusicNote, + ) + return err +} + +const getBackupSettings = `-- name: GetBackupSettings :one + +SELECT id, enabled, destination, folder, endpoint, bucket, access_key, secret_key, run_hour, upload_limit_kib, updated_at, include_music FROM backup_settings WHERE id = true +` + +// Minstrel's own backup: its settings and its runs. +func (q *Queries) GetBackupSettings(ctx context.Context) (BackupSetting, error) { + row := q.db.QueryRow(ctx, getBackupSettings) + var i BackupSetting + err := row.Scan( + &i.ID, + &i.Enabled, + &i.Destination, + &i.Folder, + &i.Endpoint, + &i.Bucket, + &i.AccessKey, + &i.SecretKey, + &i.RunHour, + &i.UploadLimitKib, + &i.UpdatedAt, + &i.IncludeMusic, + ) + return i, err +} + +const listBackupRuns = `-- name: ListBackupRuns :many +SELECT id, trigger, status, started_at, finished_at, location, bytes, error, + music_files, music_bytes, music_note + FROM backup_runs + ORDER BY started_at DESC + LIMIT $1 +` + +func (q *Queries) ListBackupRuns(ctx context.Context, limit int32) ([]BackupRun, error) { + rows, err := q.db.Query(ctx, listBackupRuns, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var items []BackupRun + for rows.Next() { + var i BackupRun + if err := rows.Scan( + &i.ID, + &i.Trigger, + &i.Status, + &i.StartedAt, + &i.FinishedAt, + &i.Location, + &i.Bytes, + &i.Error, + &i.MusicFiles, + &i.MusicBytes, + &i.MusicNote, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const pendingBackupMusic = `-- name: PendingBackupMusic :many +SELECT t.id, t.file_path, t.file_size, + m.size AS sent_size, m.mtime AS sent_mtime, m.error AS sent_error + FROM tracks t + LEFT JOIN backup_music_files m ON m.track_id = t.id + WHERE t.missing_since IS NULL + AND t.file_path > $1::text + AND (m.track_id IS NULL OR m.size <> t.file_size OR t.updated_at > m.checked_at + OR (m.error <> '' AND m.checked_at < (SELECT updated_at FROM backup_settings))) + ORDER BY t.file_path + LIMIT $2 +` + +type PendingBackupMusicParams struct { + AfterPath string + MaxRows int32 +} + +type PendingBackupMusicRow struct { + ID pgtype.UUID + FilePath string + FileSize int64 + SentSize *int64 + SentMtime pgtype.Timestamptz + SentError *string +} + +// Library files the backup may not hold as they are now, in path order from +// after_path, so a night that runs out of time carries on where it stopped: +// never sent, a different size, touched by a scan since they were last +// checked, or refused before the settings were last saved (a fixed key gets +// another go). The caller compares the file's own size and mtime before +// sending. +func (q *Queries) PendingBackupMusic(ctx context.Context, arg PendingBackupMusicParams) ([]PendingBackupMusicRow, error) { + rows, err := q.db.Query(ctx, pendingBackupMusic, arg.AfterPath, arg.MaxRows) + if err != nil { + return nil, err + } + defer rows.Close() + var items []PendingBackupMusicRow + for rows.Next() { + var i PendingBackupMusicRow + if err := rows.Scan( + &i.ID, + &i.FilePath, + &i.FileSize, + &i.SentSize, + &i.SentMtime, + &i.SentError, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const pruneBackupRuns = `-- name: PruneBackupRuns :execrows +DELETE FROM backup_runs WHERE status <> 'running' AND started_at < $1 +` + +func (q *Queries) PruneBackupRuns(ctx context.Context, startedAt pgtype.Timestamptz) (int64, error) { + result, err := q.db.Exec(ctx, pruneBackupRuns, startedAt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const recordBackupMusic = `-- name: RecordBackupMusic :exec +INSERT INTO backup_music_files (track_id, size, mtime, location, error) +VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (track_id) DO UPDATE + SET size = EXCLUDED.size, mtime = EXCLUDED.mtime, location = EXCLUDED.location, + error = EXCLUDED.error, checked_at = now() +` + +type RecordBackupMusicParams struct { + TrackID pgtype.UUID + Size int64 + Mtime pgtype.Timestamptz + Location string + Error string +} + +func (q *Queries) RecordBackupMusic(ctx context.Context, arg RecordBackupMusicParams) error { + _, err := q.db.Exec(ctx, recordBackupMusic, + arg.TrackID, + arg.Size, + arg.Mtime, + arg.Location, + arg.Error, + ) + return err +} + +const refusedBackupMusic = `-- name: RefusedBackupMusic :many +SELECT t.file_path, m.error, m.checked_at + FROM backup_music_files m + JOIN tracks t ON t.id = m.track_id + WHERE m.error <> '' AND m.size = t.file_size AND t.updated_at <= m.checked_at + ORDER BY m.checked_at DESC + LIMIT $1 +` + +type RefusedBackupMusicRow struct { + FilePath string + Error string + CheckedAt pgtype.Timestamptz +} + +func (q *Queries) RefusedBackupMusic(ctx context.Context, limit int32) ([]RefusedBackupMusicRow, error) { + rows, err := q.db.Query(ctx, refusedBackupMusic, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var items []RefusedBackupMusicRow + for rows.Next() { + var i RefusedBackupMusicRow + if err := rows.Scan(&i.FilePath, &i.Error, &i.CheckedAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const saveBackupSettings = `-- name: SaveBackupSettings :exec +UPDATE backup_settings + SET enabled = $1, + destination = $2, + folder = $3, + endpoint = $4, + bucket = $5, + access_key = $6, + secret_key = $7, + run_hour = $8, + upload_limit_kib = $9, + include_music = $10, + updated_at = now() + WHERE id = true +` + +type SaveBackupSettingsParams struct { + Enabled bool + Destination string + Folder string + Endpoint string + Bucket string + AccessKey string + SecretKey string + RunHour int16 + UploadLimitKib int32 + IncludeMusic bool +} + +func (q *Queries) SaveBackupSettings(ctx context.Context, arg SaveBackupSettingsParams) error { + _, err := q.db.Exec(ctx, saveBackupSettings, + arg.Enabled, + arg.Destination, + arg.Folder, + arg.Endpoint, + arg.Bucket, + arg.AccessKey, + arg.SecretKey, + arg.RunHour, + arg.UploadLimitKib, + arg.IncludeMusic, + ) + return err +} + +const startBackupRun = `-- name: StartBackupRun :one +INSERT INTO backup_runs (trigger) VALUES ($1) +RETURNING id, started_at +` + +type StartBackupRunRow struct { + ID pgtype.UUID + StartedAt pgtype.Timestamptz +} + +func (q *Queries) StartBackupRun(ctx context.Context, trigger string) (StartBackupRunRow, error) { + row := q.db.QueryRow(ctx, startBackupRun, trigger) + var i StartBackupRunRow + err := row.Scan(&i.ID, &i.StartedAt) + return i, err +} diff --git a/internal/db/dbq/browse.sql.go b/internal/db/dbq/browse.sql.go index 88f9502d..984ca698 100644 --- a/internal/db/dbq/browse.sql.go +++ b/internal/db/dbq/browse.sql.go @@ -100,7 +100,7 @@ func (q *Queries) ListAlbumYearsWithCount(ctx context.Context) ([]ListAlbumYears } const listAlbumsByGenreWithArtist = `-- name: ListAlbumsByGenreWithArtist :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM albums JOIN artists ON artists.id = albums.artist_id WHERE EXISTS ( @@ -153,6 +153,7 @@ func (q *Queries) ListAlbumsByGenreWithArtist(ctx context.Context, arg ListAlbum &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err @@ -165,8 +166,74 @@ func (q *Queries) ListAlbumsByGenreWithArtist(ctx context.Context, arg ListAlbum return items, nil } +const listAlbumsByYearOrdered = `-- name: ListAlbumsByYearOrdered :many +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at FROM albums +WHERE albums.release_date IS NOT NULL + AND EXTRACT(YEAR FROM albums.release_date)::int + BETWEEN LEAST($1::int, $2::int) + AND GREATEST($1::int, $2::int) + AND EXISTS ( + SELECT 1 FROM tracks + WHERE tracks.album_id = albums.id + AND tracks.missing_since IS NULL + ) +ORDER BY CASE WHEN $1::int <= $2::int THEN albums.release_date END ASC, + CASE WHEN $1::int > $2::int THEN albums.release_date END DESC, + albums.sort_title, albums.id +LIMIT $4 OFFSET $3 +` + +type ListAlbumsByYearOrderedParams struct { + FromYear int32 + ToYear int32 + Off int32 + Lim int32 +} + +// Subsonic getAlbumList2 type=byYear: albums released within an inclusive +// year range, oldest first, or newest first when the caller asks for the +// range backwards (fromYear > toYear), as the Subsonic API defines it. +func (q *Queries) ListAlbumsByYearOrdered(ctx context.Context, arg ListAlbumsByYearOrderedParams) ([]Album, error) { + rows, err := q.db.Query(ctx, listAlbumsByYearOrdered, + arg.FromYear, + arg.ToYear, + arg.Off, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Album + for rows.Next() { + var i Album + if err := rows.Scan( + &i.ID, + &i.Title, + &i.SortTitle, + &i.ArtistID, + &i.ReleaseDate, + &i.Mbid, + &i.CoverArtPath, + &i.CreatedAt, + &i.UpdatedAt, + &i.CoverArtSource, + &i.CoverArtSourcesVersion, + &i.ReleaseGroupMbid, + &i.AnnouncedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const listAlbumsByYearRangeWithArtist = `-- name: ListAlbumsByYearRangeWithArtist :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM albums JOIN artists ON artists.id = albums.artist_id WHERE albums.release_date IS NOT NULL @@ -221,6 +288,7 @@ func (q *Queries) ListAlbumsByYearRangeWithArtist(ctx context.Context, arg ListA &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err @@ -299,7 +367,8 @@ func (q *Queries) ListGenresForArtist(ctx context.Context, artistID pgtype.UUID) const listGenresWithCount = `-- name: ListGenresWithCount :many -SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count +SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count, + COUNT(DISTINCT tracks.album_id)::bigint AS album_count FROM tracks JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) ON true WHERE trim(g.genre) <> '' @@ -311,6 +380,7 @@ ORDER BY track_count DESC, trim(g.genre) type ListGenresWithCountRow struct { Genre string TrackCount int64 + AlbumCount int64 } // Every query in this file filters `tracks.missing_since IS NULL`. A row whose @@ -349,6 +419,9 @@ type ListGenresWithCountRow struct { // Ordered by count first: raw ID3 data has a long tail of one-off junk tags, // so alphabetical would bury the handful of genres a library actually has // a lot of. Name breaks ties for a stable order. +// +// album_count is the albums holding at least one of those tracks, which is +// what a Subsonic app shows beside the genre. // Ordered by the expression, not the output alias: `ORDER BY genre` is // ambiguous between the alias and tracks.genre, and sqlc rejects it. func (q *Queries) ListGenresWithCount(ctx context.Context) ([]ListGenresWithCountRow, error) { @@ -360,7 +433,96 @@ func (q *Queries) ListGenresWithCount(ctx context.Context) ([]ListGenresWithCoun var items []ListGenresWithCountRow for rows.Next() { var i ListGenresWithCountRow - if err := rows.Scan(&i.Genre, &i.TrackCount); err != nil { + if err := rows.Scan(&i.Genre, &i.TrackCount, &i.AlbumCount); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listTracksByGenre = `-- name: ListTracksByGenre :many +SELECT tracks.id, tracks.title, tracks.album_id, tracks.artist_id, tracks.track_number, tracks.disc_number, tracks.duration_ms, tracks.file_path, tracks.file_size, tracks.file_format, tracks.bitrate, tracks.mbid, tracks.genre, tracks.added_at, tracks.updated_at, tracks.tag_source, tracks.tag_sources_version, tracks.tag_read_version, tracks.missing_since, tracks.mbid_source, tracks.song_id, tracks.song_key, tracks.source_verdict, tracks.source_verdict_at, tracks.emptied_at, tracks.removed_reason, tracks.removed_by, tracks.artist_credit +FROM tracks +JOIN albums ON albums.id = tracks.album_id +WHERE tracks.missing_since IS NULL + AND EXISTS ( + SELECT 1 + FROM regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) + WHERE trim(g.genre) = trim($1::text) + ) + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = $2 AND q.track_id = tracks.id + ) +ORDER BY albums.sort_title, albums.id, + tracks.disc_number NULLS FIRST, tracks.track_number NULLS FIRST, tracks.id +LIMIT $4 OFFSET $3 +` + +type ListTracksByGenreParams struct { + Genre string + UserID pgtype.UUID + Off int32 + Lim int32 +} + +type ListTracksByGenreRow struct { + Track Track +} + +// One genre's songs for the Subsonic getSongsByGenre, a page at a time. +// Splits and trims identically to ListGenresWithCount, so the songs a genre +// leads to are the ones it counted. The listener's quarantined tracks are +// left out: an app asks for these to play them. Album by album in track +// order, so paging walks a stable order. +func (q *Queries) ListTracksByGenre(ctx context.Context, arg ListTracksByGenreParams) ([]ListTracksByGenreRow, error) { + rows, err := q.db.Query(ctx, listTracksByGenre, + arg.Genre, + arg.UserID, + arg.Off, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListTracksByGenreRow + for rows.Next() { + var i ListTracksByGenreRow + if err := rows.Scan( + &i.Track.ID, + &i.Track.Title, + &i.Track.AlbumID, + &i.Track.ArtistID, + &i.Track.TrackNumber, + &i.Track.DiscNumber, + &i.Track.DurationMs, + &i.Track.FilePath, + &i.Track.FileSize, + &i.Track.FileFormat, + &i.Track.Bitrate, + &i.Track.Mbid, + &i.Track.Genre, + &i.Track.AddedAt, + &i.Track.UpdatedAt, + &i.Track.TagSource, + &i.Track.TagSourcesVersion, + &i.Track.TagReadVersion, + &i.Track.MissingSince, + &i.Track.MbidSource, + &i.Track.SongID, + &i.Track.SongKey, + &i.Track.SourceVerdict, + &i.Track.SourceVerdictAt, + &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, + ); err != nil { return nil, err } items = append(items, i) diff --git a/internal/db/dbq/candidate_artist_tags.sql.go b/internal/db/dbq/candidate_artist_tags.sql.go deleted file mode 100644 index 12a9ceba..00000000 --- a/internal/db/dbq/candidate_artist_tags.sql.go +++ /dev/null @@ -1,228 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: candidate_artist_tags.sql - -package dbq - -import ( - "context" -) - -const countCandidateArtistTagCoverage = `-- name: CountCandidateArtistTagCoverage :one -SELECT count(*)::bigint AS processed, - count(*) FILTER (WHERE tag_source <> 'none')::bigint AS with_tags - FROM candidate_artist_tag_state -` - -type CountCandidateArtistTagCoverageRow struct { - Processed int64 - WithTags int64 -} - -// Operator-facing coverage: how many distinct candidates have been processed, -// and how many of those actually yielded tags. The gap is the honest ceiling -// from the task — obscure artists with no MBID presence or no upstream tags -// stay thin no matter how long the worker runs, and that is worth being able -// to see rather than inferring from a silent surface. -func (q *Queries) CountCandidateArtistTagCoverage(ctx context.Context) (CountCandidateArtistTagCoverageRow, error) { - row := q.db.QueryRow(ctx, countCandidateArtistTagCoverage) - var i CountCandidateArtistTagCoverageRow - err := row.Scan(&i.Processed, &i.WithTags) - return i, err -} - -const deleteCandidateArtistTags = `-- name: DeleteCandidateArtistTags :exec -DELETE FROM candidate_artist_tags WHERE candidate_mbid = $1 -` - -// Clear a candidate's cached tags before rewriting (atomic replace by the -// caller, same shape as DeleteTrackTags). -func (q *Queries) DeleteCandidateArtistTags(ctx context.Context, candidateMbid string) error { - _, err := q.db.Exec(ctx, deleteCandidateArtistTags, candidateMbid) - return err -} - -const gcDeleteOrphanedCandidateArtistTagState = `-- name: GcDeleteOrphanedCandidateArtistTagState :execrows -DELETE FROM candidate_artist_tag_state s - WHERE NOT EXISTS ( - SELECT 1 FROM artist_similarity_unmatched u - WHERE u.candidate_mbid = s.candidate_mbid - ) - OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = s.candidate_mbid) -` - -// Same sweep for the bookkeeping rows. Kept as a separate statement rather -// than a cascade: the two tables are independent by design (a 'none' outcome -// has state but no tags), so neither can be the parent of the other. -func (q *Queries) GcDeleteOrphanedCandidateArtistTagState(ctx context.Context) (int64, error) { - result, err := q.db.Exec(ctx, gcDeleteOrphanedCandidateArtistTagState) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const gcDeleteOrphanedCandidateArtistTags = `-- name: GcDeleteOrphanedCandidateArtistTags :execrows -DELETE FROM candidate_artist_tags t - WHERE NOT EXISTS ( - SELECT 1 FROM artist_similarity_unmatched u - WHERE u.candidate_mbid = t.candidate_mbid - ) - OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = t.candidate_mbid) -` - -// Drops cached tags for candidates that no longer appear in the similarity -// feed, or that have since been added to the library (their tags now live in -// track_tags). The feed is refetched periodically and churns, so without this -// the cache only ever grows. -func (q *Queries) GcDeleteOrphanedCandidateArtistTags(ctx context.Context) (int64, error) { - result, err := q.db.Exec(ctx, gcDeleteOrphanedCandidateArtistTags) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const insertCandidateArtistTag = `-- name: InsertCandidateArtistTag :exec -INSERT INTO candidate_artist_tags (candidate_mbid, tag, weight) -VALUES ($1, $2, $3) -ON CONFLICT (candidate_mbid, tag) - DO UPDATE SET weight = GREATEST(candidate_artist_tags.weight, EXCLUDED.weight) -` - -type InsertCandidateArtistTagParams struct { - CandidateMbid string - Tag string - Weight float64 -} - -// Upsert one (candidate, tag); keep the stronger weight when two providers -// agree on a tag with different folksonomy strengths. -func (q *Queries) InsertCandidateArtistTag(ctx context.Context, arg InsertCandidateArtistTagParams) error { - _, err := q.db.Exec(ctx, insertCandidateArtistTag, arg.CandidateMbid, arg.Tag, arg.Weight) - return err -} - -const listCandidateArtistTagsForMbids = `-- name: ListCandidateArtistTagsForMbids :many -SELECT candidate_mbid, tag, weight - FROM candidate_artist_tags - WHERE candidate_mbid = ANY($1::text[]) -` - -// Cached tags for a set of candidates, for the taste-overlap ranking. -// One row per (candidate, tag). -func (q *Queries) ListCandidateArtistTagsForMbids(ctx context.Context, dollar_1 []string) ([]CandidateArtistTag, error) { - rows, err := q.db.Query(ctx, listCandidateArtistTagsForMbids, dollar_1) - if err != nil { - return nil, err - } - defer rows.Close() - var items []CandidateArtistTag - for rows.Next() { - var i CandidateArtistTag - if err := rows.Scan(&i.CandidateMbid, &i.Tag, &i.Weight); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listCandidateArtistsMissingTags = `-- name: ListCandidateArtistsMissingTags :many - -SELECT u.candidate_mbid, - coalesce(max(u.candidate_name), '')::text AS candidate_name, - sum(u.score)::float8 AS total_score - FROM artist_similarity_unmatched u - LEFT JOIN candidate_artist_tag_state s ON s.candidate_mbid = u.candidate_mbid - WHERE NOT EXISTS (SELECT 1 FROM artists a WHERE a.mbid = u.candidate_mbid) - AND ( - s.candidate_mbid IS NULL - OR (s.tag_source = 'none' AND s.tag_sources_version < $1) - ) - GROUP BY u.candidate_mbid - ORDER BY total_score DESC, u.candidate_mbid - LIMIT $2 -` - -type ListCandidateArtistsMissingTagsParams struct { - TagSourcesVersion int32 - Limit int32 -} - -type ListCandidateArtistsMissingTagsRow struct { - CandidateMbid string - CandidateName string - TotalScore float64 -} - -// Folksonomy tags for out-of-library Discover candidates. Parallel to -// track_tags.sql, but keyed by MBID because the artist has no local row. See -// 0050_candidate_artist_tags.up.sql for why the bookkeeping is its own table. -// Candidates eligible for tag enrichment: never processed (no state row) or -// settled 'none' under an older provider version. -// -// artist_similarity_unmatched holds one row per (seed, candidate, source), so -// this GROUPs to one row per candidate — enriching the same MBID once per seed -// that pointed at it would multiply the API calls for no gain. -// -// ORDER BY summed similarity DESC is the load-bearing part. The candidate pool -// is O(library artists x neighbours per artist) — thousands — and MusicBrainz -// allows ~1 req/s, so it can NEVER be fully enriched in one pass. Draining in -// strength order means the candidates most likely to actually reach a user's -// deck get tags first, and the long tail fills in over subsequent ticks -// instead of starving behind it. -// -// Already-in-library candidates are skipped: they have an artists row, so -// their tags belong in track_tags, and the suggestion query filters them out -// anyway. $1 = current tag_sources_version, $2 = limit. -// candidate_name is coalesced to the empty string so it lands non-nullable in -// Go: the name is only a Last.fm lookup key, and empty simply means "MBID-keyed -// providers only", which the provider chain already handles. max() is an -// arbitrary-but-deterministic pick when several seeds spell one MBID -// differently. -func (q *Queries) ListCandidateArtistsMissingTags(ctx context.Context, arg ListCandidateArtistsMissingTagsParams) ([]ListCandidateArtistsMissingTagsRow, error) { - rows, err := q.db.Query(ctx, listCandidateArtistsMissingTags, arg.TagSourcesVersion, arg.Limit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListCandidateArtistsMissingTagsRow - for rows.Next() { - var i ListCandidateArtistsMissingTagsRow - if err := rows.Scan(&i.CandidateMbid, &i.CandidateName, &i.TotalScore); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const setCandidateArtistTagState = `-- name: SetCandidateArtistTagState :exec -INSERT INTO candidate_artist_tag_state (candidate_mbid, tag_source, tag_sources_version) -VALUES ($1, $2, $3) -ON CONFLICT (candidate_mbid) DO UPDATE - SET tag_source = EXCLUDED.tag_source, - tag_sources_version = EXCLUDED.tag_sources_version, - updated_at = now() -` - -type SetCandidateArtistTagStateParams struct { - CandidateMbid string - TagSource string - TagSourcesVersion int32 -} - -// Stamp the enrichment outcome so the drainer skips settled candidates. -// $2 = 'musicbrainz' | 'lastfm' | 'mixed' | 'none', $3 = current version. -func (q *Queries) SetCandidateArtistTagState(ctx context.Context, arg SetCandidateArtistTagStateParams) error { - _, err := q.db.Exec(ctx, setCandidateArtistTagState, arg.CandidateMbid, arg.TagSource, arg.TagSourcesVersion) - return err -} diff --git a/internal/db/dbq/catalogue.sql.go b/internal/db/dbq/catalogue.sql.go index 018c0727..47b9d2bc 100644 --- a/internal/db/dbq/catalogue.sql.go +++ b/internal/db/dbq/catalogue.sql.go @@ -7,35 +7,8 @@ package dbq import ( "context" - - "github.com/jackc/pgx/v5/pgtype" ) -const addMBArtistReleaseGroup = `-- name: AddMBArtistReleaseGroup :exec -INSERT INTO mb_artist_release_groups (artist_mbid, release_group_mbid) -VALUES ($1, $2) -ON CONFLICT DO NOTHING -` - -type AddMBArtistReleaseGroupParams struct { - ArtistMbid string - ReleaseGroupMbid string -} - -func (q *Queries) AddMBArtistReleaseGroup(ctx context.Context, arg AddMBArtistReleaseGroupParams) error { - _, err := q.db.Exec(ctx, addMBArtistReleaseGroup, arg.ArtistMbid, arg.ReleaseGroupMbid) - return err -} - -const deleteMBArtistReleaseGroups = `-- name: DeleteMBArtistReleaseGroups :exec -DELETE FROM mb_artist_release_groups WHERE artist_mbid = $1 -` - -func (q *Queries) DeleteMBArtistReleaseGroups(ctx context.Context, artistMbid string) error { - _, err := q.db.Exec(ctx, deleteMBArtistReleaseGroups, artistMbid) - return err -} - const deleteMBReleasesForGroup = `-- name: DeleteMBReleasesForGroup :exec DELETE FROM mb_releases WHERE release_group_mbid = $1 ` @@ -46,27 +19,6 @@ func (q *Queries) DeleteMBReleasesForGroup(ctx context.Context, releaseGroupMbid return err } -const getMBArtist = `-- name: GetMBArtist :one -SELECT mbid, name, sort_name, disambiguation, artist_type, country, discography_refreshed_at, created_at, updated_at FROM mb_artists WHERE mbid = $1 -` - -func (q *Queries) GetMBArtist(ctx context.Context, mbid string) (MbArtist, error) { - row := q.db.QueryRow(ctx, getMBArtist, mbid) - var i MbArtist - err := row.Scan( - &i.Mbid, - &i.Name, - &i.SortName, - &i.Disambiguation, - &i.ArtistType, - &i.Country, - &i.DiscographyRefreshedAt, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} - const getMBReleaseGroup = `-- name: GetMBReleaseGroup :one SELECT mbid, title, primary_type, secondary_types, first_release_date, artist_credit, releases_refreshed_at, created_at, updated_at FROM mb_release_groups WHERE mbid = $1 ` @@ -165,78 +117,6 @@ func (q *Queries) InsertMBReleaseTrack(ctx context.Context, arg InsertMBReleaseT return err } -const listMBArtistReleaseGroups = `-- name: ListMBArtistReleaseGroups :many -SELECT g.mbid, g.title, g.primary_type, g.secondary_types, g.first_release_date, g.artist_credit, g.releases_refreshed_at, g.created_at, g.updated_at FROM mb_release_groups g -JOIN mb_artist_release_groups ag ON ag.release_group_mbid = g.mbid -WHERE ag.artist_mbid = $1 -ORDER BY g.first_release_date = '', g.first_release_date, g.title, g.mbid -` - -// An artist's discography, oldest first; undated groups last. -func (q *Queries) ListMBArtistReleaseGroups(ctx context.Context, artistMbid string) ([]MbReleaseGroup, error) { - rows, err := q.db.Query(ctx, listMBArtistReleaseGroups, artistMbid) - if err != nil { - return nil, err - } - defer rows.Close() - var items []MbReleaseGroup - for rows.Next() { - var i MbReleaseGroup - if err := rows.Scan( - &i.Mbid, - &i.Title, - &i.PrimaryType, - &i.SecondaryTypes, - &i.FirstReleaseDate, - &i.ArtistCredit, - &i.ReleasesRefreshedAt, - &i.CreatedAt, - &i.UpdatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listMBArtistsDueForRefresh = `-- name: ListMBArtistsDueForRefresh :many -SELECT mbid FROM mb_artists -WHERE discography_refreshed_at IS NULL OR discography_refreshed_at < $1 -ORDER BY discography_refreshed_at NULLS FIRST, mbid -LIMIT $2 -` - -type ListMBArtistsDueForRefreshParams struct { - Before pgtype.Timestamptz - MaxRows int32 -} - -// Artists whose discography has never been read, or was read before the -// cutoff: never-read first, then oldest first. -func (q *Queries) ListMBArtistsDueForRefresh(ctx context.Context, arg ListMBArtistsDueForRefreshParams) ([]string, error) { - rows, err := q.db.Query(ctx, listMBArtistsDueForRefresh, arg.Before, arg.MaxRows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []string - for rows.Next() { - var mbid string - if err := rows.Scan(&mbid); err != nil { - return nil, err - } - items = append(items, mbid) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const listMBReleaseTracksForGroup = `-- name: ListMBReleaseTracksForGroup :many SELECT t.release_mbid, t.medium_position, t.position, t.medium_format, t.number, t.title, t.length_ms, t.recording_mbid FROM mb_release_tracks t JOIN mb_releases r ON r.mbid = t.release_mbid @@ -273,53 +153,6 @@ func (q *Queries) ListMBReleaseTracksForGroup(ctx context.Context, releaseGroupM return items, nil } -const listMBReleasesForGroup = `-- name: ListMBReleasesForGroup :many -SELECT mbid, release_group_mbid, title, status, release_date, country, disambiguation, formats, track_count, created_at FROM mb_releases -WHERE release_group_mbid = $1 -ORDER BY status <> 'Official', release_date = '', release_date, title, mbid -` - -// Official editions first, then by date; undated last. -func (q *Queries) ListMBReleasesForGroup(ctx context.Context, releaseGroupMbid string) ([]MbRelease, error) { - rows, err := q.db.Query(ctx, listMBReleasesForGroup, releaseGroupMbid) - if err != nil { - return nil, err - } - defer rows.Close() - var items []MbRelease - for rows.Next() { - var i MbRelease - if err := rows.Scan( - &i.Mbid, - &i.ReleaseGroupMbid, - &i.Title, - &i.Status, - &i.ReleaseDate, - &i.Country, - &i.Disambiguation, - &i.Formats, - &i.TrackCount, - &i.CreatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const markMBArtistDiscographyRefreshed = `-- name: MarkMBArtistDiscographyRefreshed :exec -UPDATE mb_artists SET discography_refreshed_at = now() WHERE mbid = $1 -` - -func (q *Queries) MarkMBArtistDiscographyRefreshed(ctx context.Context, mbid string) error { - _, err := q.db.Exec(ctx, markMBArtistDiscographyRefreshed, mbid) - return err -} - const markMBReleaseGroupReleasesRefreshed = `-- name: MarkMBReleaseGroupReleasesRefreshed :exec UPDATE mb_release_groups SET releases_refreshed_at = now() WHERE mbid = $1 ` @@ -329,43 +162,8 @@ func (q *Queries) MarkMBReleaseGroupReleasesRefreshed(ctx context.Context, mbid return err } -const upsertMBArtist = `-- name: UpsertMBArtist :exec - -INSERT INTO mb_artists (mbid, name, sort_name, disambiguation, artist_type, country) -VALUES ($1, $2, $3, $4, - $5, $6) -ON CONFLICT (mbid) DO UPDATE SET - name = EXCLUDED.name, - sort_name = EXCLUDED.sort_name, - disambiguation = EXCLUDED.disambiguation, - artist_type = EXCLUDED.artist_type, - country = EXCLUDED.country, - updated_at = now() -` - -type UpsertMBArtistParams struct { - Mbid string - Name string - SortName string - Disambiguation string - ArtistType string - Country string -} - -// The release catalogue read from MusicBrainz. -func (q *Queries) UpsertMBArtist(ctx context.Context, arg UpsertMBArtistParams) error { - _, err := q.db.Exec(ctx, upsertMBArtist, - arg.Mbid, - arg.Name, - arg.SortName, - arg.Disambiguation, - arg.ArtistType, - arg.Country, - ) - return err -} - const upsertMBReleaseGroup = `-- name: UpsertMBReleaseGroup :exec + INSERT INTO mb_release_groups (mbid, title, primary_type, secondary_types, first_release_date, artist_credit) VALUES ($1, $2, $3, $4::text[], $5, $6) @@ -387,8 +185,9 @@ type UpsertMBReleaseGroupParams struct { ArtistCredit string } -// Leaves releases_refreshed_at alone: re-reading a discography says nothing -// about whether the group's track lists are current. +// The release catalogue read from MusicBrainz. +// Leaves releases_refreshed_at alone: only a full read of the group's +// releases and track lists marks it. func (q *Queries) UpsertMBReleaseGroup(ctx context.Context, arg UpsertMBReleaseGroupParams) error { _, err := q.db.Exec(ctx, upsertMBReleaseGroup, arg.Mbid, diff --git a/internal/db/dbq/contextual_likes.sql.go b/internal/db/dbq/contextual_likes.sql.go index 32bdb7a6..93ac12bc 100644 --- a/internal/db/dbq/contextual_likes.sql.go +++ b/internal/db/dbq/contextual_likes.sql.go @@ -34,11 +34,12 @@ func (q *Queries) InsertContextualLike(ctx context.Context, arg InsertContextual } const listActiveContextualLikesForUser = `-- name: ListActiveContextualLikesForUser :many -SELECT track_id, session_vector -FROM contextual_likes -WHERE user_id = $1 - AND deleted_at IS NULL - AND session_vector IS NOT NULL +SELECT cl.track_id, cl.session_vector +FROM contextual_likes cl +WHERE cl.user_id = $1 + AND cl.deleted_at IS NULL + AND cl.session_vector IS NOT NULL + AND EXISTS (SELECT 1 FROM general_likes g WHERE g.user_id = cl.user_id AND g.track_id = cl.track_id) ` type ListActiveContextualLikesForUserRow struct { @@ -50,6 +51,9 @@ type ListActiveContextualLikesForUserRow struct { // non-null vectors. Cardinality is bounded by the user's actual like-while- // playing history — typically tens to low hundreds. Used by the engine to // compute contextual_match_score for the candidate pool. +// +// Only rows whose song is still liked count, so a context left active by +// an unlike that missed it can't keep boosting a song the user let go of. func (q *Queries) ListActiveContextualLikesForUser(ctx context.Context, userID pgtype.UUID) ([]ListActiveContextualLikesForUserRow, error) { rows, err := q.db.Query(ctx, listActiveContextualLikesForUser, userID) if err != nil { @@ -73,7 +77,11 @@ func (q *Queries) ListActiveContextualLikesForUser(ctx context.Context, userID p const softDeleteContextualLikesForUserTrack = `-- name: SoftDeleteContextualLikesForUserTrack :exec UPDATE contextual_likes SET deleted_at = now() -WHERE user_id = $1 AND track_id = $2 AND deleted_at IS NULL +WHERE user_id = $1::uuid + AND deleted_at IS NULL + AND (track_id = $2::uuid + OR track_id IN (SELECT t.id FROM tracks t + WHERE t.song_key = (SELECT s.song_key FROM tracks s WHERE s.id = $2::uuid))) ` type SoftDeleteContextualLikesForUserTrackParams struct { @@ -81,8 +89,11 @@ type SoftDeleteContextualLikesForUserTrackParams struct { TrackID pgtype.UUID } -// Marks all currently-active rows for (user, track) as deleted. Idempotent — -// already-deleted rows aren't re-touched. +// Marks the user's active rows for the song as deleted: every copy sharing +// the track's song_key, as UnlikeTrack removes the like from every copy. +// The context was captured on whichever copy was playing, which needn't be +// the one the unlike names. Idempotent — already-deleted rows aren't +// re-touched. func (q *Queries) SoftDeleteContextualLikesForUserTrack(ctx context.Context, arg SoftDeleteContextualLikesForUserTrackParams) error { _, err := q.db.Exec(ctx, softDeleteContextualLikesForUserTrack, arg.UserID, arg.TrackID) return err diff --git a/internal/db/dbq/covers.sql.go b/internal/db/dbq/covers.sql.go index ee99d700..e8af0c0a 100644 --- a/internal/db/dbq/covers.sql.go +++ b/internal/db/dbq/covers.sql.go @@ -39,39 +39,6 @@ func (q *Queries) ClearAlbumCoverNone(ctx context.Context, id pgtype.UUID) error return err } -const countAlbumCoverSources = `-- name: CountAlbumCoverSources :one -SELECT - COUNT(*) FILTER (WHERE cover_art_source IS NULL) ::bigint AS untried, - COUNT(*) FILTER (WHERE cover_art_source = 'sidecar') ::bigint AS sidecar, - COUNT(*) FILTER (WHERE cover_art_source = 'embedded')::bigint AS embedded, - COUNT(*) FILTER (WHERE cover_art_source = 'mbcaa') ::bigint AS mbcaa, - COUNT(*) FILTER (WHERE cover_art_source = 'none') ::bigint AS none - FROM albums -` - -type CountAlbumCoverSourcesRow struct { - Untried int64 - Sidecar int64 - Embedded int64 - Mbcaa int64 - None int64 -} - -// Diagnostic for the admin overview: counts by source, including NULL. -// Returns one row with named tallies. -func (q *Queries) CountAlbumCoverSources(ctx context.Context) (CountAlbumCoverSourcesRow, error) { - row := q.db.QueryRow(ctx, countAlbumCoverSources) - var i CountAlbumCoverSourcesRow - err := row.Scan( - &i.Untried, - &i.Sidecar, - &i.Embedded, - &i.Mbcaa, - &i.None, - ) - return i, err -} - const getAlbumWithFirstTrackPath = `-- name: GetAlbumWithFirstTrackPath :one SELECT a.id, a.mbid, a.title, a.cover_art_path, a.cover_art_source, ar.name AS artist_name, diff --git a/internal/db/dbq/duplicates.sql.go b/internal/db/dbq/duplicates.sql.go index bed92a34..a7f0b603 100644 --- a/internal/db/dbq/duplicates.sql.go +++ b/internal/db/dbq/duplicates.sql.go @@ -27,23 +27,6 @@ func (q *Queries) AddDuplicateGroupMember(ctx context.Context, arg AddDuplicateG return err } -const countPendingDuplicateGroups = `-- name: CountPendingDuplicateGroups :one -SELECT count(*)::bigint - FROM duplicate_groups g - WHERE g.status = 'pending' - AND (SELECT count(*) FROM duplicate_group_members m WHERE m.group_id = g.id) >= 2 -` - -// Proposals awaiting review. A group left with one member — its other tracks -// deleted since the sweep — is no proposal at all and is not counted; the next -// sweep retires it. -func (q *Queries) CountPendingDuplicateGroups(ctx context.Context) (int64, error) { - row := q.db.QueryRow(ctx, countPendingDuplicateGroups) - var column_1 int64 - err := row.Scan(&column_1) - return column_1, err -} - const countPendingDuplicateGroupsInView = `-- name: CountPendingDuplicateGroupsInView :one SELECT count(*)::bigint FROM duplicate_groups g @@ -316,7 +299,7 @@ SELECT g.id AS group_id, AND t.track_number IS NOT NULL AND o.disc_number IS NOT DISTINCT FROM t.disc_number AND o.track_number = t.track_number)::boolean AS position_clash, - COALESCE(NULLIF(al.release_group_mbid, ''), lam.release_group_mbid, '')::text AS release_group_mbid, + COALESCE(al.release_group_mbid, '')::text AS release_group_mbid, l.state AS acoustid_state, l.recording_mbid AS acoustid_recording FROM duplicate_groups g @@ -324,7 +307,6 @@ SELECT g.id AS group_id, JOIN tracks t ON t.id = m.track_id JOIN artists ON artists.id = t.artist_id JOIN albums al ON al.id = t.album_id - LEFT JOIN library_album_matches lam ON lam.album_id = t.album_id AND lam.outcome = 'listed' LEFT JOIN track_acoustid_lookups l ON l.track_id = t.id WHERE g.status = 'pending' AND t.missing_since IS NULL diff --git a/internal/db/dbq/events.sql.go b/internal/db/dbq/events.sql.go index 5b1ba57a..1f1e9796 100644 --- a/internal/db/dbq/events.sql.go +++ b/internal/db/dbq/events.sql.go @@ -261,7 +261,7 @@ func (q *Queries) InsertSkipEvent(ctx context.Context, arg InsertSkipEventParams } const listRecentSessionTracks = `-- name: ListRecentSessionTracks :many -SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at FROM tracks t +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit FROM tracks t JOIN play_events pe ON pe.track_id = t.id WHERE pe.session_id = $1 AND pe.started_at < $2 @@ -313,6 +313,9 @@ func (q *Queries) ListRecentSessionTracks(ctx context.Context, arg ListRecentSes &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, ); err != nil { return nil, err } diff --git a/internal/db/dbq/fingerprint_settings.sql.go b/internal/db/dbq/fingerprint_settings.sql.go index 62086971..4697384a 100644 --- a/internal/db/dbq/fingerprint_settings.sql.go +++ b/internal/db/dbq/fingerprint_settings.sql.go @@ -51,7 +51,7 @@ type UpdateFingerprintSettingsParams struct { AutoResolve bool } -// Whole-row write from the admin card; migration 0061's CHECKs are the backstop +// Whole-row write from the admin card; fingerprint_settings's CHECKs are the backstop // behind the service's own validation. func (q *Queries) UpdateFingerprintSettings(ctx context.Context, arg UpdateFingerprintSettingsParams) (FingerprintSetting, error) { row := q.db.QueryRow(ctx, updateFingerprintSettings, diff --git a/internal/db/dbq/genre_mixes.sql.go b/internal/db/dbq/genre_mixes.sql.go new file mode 100644 index 00000000..23b120c5 --- /dev/null +++ b/internal/db/dbq/genre_mixes.sql.go @@ -0,0 +1,286 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: genre_mixes.sql + +package dbq + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const listGenreMixCandidates = `-- name: ListGenreMixCandidates :many + +WITH library_genres AS ( + SELECT lower(trim(g.g)) AS genre_key, + min(trim(g.g))::text AS label, + COUNT(DISTINCT t.id) AS track_count, + array_agg(DISTINCT t.id)::uuid[] AS track_ids + FROM tracks t + CROSS JOIN LATERAL regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE t.missing_since IS NULL + AND trim(g.g) <> '' + GROUP BY lower(trim(g.g)) + HAVING COUNT(DISTINCT t.id) >= 25 + AND COUNT(DISTINCT t.artist_id) >= 3 +), +taste AS ( + SELECT lower(trim(tpt.tag)) AS genre_key, SUM(tpt.weight) AS weight + FROM taste_profile_tags tpt + WHERE tpt.user_id = $1 + GROUP BY lower(trim(tpt.tag)) + HAVING SUM(tpt.weight) > 0 +), +listened AS ( + SELECT t.id + FROM play_events pe + JOIN tracks t ON t.id = pe.track_id + WHERE pe.user_id = $1 AND pe.was_skipped = false + UNION ALL + SELECT gl.track_id + FROM general_likes gl + WHERE gl.user_id = $1 +), +history AS ( + SELECT lower(trim(g.g)) AS genre_key, COUNT(*) AS plays + FROM listened l + JOIN tracks t ON t.id = l.id + CROSS JOIN LATERAL regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE trim(g.g) <> '' + GROUP BY lower(trim(g.g)) +) +SELECT lg.genre_key::text AS genre_key, + lg.label AS label, + (CASE WHEN ta.genre_key IS NOT NULL THEN 1 + WHEN h.genre_key IS NOT NULL THEN 2 + ELSE 3 END)::int AS tier, + (CASE WHEN ta.genre_key IS NOT NULL THEN ta.weight + WHEN h.genre_key IS NOT NULL THEN h.plays::float8 + ELSE lg.track_count::float8 END)::float8 AS score, + lg.track_ids + FROM library_genres lg + LEFT JOIN taste ta ON ta.genre_key = lg.genre_key + LEFT JOIN history h ON h.genre_key = lg.genre_key + ORDER BY tier, score DESC, lg.genre_key + LIMIT 60 +` + +type ListGenreMixCandidatesRow struct { + GenreKey string + Label string + Tier int32 + Score float64 + TrackIds []pgtype.UUID +} + +// Candidate queries for the genre mixes: one daily system playlist per genre +// the user listens to. Genres live inline on tracks.genre as a delimited +// string and are split on [;,] the same way the Discover and radio tag arms +// split them. Matching is case-insensitive, so the ID3 "Post-Punk" and the +// folksonomy "post-punk" in the taste profile count as one genre. +// Library genres big enough to carry a mix (>= 25 playable tracks across +// >= 3 artists), each tagged with how close it is to the user's listening: +// +// tier 1: a positive taste-profile genre, scored by its taste weight +// tier 2: a genre of tracks the user has played through or liked, scored +// by how many — catches a profile that has not been built yet or +// has decayed past its window +// tier 3: any other library genre, scored by its size +// +// track_ids lets the caller tell how much music two genres share: a genre +// whose songs mostly sit in genres already picked adds no new channel, and a +// broad genre ("Rock") whose songs mostly carry narrower ones ("Pop Punk", +// "Ska Punk") gives way to them. +// $1 user_id. +func (q *Queries) ListGenreMixCandidates(ctx context.Context, userID pgtype.UUID) ([]ListGenreMixCandidatesRow, error) { + rows, err := q.db.Query(ctx, listGenreMixCandidates, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListGenreMixCandidatesRow + for rows.Next() { + var i ListGenreMixCandidatesRow + if err := rows.Scan( + &i.GenreKey, + &i.Label, + &i.Tier, + &i.Score, + &i.TrackIds, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listGenreMixTracks = `-- name: ListGenreMixTracks :many +WITH play_counts AS ( + SELECT pe.track_id, COUNT(*) AS c + FROM play_events pe + WHERE pe.user_id = $1 AND pe.was_skipped = false + GROUP BY pe.track_id +), +skip_counts AS ( + SELECT pe.track_id, COUNT(*) AS c + FROM play_events pe + WHERE pe.user_id = $1 AND pe.was_skipped = true + GROUP BY pe.track_id +), +artist_plays AS ( + SELECT t.artist_id, + COUNT(*) FILTER (WHERE NOT pe.was_skipped) AS plays, + COUNT(*) FILTER (WHERE pe.was_skipped) AS skips + FROM play_events pe + JOIN tracks t ON t.id = pe.track_id + WHERE pe.user_id = $1 + GROUP BY t.artist_id +), +artist_likes AS ( + SELECT t.artist_id, COUNT(*) AS likes + FROM general_likes gl + JOIN tracks t ON t.id = gl.track_id + WHERE gl.user_id = $1 + GROUP BY t.artist_id +), +own_artists AS ( + SELECT ap.artist_id FROM artist_plays ap WHERE ap.plays > 0 + UNION + SELECT al.artist_id FROM artist_likes al +), +artist_sim AS ( + SELECT asim.artist_b_id AS artist_id, + MAX(LEAST(GREATEST(asim.score, 0), 1)) AS sim + FROM artist_similarity asim + JOIN own_artists oa ON oa.artist_id = asim.artist_a_id + GROUP BY asim.artist_b_id +), +eligible AS ( + SELECT t.id, t.album_id, t.artist_id, + (COALESCE(pc.c, 0) > 0 OR gl.track_id IS NOT NULL) AS familiar, + CASE + WHEN COALESCE(pc.c, 0) > 0 OR gl.track_id IS NOT NULL THEN + (1 + ln(1 + COALESCE(pc.c, 0)::float8) + + CASE WHEN gl.track_id IS NOT NULL THEN 1 ELSE 0 END) + * ((COALESCE(pc.c, 0) + 1)::float8 / (COALESCE(pc.c, 0) + COALESCE(sc.c, 0) + 1)) + ELSE + (1 + ln(1 + COALESCE(ap.plays, 0)::float8 + 2 * COALESCE(al.likes, 0)::float8) + + 2 * COALESCE(asm.sim, 0)) + * ((COALESCE(ap.plays, 0) + 1)::float8 / (COALESCE(ap.plays, 0) + COALESCE(ap.skips, 0) + 1)) + END::float8 AS weight, + -- u in (0, 1): the first 32 bits of md5(track, date), shifted off 0. + ((('x' || substr(md5(t.id::text || $2::text), 1, 8))::bit(32)::bigint)::float8 + 1) + / 4294967297.0 AS u + FROM tracks t + LEFT JOIN play_counts pc ON pc.track_id = t.id + LEFT JOIN skip_counts sc ON sc.track_id = t.id + LEFT JOIN general_likes gl ON gl.user_id = $1 AND gl.track_id = t.id + LEFT JOIN artist_plays ap ON ap.artist_id = t.artist_id + LEFT JOIN artist_likes al ON al.artist_id = t.artist_id + LEFT JOIN artist_sim asm ON asm.artist_id = t.artist_id + WHERE t.missing_since IS NULL -- never offer a file that is gone + AND NOT (COALESCE(sc.c, 0) >= 2 AND COALESCE(sc.c, 0) > COALESCE(pc.c, 0)) + AND EXISTS ( + SELECT 1 + FROM regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE lower(trim(g.g)) = $3::text + ) + AND NOT EXISTS ( + SELECT 1 + FROM regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE lower(trim(g.g)) = ANY($4::text[]) + ) + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = $1 AND q.track_id = t.id + ) +), +ranked AS ( + SELECT e.id, e.album_id, e.artist_id, e.familiar, + -ln(e.u) / e.weight AS draw, + row_number() OVER (PARTITION BY e.familiar ORDER BY -ln(e.u) / e.weight, e.id) AS rn + FROM eligible e +) +SELECT r.id, r.album_id, r.artist_id, r.familiar::bool AS familiar + FROM ranked r + WHERE r.rn <= 200 + ORDER BY r.familiar DESC, r.draw, r.id +` + +type ListGenreMixTracksParams struct { + UserID pgtype.UUID + DateSeed string + GenreKey string + ExcludeGenres []string +} + +type ListGenreMixTracksRow struct { + ID pgtype.UUID + AlbumID pgtype.UUID + ArtistID pgtype.UUID + Familiar bool +} + +// Playable tracks carrying one genre, split into the two halves a genre mix +// blends: familiar (the user has played it through or liked it) and unheard. +// Up to 200 of each, drawn by a weighted lottery seeded with the date, so the +// mix changes day to day, holds still within a day, and leans toward what the +// user likes without becoming the same 50 songs every day. +// +// The lottery is the Efraimidis-Spirakis draw: each track gets +// -ln(u) / weight with u uniform in (0, 1) from md5(track, date), and the +// smallest keys win. A track of weight 3 is three times as likely as one of +// weight 1 to come before it, and every track keeps some chance. +// +// Familiar weight: 1 + ln(1 + plays through) + 1 if liked, times the share of +// its plays that were not skips. A song played 40 times weighs about 4.7, one +// played once about 1.7. +// +// Unheard weight: 1 + ln(1 + the artist's plays through + 2 × its liked +// tracks) + 2 × how similar the artist is to the user's own artists (the best +// artist_similarity score from any artist they have played through or liked, +// 0 to 1), times the share of the artist's plays that were not skips. An +// artist the user has never met weighs 1, so new artists still come up; an +// artist they keep skipping weighs well under 1. +// +// A track the user keeps skipping stays out: twice-skipped and skipped more +// often than played through. The second half of that test keeps a favourite +// with a couple of stray skips in. +// +// exclude_genres keeps each song in one mix: a track carrying a genre that +// already has a mix today is left to that mix. +func (q *Queries) ListGenreMixTracks(ctx context.Context, arg ListGenreMixTracksParams) ([]ListGenreMixTracksRow, error) { + rows, err := q.db.Query(ctx, listGenreMixTracks, + arg.UserID, + arg.DateSeed, + arg.GenreKey, + arg.ExcludeGenres, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListGenreMixTracksRow + for rows.Next() { + var i ListGenreMixTracksRow + if err := rows.Scan( + &i.ID, + &i.AlbumID, + &i.ArtistID, + &i.Familiar, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/dbq/history.sql.go b/internal/db/dbq/history.sql.go index 4edbbed0..3edf12fb 100644 --- a/internal/db/dbq/history.sql.go +++ b/internal/db/dbq/history.sql.go @@ -14,7 +14,7 @@ import ( const listUserHistory = `-- name: ListUserHistory :many SELECT pe.id AS event_id, pe.started_at, - t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, + t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit, albums.title AS album_title, artists.name AS artist_name FROM play_events pe @@ -87,6 +87,9 @@ func (q *Queries) ListUserHistory(ctx context.Context, arg ListUserHistoryParams &i.Track.SourceVerdict, &i.Track.SourceVerdictAt, &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, &i.AlbumTitle, &i.ArtistName, ); err != nil { diff --git a/internal/db/dbq/imports.sql.go b/internal/db/dbq/imports.sql.go deleted file mode 100644 index b7ce6aec..00000000 --- a/internal/db/dbq/imports.sql.go +++ /dev/null @@ -1,902 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: imports.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const claimGrabImport = `-- name: ClaimGrabImport :one -UPDATE grabs - SET import_state = 'importing', import_attempts = import_attempts + 1, - import_updated_at = now(), progress = 1 - WHERE id = $1 AND ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting') -RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at -` - -// Takes a finished download for import. The update is the lock: a second -// pass finds nothing to claim. -func (q *Queries) ClaimGrabImport(ctx context.Context, id pgtype.UUID) (Grab, error) { - row := q.db.QueryRow(ctx, claimGrabImport, id) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const clearTrackSourceVerdict = `-- name: ClearTrackSourceVerdict :exec -UPDATE tracks SET source_verdict = NULL, source_verdict_at = NULL - WHERE id = $1 AND source_verdict = 'suspect' -` - -// A track whose file was replaced in place is no longer the rip it was. -func (q *Queries) ClearTrackSourceVerdict(ctx context.Context, id pgtype.UUID) error { - _, err := q.db.Exec(ctx, clearTrackSourceVerdict, id) - return err -} - -const finishUpgrade = `-- name: FinishUpgrade :exec -UPDATE wants - SET album_id = COALESCE($1, album_id), - upgrade = '', - upgrade_checked_at = NULL, - updated_at = now() - WHERE id = $2 -` - -type FinishUpgradeParams struct { - AlbumID pgtype.UUID - ID pgtype.UUID -} - -// An upgrade was imported: the want holds the album the new tracks are in, -// and is judged again by the next upgrade check. -func (q *Queries) FinishUpgrade(ctx context.Context, arg FinishUpgradeParams) error { - _, err := q.db.Exec(ctx, finishUpgrade, arg.AlbumID, arg.ID) - return err -} - -const forceGrabImport = `-- name: ForceGrabImport :one -UPDATE grabs - SET import_state = '', import_forced = true, import_reason = '', import_updated_at = now() - WHERE id = $1 AND ended_at IS NULL AND import_state IN ('review', 'failed') -RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at -` - -// "Import anyway": the next pass imports the download whatever the check said. -func (q *Queries) ForceGrabImport(ctx context.Context, id pgtype.UUID) (Grab, error) { - row := q.db.QueryRow(ctx, forceGrabImport, id) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const getGrab = `-- name: GetGrab :one -SELECT id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at FROM grabs WHERE id = $1 -` - -func (q *Queries) GetGrab(ctx context.Context, id pgtype.UUID) (Grab, error) { - row := q.db.QueryRow(ctx, getGrab, id) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const heldPositions = `-- name: HeldPositions :many -SELECT DISTINCT COALESCE(t.disc_number, 1)::int AS disc, t.track_number::int AS track - FROM tracks t - JOIN albums a ON a.id = t.album_id - WHERE a.release_group_mbid = $1 - AND t.missing_since IS NULL AND t.track_number IS NOT NULL -` - -type HeldPositionsRow struct { - Disc int32 - Track int32 -} - -// The disc and track positions the library holds for an album of this group. -func (q *Queries) HeldPositions(ctx context.Context, releaseGroupMbid *string) ([]HeldPositionsRow, error) { - rows, err := q.db.Query(ctx, heldPositions, releaseGroupMbid) - if err != nil { - return nil, err - } - defer rows.Close() - var items []HeldPositionsRow - for rows.Next() { - var i HeldPositionsRow - if err := rows.Scan(&i.Disc, &i.Track); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const heldRecordings = `-- name: HeldRecordings :many -SELECT DISTINCT mbid::text AS mbid FROM tracks - WHERE mbid = ANY($1::text[]) AND missing_since IS NULL -` - -// Which of these recordings the library holds a file for. -func (q *Queries) HeldRecordings(ctx context.Context, recordings []string) ([]string, error) { - rows, err := q.db.Query(ctx, heldRecordings, recordings) - if err != nil { - return nil, err - } - defer rows.Close() - var items []string - for rows.Next() { - var mbid string - if err := rows.Scan(&mbid); err != nil { - return nil, err - } - items = append(items, mbid) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listGrabs = `-- name: ListGrabs :many -SELECT g.id, g.want_id, g.name, g.indexer, g.client, g.quality, g.origin, g.forced, - g.grabbed_at, g.ended_at, g.end_reason, g.end_detail, g.progress, g.import_state, - g.import_reason, g.import_detail, g.import_updated_at, g.imported_at, g.imported_files, - g.destination, g.seeding, g.ratio, g.seed_released_at, - w.title AS want_title, w.artist_name AS want_artist, - di.trigger AS condition, di.detail AS condition_detail, di.remediations AS condition_retries, - di.first_seen AS condition_since - FROM grabs g - LEFT JOIN wants w ON w.id = g.want_id - LEFT JOIN download_interventions di - ON di.id = (SELECT x.id FROM download_interventions x - WHERE x.grab_id = g.id AND x.outcome = 'open' - ORDER BY x.last_seen DESC LIMIT 1) - ORDER BY (g.ended_at IS NULL AND g.import_state IN ('review', 'failed')) DESC, - g.ended_at IS NULL DESC, g.grabbed_at DESC, g.id - LIMIT $2 OFFSET $1 -` - -type ListGrabsParams struct { - Skip int32 - MaxRows int32 -} - -type ListGrabsRow struct { - ID pgtype.UUID - WantID pgtype.UUID - Name string - Indexer string - Client string - Quality string - Origin string - Forced bool - GrabbedAt pgtype.Timestamptz - EndedAt pgtype.Timestamptz - EndReason string - EndDetail string - Progress float32 - ImportState string - ImportReason string - ImportDetail []byte - ImportUpdatedAt pgtype.Timestamptz - ImportedAt pgtype.Timestamptz - ImportedFiles int32 - Destination string - Seeding bool - Ratio float32 - SeedReleasedAt pgtype.Timestamptz - WantTitle *string - WantArtist *string - Condition *string - ConditionDetail *string - ConditionRetries *int32 - ConditionSince pgtype.Timestamptz -} - -// The Wanted view's Activity tab: downloads waiting on a person first, then -// the rest still running, then the ended ones newest first. Each carries -// what is wrong with it now, if anything. -func (q *Queries) ListGrabs(ctx context.Context, arg ListGrabsParams) ([]ListGrabsRow, error) { - rows, err := q.db.Query(ctx, listGrabs, arg.Skip, arg.MaxRows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListGrabsRow - for rows.Next() { - var i ListGrabsRow - if err := rows.Scan( - &i.ID, - &i.WantID, - &i.Name, - &i.Indexer, - &i.Client, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - &i.WantTitle, - &i.WantArtist, - &i.Condition, - &i.ConditionDetail, - &i.ConditionRetries, - &i.ConditionSince, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listImportedGrabsHolding = `-- name: ListImportedGrabsHolding :many -SELECT id, info_hash, name, want_id - FROM grabs - WHERE import_state = 'imported' - AND info_hash <> '' - AND destination <> '' - AND starts_with($1::text, rtrim(destination, '/') || '/') -` - -type ListImportedGrabsHoldingRow struct { - ID pgtype.UUID - InfoHash string - Name string - WantID pgtype.UUID -} - -// The downloads Minstrel imported into the folder holding path: the releases a -// file there came from, to block when the files proved not to be the album -// . A file imported before Minstrel downloaded anything has none. -func (q *Queries) ListImportedGrabsHolding(ctx context.Context, path string) ([]ListImportedGrabsHoldingRow, error) { - rows, err := q.db.Query(ctx, listImportedGrabsHolding, path) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListImportedGrabsHoldingRow - for rows.Next() { - var i ListImportedGrabsHoldingRow - if err := rows.Scan( - &i.ID, - &i.InfoHash, - &i.Name, - &i.WantID, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listLiveGrabs = `-- name: ListLiveGrabs :many - -SELECT g.id, g.want_id, g.info_hash, g.name, g.key, g.indexer, g.source, g.client, g.save_path, g.quality, g.origin, g.forced, g.grabbed_by, g.grabbed_at, g.ended_at, g.end_reason, g.end_detail, g.progress, g.import_state, g.import_reason, g.import_detail, g.import_forced, g.import_attempts, g.import_updated_at, g.imported_at, g.imported_files, g.destination, g.seeding, g.ratio, g.seed_released_at, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title AS want_title, - w.reason AS want_reason, w.album_id AS want_album_id - FROM grabs g - LEFT JOIN wants w ON w.id = g.want_id - WHERE g.ended_at IS NULL - ORDER BY g.grabbed_at, g.id -` - -type ListLiveGrabsRow struct { - ID pgtype.UUID - WantID pgtype.UUID - InfoHash string - Name string - Key string - Indexer string - Source string - Client string - SavePath string - Quality string - Origin string - Forced bool - GrabbedBy pgtype.UUID - GrabbedAt pgtype.Timestamptz - EndedAt pgtype.Timestamptz - EndReason string - EndDetail string - Progress float32 - ImportState string - ImportReason string - ImportDetail []byte - ImportForced bool - ImportAttempts int32 - ImportUpdatedAt pgtype.Timestamptz - ImportedAt pgtype.Timestamptz - ImportedFiles int32 - Destination string - Seeding bool - Ratio float32 - SeedReleasedAt pgtype.Timestamptz - ReleaseGroupMbid *string - ArtistMbid *string - ArtistName *string - WantTitle *string - WantReason *string - WantAlbumID pgtype.UUID -} - -// Import with verification. -// Every download still running or waiting on its import, oldest first. -func (q *Queries) ListLiveGrabs(ctx context.Context) ([]ListLiveGrabsRow, error) { - rows, err := q.db.Query(ctx, listLiveGrabs) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListLiveGrabsRow - for rows.Next() { - var i ListLiveGrabsRow - if err := rows.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.WantTitle, - &i.WantReason, - &i.WantAlbumID, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listReleaseBlocksPage = `-- name: ListReleaseBlocksPage :many -SELECT b.info_hash, b.name, b.reason, b.detail, b.blocked_at, b.expires_at, w.title AS want_title, - w.artist_name AS want_artist - FROM release_blocks b - LEFT JOIN wants w ON w.id = b.want_id - WHERE b.expires_at IS NULL OR b.expires_at > now() - ORDER BY b.blocked_at DESC, b.info_hash - LIMIT $2 OFFSET $1 -` - -type ListReleaseBlocksPageParams struct { - Skip int32 - MaxRows int32 -} - -type ListReleaseBlocksPageRow struct { - InfoHash string - Name string - Reason string - Detail string - BlockedAt pgtype.Timestamptz - ExpiresAt pgtype.Timestamptz - WantTitle *string - WantArtist *string -} - -func (q *Queries) ListReleaseBlocksPage(ctx context.Context, arg ListReleaseBlocksPageParams) ([]ListReleaseBlocksPageRow, error) { - rows, err := q.db.Query(ctx, listReleaseBlocksPage, arg.Skip, arg.MaxRows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListReleaseBlocksPageRow - for rows.Next() { - var i ListReleaseBlocksPageRow - if err := rows.Scan( - &i.InfoHash, - &i.Name, - &i.Reason, - &i.Detail, - &i.BlockedAt, - &i.ExpiresAt, - &i.WantTitle, - &i.WantArtist, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listUpgradeTracks = `-- name: ListUpgradeTracks :many -SELECT id, file_path, mbid, COALESCE(disc_number, 1)::int AS disc, track_number, - file_format, file_size, duration_ms, source_verdict - FROM tracks - WHERE album_id = $1 AND missing_since IS NULL -` - -type ListUpgradeTracksRow struct { - ID pgtype.UUID - FilePath string - Mbid *string - Disc int32 - TrackNumber *int32 - FileFormat string - FileSize int64 - DurationMs int32 - SourceVerdict *string -} - -// The tracks an upgrade may replace: the present tracks of the album -// the want holds. -func (q *Queries) ListUpgradeTracks(ctx context.Context, albumID pgtype.UUID) ([]ListUpgradeTracksRow, error) { - rows, err := q.db.Query(ctx, listUpgradeTracks, albumID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListUpgradeTracksRow - for rows.Next() { - var i ListUpgradeTracksRow - if err := rows.Scan( - &i.ID, - &i.FilePath, - &i.Mbid, - &i.Disc, - &i.TrackNumber, - &i.FileFormat, - &i.FileSize, - &i.DurationMs, - &i.SourceVerdict, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const markWantSearched = `-- name: MarkWantSearched :exec -UPDATE wants SET searched_at = now() WHERE id = $1 -` - -// Imported: nothing to search for until the wanted pass settles the want. -func (q *Queries) MarkWantSearched(ctx context.Context, id pgtype.UUID) error { - _, err := q.db.Exec(ctx, markWantSearched, id) - return err -} - -const openWantsForGroups = `-- name: OpenWantsForGroups :many -SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.primary_type, w.first_release_date, w.reason, w.album_id, w.created_by, w.wanted_at, w.fulfilled_at, w.created_at, w.updated_at, w.searched_at, w.search_outcome, w.search_considered, w.best_release, w.best_verdict, w.search_error, w.upgrade, w.held_tier, w.held_quality, w.upgrade_checked_at FROM wants w - WHERE w.fulfilled_at IS NULL AND w.release_group_mbid = ANY($1::text[]) - AND NOT EXISTS (SELECT 1 FROM grabs g WHERE g.want_id = w.id AND g.ended_at IS NULL) -` - -// Open wants for these release groups with no download running. -func (q *Queries) OpenWantsForGroups(ctx context.Context, groups []string) ([]Want, error) { - rows, err := q.db.Query(ctx, openWantsForGroups, groups) - if err != nil { - return nil, err - } - defer rows.Close() - var items []Want - for rows.Next() { - var i Want - if err := rows.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.Title, - &i.PrimaryType, - &i.FirstReleaseDate, - &i.Reason, - &i.AlbumID, - &i.CreatedBy, - &i.WantedAt, - &i.FulfilledAt, - &i.CreatedAt, - &i.UpdatedAt, - &i.SearchedAt, - &i.SearchOutcome, - &i.SearchConsidered, - &i.BestRelease, - &i.BestVerdict, - &i.SearchError, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.UpgradeCheckedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const reclaimStaleImports = `-- name: ReclaimStaleImports :execrows -UPDATE grabs - SET import_state = 'waiting', - import_reason = 'The last import was cut short, so it is being tried again.' - WHERE ended_at IS NULL AND import_state = 'importing' - AND import_updated_at < now() - make_interval(mins => $1::int) -` - -// An import cut short (a restart mid-copy) is tried again. -func (q *Queries) ReclaimStaleImports(ctx context.Context, minutes int32) (int64, error) { - result, err := q.db.Exec(ctx, reclaimStaleImports, minutes) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const recordImport = `-- name: RecordImport :one -UPDATE grabs - SET import_state = $1, - import_reason = $2, - import_detail = $3, - import_updated_at = now(), - import_forced = false, - imported_at = CASE WHEN $1::text = 'imported' THEN now() ELSE imported_at END, - -- The files were copied, so an imported download goes on sharing - -- until the lifecycle removes it. - seeding = $1::text = 'imported', - imported_files = $4, - destination = $5, - ended_at = CASE WHEN $6::text <> '' THEN now() ELSE ended_at END, - end_reason = $6, - end_detail = CASE WHEN $6::text <> '' THEN $2::text ELSE end_detail END - WHERE id = $7 -RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at -` - -type RecordImportParams struct { - ImportState string - ImportReason string - ImportDetail []byte - ImportedFiles int32 - Destination string - EndReason string - ID pgtype.UUID -} - -// The import's outcome. An end reason ends the grab: imported, refused or -// held. Without one the grab stays live: review and failed wait for a person. -func (q *Queries) RecordImport(ctx context.Context, arg RecordImportParams) (Grab, error) { - row := q.db.QueryRow(ctx, recordImport, - arg.ImportState, - arg.ImportReason, - arg.ImportDetail, - arg.ImportedFiles, - arg.Destination, - arg.EndReason, - arg.ID, - ) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const rehomeGrab = `-- name: RehomeGrab :one -UPDATE grabs g - SET want_id = $1 - WHERE g.id = $2 AND g.ended_at IS NULL - AND NOT EXISTS (SELECT 1 FROM grabs o WHERE o.want_id = $1 AND o.ended_at IS NULL) -RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at -` - -type RehomeGrabParams struct { - WantID pgtype.UUID - ID pgtype.UUID -} - -// A download that turned out to be another wanted album is that want's grab, -// when the want has none running. -func (q *Queries) RehomeGrab(ctx context.Context, arg RehomeGrabParams) (Grab, error) { - row := q.db.QueryRow(ctx, rehomeGrab, arg.WantID, arg.ID) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const retryGrabImport = `-- name: RetryGrabImport :one -UPDATE grabs - SET import_state = '', import_reason = '', import_updated_at = now() - WHERE id = $1 AND ended_at IS NULL AND import_state = 'failed' -RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at -` - -func (q *Queries) RetryGrabImport(ctx context.Context, id pgtype.UUID) (Grab, error) { - row := q.db.QueryRow(ctx, retryGrabImport, id) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const searchWantAgain = `-- name: SearchWantAgain :exec -UPDATE wants SET searched_at = NULL, search_outcome = '' WHERE id = $1 -` - -// Refused: search again on the next pass. -func (q *Queries) SearchWantAgain(ctx context.Context, id pgtype.UUID) error { - _, err := q.db.Exec(ctx, searchWantAgain, id) - return err -} - -const setGrabProgress = `-- name: SetGrabProgress :exec -UPDATE grabs - SET progress = $1, - import_state = $2, - import_reason = $3, - import_updated_at = now() - WHERE id = $4 AND ended_at IS NULL - AND import_state IN ('', 'downloading', 'waiting') -` - -type SetGrabProgressParams struct { - Progress float32 - ImportState string - ImportReason string - ID pgtype.UUID -} - -// What the download client says of a download not yet finished, or finished -// and waiting for what the import needs. Leaves a claimed, decided or failed -// import alone. -func (q *Queries) SetGrabProgress(ctx context.Context, arg SetGrabProgressParams) error { - _, err := q.db.Exec(ctx, setGrabProgress, - arg.Progress, - arg.ImportState, - arg.ImportReason, - arg.ID, - ) - return err -} diff --git a/internal/db/dbq/invites.sql.go b/internal/db/dbq/invites.sql.go index 9f9b9a2d..697977cf 100644 --- a/internal/db/dbq/invites.sql.go +++ b/internal/db/dbq/invites.sql.go @@ -109,42 +109,6 @@ func (q *Queries) ListInvitesActive(ctx context.Context) ([]UserInvite, error) { return items, nil } -const listInvitesAll = `-- name: ListInvitesAll :many -SELECT token, invited_by, note, created_at, expires_at, redeemed_at, redeemed_by FROM user_invites - ORDER BY created_at DESC - LIMIT $1 -` - -// Includes redeemed + expired for full audit visibility. Caller -// supplies a LIMIT to bound the response. -func (q *Queries) ListInvitesAll(ctx context.Context, limit int32) ([]UserInvite, error) { - rows, err := q.db.Query(ctx, listInvitesAll, limit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []UserInvite - for rows.Next() { - var i UserInvite - if err := rows.Scan( - &i.Token, - &i.InvitedBy, - &i.Note, - &i.CreatedAt, - &i.ExpiresAt, - &i.RedeemedAt, - &i.RedeemedBy, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const redeemInvite = `-- name: RedeemInvite :execrows UPDATE user_invites SET redeemed_at = now(), redeemed_by = $2 diff --git a/internal/db/dbq/library_changes.sql.go b/internal/db/dbq/library_changes.sql.go index 1d38222d..b78b26d0 100644 --- a/internal/db/dbq/library_changes.sql.go +++ b/internal/db/dbq/library_changes.sql.go @@ -11,21 +11,58 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) -const deleteOldLibraryChanges = `-- name: DeleteOldLibraryChanges :execrows -DELETE FROM library_changes WHERE changed_at < $1 +const deleteOldLibraryDeletes = `-- name: DeleteOldLibraryDeletes :one +WITH gone AS ( + DELETE FROM library_changes WHERE op = 'delete' AND changed_at < $1 RETURNING id +), mark AS ( + UPDATE library_changes_trimmed + SET through = GREATEST(through, (SELECT COALESCE(max(id), 0) FROM gone)) +) +SELECT count(*)::BIGINT FROM gone ` -// Removes library_changes rows older than the given cutoff. Run from -// the sync compactor goroutine on a daily tick. Returns the number of -// rows deleted so the worker can log meaningful progress. -func (q *Queries) DeleteOldLibraryChanges(ctx context.Context, changedAt pgtype.Timestamptz) (int64, error) { - result, err := q.db.Exec(ctx, deleteOldLibraryChanges, changedAt) +// Removes deletes older than the cutoff and raises the trimmed mark past the +// highest one, so an app whose cursor is below it starts over. Returns how +// many went. +func (q *Queries) DeleteOldLibraryDeletes(ctx context.Context, changedAt pgtype.Timestamptz) (int64, error) { + row := q.db.QueryRow(ctx, deleteOldLibraryDeletes, changedAt) + var column_1 int64 + err := row.Scan(&column_1) + return column_1, err +} + +const deleteSupersededLibraryChanges = `-- name: DeleteSupersededLibraryChanges :execrows +DELETE FROM library_changes old + WHERE EXISTS (SELECT 1 FROM library_changes newer + WHERE newer.entity_type = old.entity_type + AND newer.entity_id = old.entity_id + AND newer.id > old.id) +` + +// Removes every row a newer row for the same entity has superseded. An app +// reading from any cursor still meets the newer row, so it loses nothing. +func (q *Queries) DeleteSupersededLibraryChanges(ctx context.Context) (int64, error) { + result, err := q.db.Exec(ctx, deleteSupersededLibraryChanges) if err != nil { return 0, err } return result.RowsAffected(), nil } +const getLastIssuedLibraryChangeCursor = `-- name: GetLastIssuedLibraryChangeCursor :one +SELECT COALESCE(pg_sequence_last_value(pg_get_serial_sequence('library_changes', 'id')::regclass), 0)::BIGINT +` + +// The highest cursor this server has handed out, even once the compactor has +// trimmed the rows: the id sequence's last value. A restored server's +// sequence stands at the backup's last change. +func (q *Queries) GetLastIssuedLibraryChangeCursor(ctx context.Context) (int64, error) { + row := q.db.QueryRow(ctx, getLastIssuedLibraryChangeCursor) + var column_1 int64 + err := row.Scan(&column_1) + return column_1, err +} + const getLibraryChangesSince = `-- name: GetLibraryChangesSince :many SELECT id, entity_type, entity_id, op, changed_at FROM library_changes @@ -65,6 +102,19 @@ func (q *Queries) GetLibraryChangesSince(ctx context.Context, arg GetLibraryChan return items, nil } +const getLibraryChangesTrimmedThrough = `-- name: GetLibraryChangesTrimmedThrough :one +SELECT through FROM library_changes_trimmed +` + +// The highest id of a delete the compactor has dropped. A cursor below it may +// have missed that delete. +func (q *Queries) GetLibraryChangesTrimmedThrough(ctx context.Context) (int64, error) { + row := q.db.QueryRow(ctx, getLibraryChangesTrimmedThrough) + var through int64 + err := row.Scan(&through) + return through, err +} + const getMaxLibraryChangeCursor = `-- name: GetMaxLibraryChangeCursor :one SELECT COALESCE(MAX(id), 0)::BIGINT FROM library_changes ` @@ -76,17 +126,6 @@ func (q *Queries) GetMaxLibraryChangeCursor(ctx context.Context) (int64, error) return column_1, err } -const getMinLibraryChangeCursor = `-- name: GetMinLibraryChangeCursor :one -SELECT COALESCE(MIN(id), 0)::BIGINT FROM library_changes -` - -func (q *Queries) GetMinLibraryChangeCursor(ctx context.Context) (int64, error) { - row := q.db.QueryRow(ctx, getMinLibraryChangeCursor) - var column_1 int64 - err := row.Scan(&column_1) - return column_1, err -} - const insertLibraryChange = `-- name: InsertLibraryChange :exec INSERT INTO library_changes (entity_type, entity_id, op) VALUES ($1, $2, $3) diff --git a/internal/db/dbq/library_settings.sql.go b/internal/db/dbq/library_settings.sql.go index 7287bdb4..57baf9e9 100644 --- a/internal/db/dbq/library_settings.sql.go +++ b/internal/db/dbq/library_settings.sql.go @@ -50,45 +50,6 @@ func (q *Queries) RerootAlbumCoverPaths(ctx context.Context, arg RerootAlbumCove return result.RowsAffected(), nil } -const rerootGrabDestinations = `-- name: RerootGrabDestinations :execrows -UPDATE grabs - SET destination = $1::text || substr(destination, length($2::text) + 1) - WHERE destination = $2::text - OR starts_with(destination, $2::text || '/') -` - -type RerootGrabDestinationsParams struct { - NewRoot string - OldRoot string -} - -func (q *Queries) RerootGrabDestinations(ctx context.Context, arg RerootGrabDestinationsParams) (int64, error) { - result, err := q.db.Exec(ctx, rerootGrabDestinations, arg.NewRoot, arg.OldRoot) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const rerootImportRoot = `-- name: RerootImportRoot :execrows -UPDATE acquisition_settings - SET import_root = $1::text - WHERE import_root = $2::text -` - -type RerootImportRootParams struct { - NewRoot string - OldRoot string -} - -func (q *Queries) RerootImportRoot(ctx context.Context, arg RerootImportRootParams) (int64, error) { - result, err := q.db.Exec(ctx, rerootImportRoot, arg.NewRoot, arg.OldRoot) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - const rerootTrackPaths = `-- name: RerootTrackPaths :execrows UPDATE tracks diff --git a/internal/db/dbq/lifecycle.sql.go b/internal/db/dbq/lifecycle.sql.go deleted file mode 100644 index 09aa6f5a..00000000 --- a/internal/db/dbq/lifecycle.sql.go +++ /dev/null @@ -1,408 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: lifecycle.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const countGoneGrabs = `-- name: CountGoneGrabs :one -SELECT count(*) FROM grabs - WHERE info_hash = $1 AND end_reason = 'gone' AND ended_at > $2 -` - -type CountGoneGrabsParams struct { - InfoHash string - Since pgtype.Timestamptz -} - -// How many of a release's grabs ended gone since a time: a release that keeps -// leaving its client is held back rather than taken on every pass. -func (q *Queries) CountGoneGrabs(ctx context.Context, arg CountGoneGrabsParams) (int64, error) { - row := q.db.QueryRow(ctx, countGoneGrabs, arg.InfoHash, arg.Since) - var count int64 - err := row.Scan(&count) - return count, err -} - -const countRemediation = `-- name: CountRemediation :one -UPDATE download_interventions - SET remediations = remediations + 1, - action = $1, - last_seen = now(), - outcome = CASE WHEN $1::text IN ('given_up', 'removed') THEN 'resolved' ELSE outcome END, - settled_at = CASE WHEN $1::text IN ('given_up', 'removed') THEN now() ELSE settled_at END - WHERE client = $2 AND info_hash = $3 - AND trigger = $4 AND outcome = 'open' -RETURNING remediations -` - -type CountRemediationParams struct { - Action string - Client string - InfoHash string - Trigger string -} - -// Minstrel acted on an open condition. A retry climbs the ladder; giving up -// or removing ends the condition, since what it was about is gone. Written -// before the act, so a retry that happened is never uncounted. -func (q *Queries) CountRemediation(ctx context.Context, arg CountRemediationParams) (int32, error) { - row := q.db.QueryRow(ctx, countRemediation, - arg.Action, - arg.Client, - arg.InfoHash, - arg.Trigger, - ) - var remediations int32 - err := row.Scan(&remediations) - return remediations, err -} - -const deleteExpiredBlocks = `-- name: DeleteExpiredBlocks :execrows -DELETE FROM release_blocks WHERE expires_at IS NOT NULL AND expires_at <= now() -` - -// A release given up on is held back for a while; after that the search may -// take it again. -func (q *Queries) DeleteExpiredBlocks(ctx context.Context) (int64, error) { - result, err := q.db.Exec(ctx, deleteExpiredBlocks) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const giveUpGrab = `-- name: GiveUpGrab :one -UPDATE grabs - SET ended_at = now(), end_reason = $1, end_detail = $2, - import_updated_at = now() - WHERE id = $3 AND ended_at IS NULL AND import_state = ANY($4::text[]) -RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at -` - -type GiveUpGrabParams struct { - EndReason string - EndDetail string - ID pgtype.UUID - States []string -} - -// Ends a running grab, given up on. Only from the states named: the update -// is the lock against an import that claimed the download meanwhile. -func (q *Queries) GiveUpGrab(ctx context.Context, arg GiveUpGrabParams) (Grab, error) { - row := q.db.QueryRow(ctx, giveUpGrab, - arg.EndReason, - arg.EndDetail, - arg.ID, - arg.States, - ) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const listClientsDown = `-- name: ListClientsDown :many -SELECT client, detail, first_seen FROM download_interventions - WHERE trigger = 'client_unreachable' AND outcome = 'open' - ORDER BY client -` - -type ListClientsDownRow struct { - Client string - Detail string - FirstSeen pgtype.Timestamptz -} - -// Download clients not answering now, for the Activity tab. -func (q *Queries) ListClientsDown(ctx context.Context) ([]ListClientsDownRow, error) { - rows, err := q.db.Query(ctx, listClientsDown) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListClientsDownRow - for rows.Next() { - var i ListClientsDownRow - if err := rows.Scan(&i.Client, &i.Detail, &i.FirstSeen); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listLeftovers = `-- name: ListLeftovers :many -SELECT id, client, info_hash, grab_id, name, trigger, action, outcome, detail, observations, remediations, first_seen, last_seen, settled_at FROM download_interventions - WHERE trigger = 'not_removed' AND outcome = 'open' AND info_hash <> '' - ORDER BY first_seen -` - -// Downloads given up on that the client would not remove; each pass asks -// again. -func (q *Queries) ListLeftovers(ctx context.Context) ([]DownloadIntervention, error) { - rows, err := q.db.Query(ctx, listLeftovers) - if err != nil { - return nil, err - } - defer rows.Close() - var items []DownloadIntervention - for rows.Next() { - var i DownloadIntervention - if err := rows.Scan( - &i.ID, - &i.Client, - &i.InfoHash, - &i.GrabID, - &i.Name, - &i.Trigger, - &i.Action, - &i.Outcome, - &i.Detail, - &i.Observations, - &i.Remediations, - &i.FirstSeen, - &i.LastSeen, - &i.SettledAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listSeedingGrabs = `-- name: ListSeedingGrabs :many -SELECT id, client, info_hash, name, imported_at FROM grabs - WHERE seeding AND seed_released_at IS NULL - ORDER BY imported_at, id -` - -type ListSeedingGrabsRow struct { - ID pgtype.UUID - Client string - InfoHash string - Name string - ImportedAt pgtype.Timestamptz -} - -// Imported downloads still sharing, oldest import first. -func (q *Queries) ListSeedingGrabs(ctx context.Context) ([]ListSeedingGrabsRow, error) { - rows, err := q.db.Query(ctx, listSeedingGrabs) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListSeedingGrabsRow - for rows.Next() { - var i ListSeedingGrabsRow - if err := rows.Scan( - &i.ID, - &i.Client, - &i.InfoHash, - &i.Name, - &i.ImportedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const liveGrabOnHash = `-- name: LiveGrabOnHash :one -SELECT EXISTS (SELECT 1 FROM grabs WHERE info_hash = $1 AND ended_at IS NULL)::bool -` - -func (q *Queries) LiveGrabOnHash(ctx context.Context, infoHash string) (bool, error) { - row := q.db.QueryRow(ctx, liveGrabOnHash, infoHash) - var column_1 bool - err := row.Scan(&column_1) - return column_1, err -} - -const raiseIntervention = `-- name: RaiseIntervention :one - -INSERT INTO download_interventions (client, info_hash, grab_id, name, trigger, detail) -VALUES ($1, $2, $3, $4, - $5, $6) -ON CONFLICT (client, info_hash, trigger) WHERE outcome = 'open' DO UPDATE SET - observations = download_interventions.observations + 1, - last_seen = now(), - detail = EXCLUDED.detail, - grab_id = COALESCE(EXCLUDED.grab_id, download_interventions.grab_id), - name = CASE WHEN EXCLUDED.name <> '' THEN EXCLUDED.name ELSE download_interventions.name END -RETURNING id, client, info_hash, grab_id, name, trigger, action, outcome, detail, observations, remediations, first_seen, last_seen, settled_at -` - -type RaiseInterventionParams struct { - Client string - InfoHash string - GrabID pgtype.UUID - Name string - Trigger string - Detail string -} - -// The download lifecycle: the intervention ledger, giving a -// download up, and seeding after import. -// A condition seen, or seen again: a second pass lands on the open row, so -// a download stuck for a week is one row that says how long. The name only -// improves, and the detail is the latest word. -func (q *Queries) RaiseIntervention(ctx context.Context, arg RaiseInterventionParams) (DownloadIntervention, error) { - row := q.db.QueryRow(ctx, raiseIntervention, - arg.Client, - arg.InfoHash, - arg.GrabID, - arg.Name, - arg.Trigger, - arg.Detail, - ) - var i DownloadIntervention - err := row.Scan( - &i.ID, - &i.Client, - &i.InfoHash, - &i.GrabID, - &i.Name, - &i.Trigger, - &i.Action, - &i.Outcome, - &i.Detail, - &i.Observations, - &i.Remediations, - &i.FirstSeen, - &i.LastSeen, - &i.SettledAt, - ) - return i, err -} - -const releaseSeed = `-- name: ReleaseSeed :exec -UPDATE grabs SET seed_released_at = now() WHERE id = $1 AND seed_released_at IS NULL -` - -// The seeding download was removed, or found gone. -func (q *Queries) ReleaseSeed(ctx context.Context, id pgtype.UUID) error { - _, err := q.db.Exec(ctx, releaseSeed, id) - return err -} - -const setGrabRatio = `-- name: SetGrabRatio :exec -UPDATE grabs SET ratio = $1 WHERE id = $2 -` - -type SetGrabRatioParams struct { - Ratio float32 - ID pgtype.UUID -} - -func (q *Queries) SetGrabRatio(ctx context.Context, arg SetGrabRatioParams) error { - _, err := q.db.Exec(ctx, setGrabRatio, arg.Ratio, arg.ID) - return err -} - -const settleEndedGrabs = `-- name: SettleEndedGrabs :execrows -UPDATE download_interventions di - SET outcome = 'resolved', settled_at = now(), last_seen = now() - FROM grabs g - WHERE g.id = di.grab_id AND g.ended_at IS NOT NULL - AND di.outcome = 'open' AND di.trigger <> 'not_removed' -` - -// What was wrong with a download whose grab has ended (imported, refused, -// given up) is over, except a download left in the client to remove. -func (q *Queries) SettleEndedGrabs(ctx context.Context) (int64, error) { - result, err := q.db.Exec(ctx, settleEndedGrabs) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const settleIntervention = `-- name: SettleIntervention :execrows -UPDATE download_interventions - SET outcome = 'resolved', settled_at = now(), last_seen = now() - WHERE client = $1 AND info_hash = $2 - AND trigger = $3 AND outcome = 'open' -` - -type SettleInterventionParams struct { - Client string - InfoHash string - Trigger string -} - -// The condition cleared. -func (q *Queries) SettleIntervention(ctx context.Context, arg SettleInterventionParams) (int64, error) { - result, err := q.db.Exec(ctx, settleIntervention, arg.Client, arg.InfoHash, arg.Trigger) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const settleInterventionsFor = `-- name: SettleInterventionsFor :execrows -UPDATE download_interventions - SET outcome = 'resolved', settled_at = now(), last_seen = now() - WHERE client = $1 AND info_hash = $2 AND outcome = 'open' -` - -type SettleInterventionsForParams struct { - Client string - InfoHash string -} - -// Everything open about one download is over: it is gone from the client. -func (q *Queries) SettleInterventionsFor(ctx context.Context, arg SettleInterventionsForParams) (int64, error) { - result, err := q.db.Exec(ctx, settleInterventionsFor, arg.Client, arg.InfoHash) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} diff --git a/internal/db/dbq/likes.sql.go b/internal/db/dbq/likes.sql.go index 5c0137ec..74d53be6 100644 --- a/internal/db/dbq/likes.sql.go +++ b/internal/db/dbq/likes.sql.go @@ -141,7 +141,7 @@ func (q *Queries) ListLikedAlbumIDs(ctx context.Context, userID pgtype.UUID) ([] } const listLikedAlbumRows = `-- name: ListLikedAlbumRows :many -SELECT a.id, a.title, a.sort_title, a.artist_id, a.release_date, a.mbid, a.cover_art_path, a.created_at, a.updated_at, a.cover_art_source, a.cover_art_sources_version, a.release_group_mbid FROM albums a +SELECT a.id, a.title, a.sort_title, a.artist_id, a.release_date, a.mbid, a.cover_art_path, a.created_at, a.updated_at, a.cover_art_source, a.cover_art_sources_version, a.release_group_mbid, a.announced_at FROM albums a JOIN general_likes_albums l ON l.album_id = a.id WHERE l.user_id = $1 ORDER BY l.liked_at DESC @@ -176,6 +176,7 @@ func (q *Queries) ListLikedAlbumRows(ctx context.Context, arg ListLikedAlbumRows &i.CoverArtSource, &i.CoverArtSourcesVersion, &i.ReleaseGroupMbid, + &i.AnnouncedAt, ); err != nil { return nil, err } @@ -281,7 +282,7 @@ func (q *Queries) ListLikedTrackIDs(ctx context.Context, userID pgtype.UUID) ([] } const listLikedTrackRows = `-- name: ListLikedTrackRows :many -SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at FROM tracks t +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit FROM tracks t JOIN (SELECT DISTINCT ON (lt.song_key) l.track_id, l.liked_at FROM general_likes l JOIN tracks lt ON lt.id = l.track_id @@ -336,6 +337,84 @@ func (q *Queries) ListLikedTrackRows(ctx context.Context, arg ListLikedTrackRows &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listPlayableLikedTrackRows = `-- name: ListPlayableLikedTrackRows :many +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit FROM tracks t +JOIN (SELECT DISTINCT ON (lt.song_key) l.track_id, l.liked_at + FROM general_likes l + JOIN tracks lt ON lt.id = l.track_id + WHERE l.user_id = $1 + AND lt.missing_since IS NULL + AND NOT EXISTS (SELECT 1 FROM quarantine q + WHERE q.user_id = $1 AND q.track_id = lt.id) + ORDER BY lt.song_key, (lt.source_verdict IS NOT DISTINCT FROM 'suspect'), l.liked_at, lt.id) l + ON l.track_id = t.id +ORDER BY l.liked_at DESC, t.id +LIMIT $2 +` + +type ListPlayableLikedTrackRowsParams struct { + UserID pgtype.UUID + RowLimit int32 +} + +// Subsonic's starred songs: one row per liked song the listener can play, so +// a copy present on disk and not quarantined by them, preferring one that is +// not a held-back video rip, then the one liked first. Subsonic has no way to +// show a song as unplayable; an app would only fail to stream it, or play the +// copy the listener hid. Filtered here rather than after the LIMIT so the cap +// counts playable songs. +func (q *Queries) ListPlayableLikedTrackRows(ctx context.Context, arg ListPlayableLikedTrackRowsParams) ([]Track, error) { + rows, err := q.db.Query(ctx, listPlayableLikedTrackRows, arg.UserID, arg.RowLimit) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Track + for rows.Next() { + var i Track + if err := rows.Scan( + &i.ID, + &i.Title, + &i.AlbumID, + &i.ArtistID, + &i.TrackNumber, + &i.DiscNumber, + &i.DurationMs, + &i.FilePath, + &i.FileSize, + &i.FileFormat, + &i.Bitrate, + &i.Mbid, + &i.Genre, + &i.AddedAt, + &i.UpdatedAt, + &i.TagSource, + &i.TagSourcesVersion, + &i.TagReadVersion, + &i.MissingSince, + &i.MbidSource, + &i.SongID, + &i.SongKey, + &i.SourceVerdict, + &i.SourceVerdictAt, + &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, ); err != nil { return nil, err } diff --git a/internal/db/dbq/lookup_settings.sql.go b/internal/db/dbq/lookup_settings.sql.go new file mode 100644 index 00000000..135c146c --- /dev/null +++ b/internal/db/dbq/lookup_settings.sql.go @@ -0,0 +1,52 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: lookup_settings.sql + +package dbq + +import ( + "context" +) + +const getLookupSettings = `-- name: GetLookupSettings :one +SELECT id, listenbrainz_similarity, musicbrainz_track_lists, updated_at FROM lookup_settings WHERE id = true +` + +func (q *Queries) GetLookupSettings(ctx context.Context) (LookupSetting, error) { + row := q.db.QueryRow(ctx, getLookupSettings) + var i LookupSetting + err := row.Scan( + &i.ID, + &i.ListenbrainzSimilarity, + &i.MusicbrainzTrackLists, + &i.UpdatedAt, + ) + return i, err +} + +const updateLookupSettings = `-- name: UpdateLookupSettings :one +UPDATE lookup_settings + SET listenbrainz_similarity = $1, + musicbrainz_track_lists = $2, + updated_at = now() + WHERE id = true +RETURNING id, listenbrainz_similarity, musicbrainz_track_lists, updated_at +` + +type UpdateLookupSettingsParams struct { + ListenbrainzSimilarity bool + MusicbrainzTrackLists bool +} + +func (q *Queries) UpdateLookupSettings(ctx context.Context, arg UpdateLookupSettingsParams) (LookupSetting, error) { + row := q.db.QueryRow(ctx, updateLookupSettings, arg.ListenbrainzSimilarity, arg.MusicbrainzTrackLists) + var i LookupSetting + err := row.Scan( + &i.ID, + &i.ListenbrainzSimilarity, + &i.MusicbrainzTrackLists, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/db/dbq/merge.sql.go b/internal/db/dbq/merge.sql.go index eee18b55..e5979740 100644 --- a/internal/db/dbq/merge.sql.go +++ b/internal/db/dbq/merge.sql.go @@ -297,24 +297,6 @@ func (q *Queries) MergeRepointPlaylistTracks(ctx context.Context, arg MergeRepoi return items, nil } -const mergeRepointRequests = `-- name: MergeRepointRequests :execrows -UPDATE requests SET matched_track_id = $1::uuid - WHERE matched_track_id = $2::uuid -` - -type MergeRepointRequestsParams struct { - SurvivorID pgtype.UUID - LoserID pgtype.UUID -} - -func (q *Queries) MergeRepointRequests(ctx context.Context, arg MergeRepointRequestsParams) (int64, error) { - result, err := q.db.Exec(ctx, mergeRepointRequests, arg.SurvivorID, arg.LoserID) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - const mergeRepointSkipEvents = `-- name: MergeRepointSkipEvents :execrows UPDATE skip_events SET track_id = $1::uuid WHERE track_id = $2::uuid ` diff --git a/internal/db/dbq/missing_pairs.sql.go b/internal/db/dbq/missing_pairs.sql.go index 408f1e43..1f04e993 100644 --- a/internal/db/dbq/missing_pairs.sql.go +++ b/internal/db/dbq/missing_pairs.sql.go @@ -66,7 +66,7 @@ type ListMissingTrackPairsRow struct { // Missing-pair pass. A track marked missing whose replacement is already // on disk under another row — most often a quality upgrade, mp3 → flac at a new // path — is folded into that replacement, so its history moves across and -// re-acquisition stops chasing music the library already has. +// the track stops waiting for a file the library already has. // // Move adoption cannot catch these: it links a new file to a missing row // at the moment the file is first inserted, and the replacement arrives as a @@ -89,7 +89,7 @@ type ListMissingTrackPairsRow struct { // they are different recordings. The caller folds a pair only when each side has // exactly one candidate; anything else is ambiguous and left alone. // -// A slot the duplicate resolver emptied (emptied_at, migration 0095) pairs by +// A slot the duplicate resolver emptied (emptied_at) pairs by // title only with a track added since: the album held no copy of the song as // long as it is, so one already there under the title is another song. func (q *Queries) ListMissingTrackPairs(ctx context.Context) ([]ListMissingTrackPairsRow, error) { diff --git a/internal/db/dbq/models.go b/internal/db/dbq/models.go index 96e155aa..784c5b9c 100644 --- a/internal/db/dbq/models.go +++ b/internal/db/dbq/models.go @@ -17,6 +17,7 @@ const ( QuarantineActionKindResolved QuarantineActionKind = "resolved" QuarantineActionKindDeletedFile QuarantineActionKind = "deleted_file" QuarantineActionKindDeletedAlbum QuarantineActionKind = "deleted_album" + QuarantineActionKindRemovedFile QuarantineActionKind = "removed_file" ) func (e *QuarantineActionKind) Scan(src interface{}) error { @@ -99,94 +100,6 @@ func (ns NullQuarantineReason) Value() (driver.Value, error) { return string(ns.QuarantineReason), nil } -type RequestKind string - -const ( - RequestKindArtist RequestKind = "artist" - RequestKindAlbum RequestKind = "album" - RequestKindTrack RequestKind = "track" -) - -func (e *RequestKind) Scan(src interface{}) error { - switch s := src.(type) { - case []byte: - *e = RequestKind(s) - case string: - *e = RequestKind(s) - default: - return fmt.Errorf("unsupported scan type for RequestKind: %T", src) - } - return nil -} - -type NullRequestKind struct { - RequestKind RequestKind - Valid bool // Valid is true if RequestKind is not NULL -} - -// Scan implements the Scanner interface. -func (ns *NullRequestKind) Scan(value interface{}) error { - if value == nil { - ns.RequestKind, ns.Valid = "", false - return nil - } - ns.Valid = true - return ns.RequestKind.Scan(value) -} - -// Value implements the driver Valuer interface. -func (ns NullRequestKind) Value() (driver.Value, error) { - if !ns.Valid { - return nil, nil - } - return string(ns.RequestKind), nil -} - -type RequestStatus string - -const ( - RequestStatusPending RequestStatus = "pending" - RequestStatusApproved RequestStatus = "approved" - RequestStatusRejected RequestStatus = "rejected" - RequestStatusCompleted RequestStatus = "completed" - RequestStatusFailed RequestStatus = "failed" -) - -func (e *RequestStatus) Scan(src interface{}) error { - switch s := src.(type) { - case []byte: - *e = RequestStatus(s) - case string: - *e = RequestStatus(s) - default: - return fmt.Errorf("unsupported scan type for RequestStatus: %T", src) - } - return nil -} - -type NullRequestStatus struct { - RequestStatus RequestStatus - Valid bool // Valid is true if RequestStatus is not NULL -} - -// Scan implements the Scanner interface. -func (ns *NullRequestStatus) Scan(value interface{}) error { - if value == nil { - ns.RequestStatus, ns.Valid = "", false - return nil - } - ns.Valid = true - return ns.RequestStatus.Scan(value) -} - -// Value implements the driver Valuer interface. -func (ns NullRequestStatus) Value() (driver.Value, error) { - if !ns.Valid { - return nil, nil - } - return string(ns.RequestStatus), nil -} - type AcoustidSetting struct { ID bool Enabled bool @@ -195,46 +108,6 @@ type AcoustidSetting struct { UpdatedAt pgtype.Timestamptz } -type AcquisitionService struct { - Code string - Kind string - Protocol string - Label string - Enabled bool - BaseUrl string - ApiKey string - Username string - Password string - Category string - TimeoutMs int32 - ServesSearch bool - ServesDownloads bool - ServesEnrichment bool - LocalPath string - RemotePath string - SearchesPerHour int32 - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz -} - -type AcquisitionSetting struct { - ID bool - AutoGrab bool - SearchIntervalHours int32 - AllowedQualities []string - LastPassAt pgtype.Timestamptz - LastPass []byte - UpdatedAt pgtype.Timestamptz - ImportRoot string - SeedRatio float32 - SeedDays int32 - StallHours int32 - LibraryListingStartedAt pgtype.Timestamptz - LibraryListedAt pgtype.Timestamptz - LibraryUnlisted int32 - UpgradeUntil string -} - type Album struct { ID pgtype.UUID Title string @@ -248,6 +121,7 @@ type Album struct { CoverArtSource *string CoverArtSourcesVersion int32 ReleaseGroupMbid *string + AnnouncedAt pgtype.Timestamptz } type AlbumLoudness struct { @@ -287,15 +161,6 @@ type ArtistSimilarityFetch struct { Returned int32 } -type ArtistSimilarityUnmatched struct { - SeedArtistID pgtype.UUID - CandidateMbid string - CandidateName string - Score float64 - Source string - FetchedAt pgtype.Timestamptz -} - type AuditLog struct { ID pgtype.UUID ActorID pgtype.UUID @@ -305,17 +170,42 @@ type AuditLog struct { CreatedAt pgtype.Timestamptz } -type CandidateArtistTag struct { - CandidateMbid string - Tag string - Weight float64 +type BackupMusicFile struct { + TrackID pgtype.UUID + Size int64 + Mtime pgtype.Timestamptz + Location string + CheckedAt pgtype.Timestamptz + Error string } -type CandidateArtistTagState struct { - CandidateMbid string - TagSource string - TagSourcesVersion int32 - UpdatedAt pgtype.Timestamptz +type BackupRun struct { + ID pgtype.UUID + Trigger string + Status string + StartedAt pgtype.Timestamptz + FinishedAt pgtype.Timestamptz + Location string + Bytes int64 + Error string + MusicFiles int32 + MusicBytes int64 + MusicNote string +} + +type BackupSetting struct { + ID bool + Enabled bool + Destination string + Folder string + Endpoint string + Bucket string + AccessKey string + SecretKey string + RunHour int16 + UploadLimitKib int32 + UpdatedAt pgtype.Timestamptz + IncludeMusic bool } type ContextualLike struct { @@ -355,30 +245,6 @@ type DiagnosticEvent struct { ReceivedAt pgtype.Timestamptz } -type DiscoverTuning struct { - Singleton bool - TagOverlapWeight float64 - SnoozeDays float64 - UpdatedAt pgtype.Timestamptz -} - -type DownloadIntervention struct { - ID pgtype.UUID - Client string - InfoHash string - GrabID pgtype.UUID - Name string - Trigger string - Action string - Outcome string - Detail string - Observations int32 - Remediations int32 - FirstSeen pgtype.Timestamptz - LastSeen pgtype.Timestamptz - SettledAt pgtype.Timestamptz -} - type DuplicateGroup struct { ID pgtype.UUID MemberKey string @@ -419,24 +285,6 @@ type FingerprintSetting struct { AutoResolve bool } -type Follow struct { - ArtistMbid string - ArtistName string - ProfileID pgtype.UUID - FollowedBy pgtype.UUID - FollowedAt pgtype.Timestamptz - BaselineAt pgtype.Timestamptz - WantExisting bool - CheckedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz -} - -type FollowSeenGroup struct { - ArtistMbid string - ReleaseGroupMbid string - SeenAt pgtype.Timestamptz -} - type GeneralLike struct { UserID pgtype.UUID TrackID pgtype.UUID @@ -455,49 +303,6 @@ type GeneralLikesArtist struct { LikedAt pgtype.Timestamptz } -type Grab struct { - ID pgtype.UUID - WantID pgtype.UUID - InfoHash string - Name string - Key string - Indexer string - Source string - Client string - SavePath string - Quality string - Origin string - Forced bool - GrabbedBy pgtype.UUID - GrabbedAt pgtype.Timestamptz - EndedAt pgtype.Timestamptz - EndReason string - EndDetail string - Progress float32 - ImportState string - ImportReason string - ImportDetail []byte - ImportForced bool - ImportAttempts int32 - ImportUpdatedAt pgtype.Timestamptz - ImportedAt pgtype.Timestamptz - ImportedFiles int32 - Destination string - Seeding bool - Ratio float32 - SeedReleasedAt pgtype.Timestamptz -} - -type LibraryAlbumMatch struct { - AlbumID pgtype.UUID - Outcome string - Method string - ReleaseGroupMbid string - Detail string - DecidedAt pgtype.Timestamptz - Matcher int32 -} - type LibraryChange struct { ID int64 EntityType string @@ -506,6 +311,11 @@ type LibraryChange struct { ChangedAt pgtype.Timestamptz } +type LibraryChangesTrimmed struct { + ID bool + Through int64 +} + type LibrarySetting struct { ID bool ScanPaths []string @@ -518,6 +328,13 @@ type ListenbrainzSimilarRecording struct { Score float64 } +type LookupSetting struct { + ID bool + ListenbrainzSimilarity bool + MusicbrainzTrackLists bool + UpdatedAt pgtype.Timestamptz +} + type LoudnessSetting struct { ID bool Enabled bool @@ -526,23 +343,6 @@ type LoudnessSetting struct { LeveledCacheMb int32 } -type MbArtist struct { - Mbid string - Name string - SortName string - Disambiguation string - ArtistType string - Country string - DiscographyRefreshedAt pgtype.Timestamptz - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz -} - -type MbArtistReleaseGroup struct { - ArtistMbid string - ReleaseGroupMbid string -} - type MbRelease struct { Mbid string ReleaseGroupMbid string @@ -618,6 +418,15 @@ type PlayEvent struct { DeviceClass *string } +type PlayQueue struct { + UserID pgtype.UUID + TrackIds []pgtype.UUID + CurrentTrackID pgtype.UUID + PositionMs int64 + ChangedAt pgtype.Timestamptz + ChangedBy string +} + type PlaySession struct { ID pgtype.UUID UserID pgtype.UUID @@ -655,6 +464,13 @@ type Playlist struct { Kind string SystemVariant *string SeedArtistID pgtype.UUID + ShelfRank int32 +} + +type PlaylistAppendRequest struct { + PlaylistID pgtype.UUID + RequestID pgtype.UUID + CreatedAt pgtype.Timestamptz } type PlaylistTrack struct { @@ -690,13 +506,6 @@ type QuarantineAction struct { CreatedAt pgtype.Timestamptz } -type ReacquisitionSetting struct { - ID bool - Enabled bool - GraceHours int32 - MaxPerPass int32 -} - type RecommendationTuningAudit struct { ID int64 ChangedAt pgtype.Timestamptz @@ -719,54 +528,6 @@ type RecommendationWeightProfile struct { ContextTimeWeight float64 } -type RegistrationSetting struct { - ID bool - Mode string -} - -type ReleaseBlock struct { - InfoHash string - Name string - Reason string - Detail string - WantID pgtype.UUID - BlockedBy pgtype.UUID - BlockedAt pgtype.Timestamptz - ExpiresAt pgtype.Timestamptz -} - -type ReleaseTypeProfile struct { - ID pgtype.UUID - Name string - PrimaryTypes []string - SecondaryTypes []string - IsDefault bool - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz -} - -type Request struct { - ID pgtype.UUID - UserID pgtype.UUID - Status RequestStatus - Kind RequestKind - ArtistMbid string - AlbumMbid *string - TrackMbid *string - ArtistName string - AlbumTitle *string - TrackTitle *string - DecidedAt pgtype.Timestamptz - DecidedBy pgtype.UUID - Notes *string - CompletedAt pgtype.Timestamptz - MatchedTrackID pgtype.UUID - MatchedAlbumID pgtype.UUID - MatchedArtistID pgtype.UUID - RequestedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz -} - type ScanRun struct { ID pgtype.UUID StartedAt pgtype.Timestamptz @@ -822,14 +583,6 @@ type SmtpConfig struct { UpdatedAt pgtype.Timestamptz } -type SuggestionSnooze struct { - UserID pgtype.UUID - CandidateMbid string - CandidateName string - SnoozedUntil pgtype.Timestamptz - CreatedAt pgtype.Timestamptz -} - type SystemPlaylistRotationState struct { UserID pgtype.UUID PlaylistKind string @@ -927,6 +680,9 @@ type Track struct { SourceVerdict *string SourceVerdictAt pgtype.Timestamptz EmptiedAt pgtype.Timestamptz + RemovedReason *string + RemovedBy pgtype.UUID + ArtistCredit *string } type TrackAcoustidLookup struct { @@ -990,7 +746,6 @@ type User struct { ListenbrainzToken *string ListenbrainzEnabled bool DisplayName *string - AutoApproveRequests bool Email *string Timezone string TimezoneUpdatedAt pgtype.Timestamptz @@ -1045,54 +800,6 @@ type UserNotificationPref struct { UpdatedAt pgtype.Timestamptz } -type Want struct { - ID pgtype.UUID - ReleaseGroupMbid string - ArtistMbid string - ArtistName string - Title string - PrimaryType string - FirstReleaseDate string - Reason string - AlbumID pgtype.UUID - CreatedBy pgtype.UUID - WantedAt pgtype.Timestamptz - FulfilledAt pgtype.Timestamptz - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz - SearchedAt pgtype.Timestamptz - SearchOutcome string - SearchConsidered int32 - BestRelease string - BestVerdict string - SearchError string - Upgrade string - HeldTier string - HeldQuality string - UpgradeCheckedAt pgtype.Timestamptz -} - -type WantCandidate struct { - WantID pgtype.UUID - Key string - Name string - InfoHash string - Indexer string - Source string - SizeBytes int64 - Seeders int32 - FilesCount int32 - Format string - Quality string - Year int32 - Verdict string - Reason string - Reasons []byte - FoldedFrom []string - Rank int32 - SearchedAt pgtype.Timestamptz -} - type YouMightLikeAlbum struct { UserID pgtype.UUID AlbumID pgtype.UUID diff --git a/internal/db/dbq/normalization_prefs.sql.go b/internal/db/dbq/normalization_prefs.sql.go index 332edb96..2726d2b5 100644 --- a/internal/db/dbq/normalization_prefs.sql.go +++ b/internal/db/dbq/normalization_prefs.sql.go @@ -61,7 +61,7 @@ type UpsertNormalizationPrefsRow struct { UpdatedAt pgtype.Timestamptz } -// Whole-row write from either client; the CHECKs in migration 0067 back the +// Whole-row write from either client; the CHECKs on user_normalization_prefs back the // handler's own validation. func (q *Queries) UpsertNormalizationPrefs(ctx context.Context, arg UpsertNormalizationPrefsParams) (UpsertNormalizationPrefsRow, error) { row := q.db.QueryRow(ctx, upsertNormalizationPrefs, diff --git a/internal/db/dbq/notifications.sql.go b/internal/db/dbq/notifications.sql.go index 4ea5343d..56e350a0 100644 --- a/internal/db/dbq/notifications.sql.go +++ b/internal/db/dbq/notifications.sql.go @@ -331,6 +331,30 @@ func (q *Queries) ListNotifications(ctx context.Context, arg ListNotificationsPa return items, nil } +const listUserIDs = `-- name: ListUserIDs :many +SELECT id FROM users ORDER BY created_at, id +` + +func (q *Queries) ListUserIDs(ctx context.Context) ([]pgtype.UUID, error) { + rows, err := q.db.Query(ctx, listUserIDs) + if err != nil { + return nil, err + } + defer rows.Close() + var items []pgtype.UUID + for rows.Next() { + var id pgtype.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + items = append(items, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const markAllNotificationsRead = `-- name: MarkAllNotificationsRead :execrows UPDATE user_notifications SET read_at = now() @@ -439,7 +463,7 @@ type UpdateNotificationEmailSettingsParams struct { BatchWindowMinutes int32 } -// Migration 0074's CHECKs are the backstop behind the service's validation. +// notification_email_settings's CHECKs are the backstop behind the service's validation. func (q *Queries) UpdateNotificationEmailSettings(ctx context.Context, arg UpdateNotificationEmailSettingsParams) (NotificationEmailSetting, error) { row := q.db.QueryRow(ctx, updateNotificationEmailSettings, arg.SummaryHour, arg.BatchWindowMinutes) var i NotificationEmailSetting diff --git a/internal/db/dbq/password_resets.sql.go b/internal/db/dbq/password_resets.sql.go index 64977b7f..97e0990e 100644 --- a/internal/db/dbq/password_resets.sql.go +++ b/internal/db/dbq/password_resets.sql.go @@ -27,17 +27,6 @@ func (q *Queries) CreatePasswordReset(ctx context.Context, arg CreatePasswordRes return err } -const deleteExpiredPasswordResets = `-- name: DeleteExpiredPasswordResets :exec -DELETE FROM password_resets WHERE expires_at < now() - interval '7 days' -` - -// Cleanup: drop tokens that have been expired more than 7 days. -// Not wired in U3; useful to have for a future cron sweep. -func (q *Queries) DeleteExpiredPasswordResets(ctx context.Context) error { - _, err := q.db.Exec(ctx, deleteExpiredPasswordResets) - return err -} - const getPasswordReset = `-- name: GetPasswordReset :one SELECT token, user_id, created_at, expires_at, used_at FROM password_resets WHERE token = $1 ` diff --git a/internal/db/dbq/play_queue.sql.go b/internal/db/dbq/play_queue.sql.go new file mode 100644 index 00000000..089e1a7c --- /dev/null +++ b/internal/db/dbq/play_queue.sql.go @@ -0,0 +1,70 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: play_queue.sql + +package dbq + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const deletePlayQueue = `-- name: DeletePlayQueue :exec +DELETE FROM play_queues WHERE user_id = $1 +` + +func (q *Queries) DeletePlayQueue(ctx context.Context, userID pgtype.UUID) error { + _, err := q.db.Exec(ctx, deletePlayQueue, userID) + return err +} + +const getPlayQueue = `-- name: GetPlayQueue :one +SELECT user_id, track_ids, current_track_id, position_ms, changed_at, changed_by FROM play_queues WHERE user_id = $1 +` + +func (q *Queries) GetPlayQueue(ctx context.Context, userID pgtype.UUID) (PlayQueue, error) { + row := q.db.QueryRow(ctx, getPlayQueue, userID) + var i PlayQueue + err := row.Scan( + &i.UserID, + &i.TrackIds, + &i.CurrentTrackID, + &i.PositionMs, + &i.ChangedAt, + &i.ChangedBy, + ) + return i, err +} + +const savePlayQueue = `-- name: SavePlayQueue :exec +INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_at, changed_by) +VALUES ($1, $2::uuid[], $3, $4, now(), $5) +ON CONFLICT (user_id) DO UPDATE + SET track_ids = EXCLUDED.track_ids, + current_track_id = EXCLUDED.current_track_id, + position_ms = EXCLUDED.position_ms, + changed_at = EXCLUDED.changed_at, + changed_by = EXCLUDED.changed_by +` + +type SavePlayQueueParams struct { + UserID pgtype.UUID + TrackIds []pgtype.UUID + CurrentTrackID pgtype.UUID + PositionMs int64 + ChangedBy string +} + +// Replaces the user's saved queue. +func (q *Queries) SavePlayQueue(ctx context.Context, arg SavePlayQueueParams) error { + _, err := q.db.Exec(ctx, savePlayQueue, + arg.UserID, + arg.TrackIds, + arg.CurrentTrackID, + arg.PositionMs, + arg.ChangedBy, + ) + return err +} diff --git a/internal/db/dbq/playlists.sql.go b/internal/db/dbq/playlists.sql.go index 78c134bd..ed88fac9 100644 --- a/internal/db/dbq/playlists.sql.go +++ b/internal/db/dbq/playlists.sql.go @@ -18,7 +18,7 @@ SELECT COALESCE((SELECT MAX(position) + 1 FROM playlist_tracks WHERE playlist_id = $1::uuid), 0), t.id, t.title, - artists.name, + COALESCE(t.artist_credit, artists.name), albums.title, (t.duration_ms / 1000)::integer, $2::text @@ -57,20 +57,26 @@ func (q *Queries) AppendPlaylistTrack(ctx context.Context, arg AppendPlaylistTra } const createPlaylist = `-- name: CreatePlaylist :one -INSERT INTO playlists (user_id, name, description, is_public) -VALUES ($1, $2, $3, $4) -RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id +INSERT INTO playlists (id, user_id, name, description, is_public) +VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3, $4, $5) +ON CONFLICT (id) DO NOTHING +RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank ` type CreatePlaylistParams struct { + ID pgtype.UUID UserID pgtype.UUID Name string Description string IsPublic bool } +// id is the client's own id for the list, or NULL for a new one. A client +// that made the list offline sends its id again on every retry, so an id +// already taken inserts nothing and returns no row. func (q *Queries) CreatePlaylist(ctx context.Context, arg CreatePlaylistParams) (Playlist, error) { row := q.db.QueryRow(ctx, createPlaylist, + arg.ID, arg.UserID, arg.Name, arg.Description, @@ -91,6 +97,7 @@ func (q *Queries) CreatePlaylist(ctx context.Context, arg CreatePlaylistParams) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ) return i, err } @@ -132,7 +139,7 @@ func (q *Queries) DeletePlaylistTrack(ctx context.Context, arg DeletePlaylistTra } const getPlaylist = `-- name: GetPlaylist :one -SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, u.username AS owner_username +SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, p.shelf_rank, u.username AS owner_username FROM playlists p JOIN users u ON u.id = p.user_id WHERE p.id = $1 @@ -152,6 +159,7 @@ type GetPlaylistRow struct { Kind string SystemVariant *string SeedArtistID pgtype.UUID + ShelfRank int32 OwnerUsername string } @@ -172,13 +180,14 @@ func (q *Queries) GetPlaylist(ctx context.Context, id pgtype.UUID) (GetPlaylistR &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, &i.OwnerUsername, ) return i, err } const getPlaylistsByIDs = `-- name: GetPlaylistsByIDs :many -SELECT id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id FROM playlists WHERE id = ANY($1::uuid[]) +SELECT id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank FROM playlists WHERE id = ANY($1::uuid[]) ` // Batched lookup used by /api/library/sync to hydrate upsert payloads @@ -206,6 +215,7 @@ func (q *Queries) GetPlaylistsByIDs(ctx context.Context, dollar_1 []pgtype.UUID) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ); err != nil { return nil, err } @@ -260,6 +270,86 @@ func (q *Queries) ListAllPlaylistTracksForCollage(ctx context.Context, arg ListA return items, nil } +const listPlaylistCoverAlbums = `-- name: ListPlaylistCoverAlbums :many +SELECT s.playlist_id, + (array_agg(s.album_id ORDER BY s.first_position))[1:6]::uuid[] AS album_ids +FROM ( + SELECT pt.playlist_id, t.album_id, MIN(pt.position) AS first_position + FROM playlist_tracks pt + JOIN tracks t ON t.id = pt.track_id + JOIN albums a ON a.id = t.album_id + WHERE pt.playlist_id = ANY($1::uuid[]) + AND a.cover_art_path IS NOT NULL + AND a.cover_art_path <> '' + GROUP BY pt.playlist_id, t.album_id +) s +GROUP BY s.playlist_id +` + +type ListPlaylistCoverAlbumsRow struct { + PlaylistID pgtype.UUID + AlbumIds []pgtype.UUID +} + +// The albums a playlist's tiles can show: up to six distinct albums with +// cover art per playlist, in the order they first appear in its tracks. +// More than one per playlist, so a shelf of tiles can give each one a +// cover no other tile on the shelf is already showing. +func (q *Queries) ListPlaylistCoverAlbums(ctx context.Context, playlistIds []pgtype.UUID) ([]ListPlaylistCoverAlbumsRow, error) { + rows, err := q.db.Query(ctx, listPlaylistCoverAlbums, playlistIds) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListPlaylistCoverAlbumsRow + for rows.Next() { + var i ListPlaylistCoverAlbumsRow + if err := rows.Scan(&i.PlaylistID, &i.AlbumIds); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listPlaylistEntriesForUpdate = `-- name: ListPlaylistEntriesForUpdate :many +SELECT position, track_id +FROM playlist_tracks +WHERE playlist_id = $1 +ORDER BY position +FOR UPDATE +` + +type ListPlaylistEntriesForUpdateRow struct { + Position int32 + TrackID pgtype.UUID +} + +// The track at each position, locking the rows while a reorder rewrites +// them. +func (q *Queries) ListPlaylistEntriesForUpdate(ctx context.Context, playlistID pgtype.UUID) ([]ListPlaylistEntriesForUpdateRow, error) { + rows, err := q.db.Query(ctx, listPlaylistEntriesForUpdate, playlistID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListPlaylistEntriesForUpdateRow + for rows.Next() { + var i ListPlaylistEntriesForUpdateRow + if err := rows.Scan(&i.Position, &i.TrackID); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const listPlaylistTracks = `-- name: ListPlaylistTracks :many SELECT pt.playlist_id, pt.position, pt.track_id, pt.title, pt.artist_name, pt.album_title, pt.duration_sec, pt.added_at, pt.pick_kind, t.id AS live_track_id, @@ -335,7 +425,7 @@ func (q *Queries) ListPlaylistTracks(ctx context.Context, playlistID pgtype.UUID } const listPlaylistsForUser = `-- name: ListPlaylistsForUser :many -SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, u.username AS owner_username +SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, p.shelf_rank, u.username AS owner_username FROM playlists p JOIN users u ON u.id = p.user_id WHERE p.user_id = $1 OR p.is_public = true @@ -356,6 +446,7 @@ type ListPlaylistsForUserRow struct { Kind string SystemVariant *string SeedArtistID pgtype.UUID + ShelfRank int32 OwnerUsername string } @@ -384,6 +475,7 @@ func (q *Queries) ListPlaylistsForUser(ctx context.Context, userID pgtype.UUID) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, &i.OwnerUsername, ); err != nil { return nil, err @@ -396,6 +488,64 @@ func (q *Queries) ListPlaylistsForUser(ctx context.Context, userID pgtype.UUID) return items, nil } +const listUserPlaylistIDsForOwner = `-- name: ListUserPlaylistIDsForOwner :many +SELECT id FROM playlists WHERE user_id = $1 AND kind = 'user' ORDER BY id +` + +// The playlists a person made, not their system mixes. +func (q *Queries) ListUserPlaylistIDsForOwner(ctx context.Context, userID pgtype.UUID) ([]pgtype.UUID, error) { + rows, err := q.db.Query(ctx, listUserPlaylistIDsForOwner, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []pgtype.UUID + for rows.Next() { + var id pgtype.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + items = append(items, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const prunePlaylistAppendRequests = `-- name: PrunePlaylistAppendRequests :exec +DELETE FROM playlist_append_requests +WHERE playlist_id = $1 AND created_at < now() - interval '30 days' +` + +// Forgets the playlist's append request ids older than 30 days, by which +// time any queued replay of them has long since been sent. +func (q *Queries) PrunePlaylistAppendRequests(ctx context.Context, playlistID pgtype.UUID) error { + _, err := q.db.Exec(ctx, prunePlaylistAppendRequests, playlistID) + return err +} + +const recordPlaylistAppendRequest = `-- name: RecordPlaylistAppendRequest :execrows +INSERT INTO playlist_append_requests (playlist_id, request_id) +VALUES ($1::uuid, $2::uuid) +ON CONFLICT DO NOTHING +` + +type RecordPlaylistAppendRequestParams struct { + PlaylistID pgtype.UUID + RequestID pgtype.UUID +} + +// Claims a client's append request id for the playlist. No row affected +// means the id was already applied: the append is a replay. +func (q *Queries) RecordPlaylistAppendRequest(ctx context.Context, arg RecordPlaylistAppendRequestParams) (int64, error) { + result, err := q.db.Exec(ctx, recordPlaylistAppendRequest, arg.PlaylistID, arg.RequestID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const renumberPlaylistTracksAfter = `-- name: RenumberPlaylistTracksAfter :exec UPDATE playlist_tracks SET position = position - 1 @@ -414,7 +564,8 @@ func (q *Queries) RenumberPlaylistTracksAfter(ctx context.Context, arg RenumberP } const setPlaylistCover = `-- name: SetPlaylistCover :exec -UPDATE playlists SET cover_path = $2, updated_at = now() WHERE id = $1 +UPDATE playlists SET cover_path = $2, updated_at = now() + WHERE id = $1 AND cover_path IS DISTINCT FROM $2 ` type SetPlaylistCoverParams struct { @@ -422,6 +573,8 @@ type SetPlaylistCoverParams struct { CoverPath *string } +// Only a changed path counts as a change to the playlist: a collage drawn +// again to the same file leaves updated_at alone. func (q *Queries) SetPlaylistCover(ctx context.Context, arg SetPlaylistCoverParams) error { _, err := q.db.Exec(ctx, setPlaylistCover, arg.ID, arg.CoverPath) return err @@ -435,7 +588,7 @@ SET is_public = CASE WHEN $5::boolean THEN $6::boolean ELSE is_public END, updated_at = now() WHERE id = $7 -RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id +RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank ` type UpdatePlaylistParams struct { @@ -476,6 +629,7 @@ func (q *Queries) UpdatePlaylist(ctx context.Context, arg UpdatePlaylistParams) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ) return i, err } diff --git a/internal/db/dbq/reacquisition.sql.go b/internal/db/dbq/reacquisition.sql.go deleted file mode 100644 index f82244f6..00000000 --- a/internal/db/dbq/reacquisition.sql.go +++ /dev/null @@ -1,272 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: reacquisition.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const countAlbumsMissingWithoutMbid = `-- name: CountAlbumsMissingWithoutMbid :one -SELECT COUNT(DISTINCT albums.id)::bigint - FROM albums - JOIN artists ON artists.id = albums.artist_id - JOIN tracks ON tracks.album_id = albums.id - WHERE tracks.missing_since IS NOT NULL - AND ((albums.mbid IS NULL AND albums.release_group_mbid IS NULL) OR artists.mbid IS NULL) -` - -// Albums with missing files that can never be wanted automatically because -// nothing identifies them to MusicBrainz. Surfaced on the admin card so the -// gap is visible: silently doing nothing for these would read as broken. -func (q *Queries) CountAlbumsMissingWithoutMbid(ctx context.Context) (int64, error) { - row := q.db.QueryRow(ctx, countAlbumsMissingWithoutMbid) - var column_1 int64 - err := row.Scan(&column_1) - return column_1, err -} - -const getReacquisitionSettings = `-- name: GetReacquisitionSettings :one - -SELECT id, enabled, grace_hours, max_per_pass FROM reacquisition_settings WHERE id = true -` - -// Re-acquisition of missing files. -// The unit is the album: an album whose files went missing becomes a want for -// its release group, and the search schedule looks for it. -func (q *Queries) GetReacquisitionSettings(ctx context.Context) (ReacquisitionSetting, error) { - row := q.db.QueryRow(ctx, getReacquisitionSettings) - var i ReacquisitionSetting - err := row.Scan( - &i.ID, - &i.Enabled, - &i.GraceHours, - &i.MaxPerPass, - ) - return i, err -} - -const getWantsForAlbums = `-- name: GetWantsForAlbums :many -SELECT a.id AS album_id, w.id AS want_id, w.wanted_at, w.fulfilled_at - FROM albums a - JOIN wants w ON w.album_id = a.id OR w.release_group_mbid = a.release_group_mbid - WHERE a.id = ANY($1::uuid[]) - ORDER BY w.wanted_at DESC -` - -type GetWantsForAlbumsRow struct { - AlbumID pgtype.UUID - WantID pgtype.UUID - WantedAt pgtype.Timestamptz - FulfilledAt pgtype.Timestamptz -} - -// What the wanted list says about each album on the missing-files page. -func (q *Queries) GetWantsForAlbums(ctx context.Context, albumIds []pgtype.UUID) ([]GetWantsForAlbumsRow, error) { - rows, err := q.db.Query(ctx, getWantsForAlbums, albumIds) - if err != nil { - return nil, err - } - defer rows.Close() - var items []GetWantsForAlbumsRow - for rows.Next() { - var i GetWantsForAlbumsRow - if err := rows.Scan( - &i.AlbumID, - &i.WantID, - &i.WantedAt, - &i.FulfilledAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listAlbumsDueReacquisition = `-- name: ListAlbumsDueReacquisition :many -SELECT albums.id AS album_id, - albums.title AS album_title, - albums.mbid AS album_mbid, - albums.release_group_mbid AS album_release_group_mbid, - artists.name AS artist_name, - artists.mbid AS artist_mbid, - COUNT(tracks.id)::bigint AS missing_track_count, - MAX(tracks.missing_since)::timestamptz AS last_missing_since - FROM albums - JOIN artists ON artists.id = albums.artist_id - JOIN tracks ON tracks.album_id = albums.id - WHERE tracks.missing_since IS NOT NULL - AND tracks.missing_since <= now() - make_interval(hours => $1::int) - AND (albums.mbid IS NOT NULL OR albums.release_group_mbid IS NOT NULL) - AND artists.mbid IS NOT NULL - GROUP BY albums.id, albums.title, albums.mbid, albums.release_group_mbid, - artists.name, artists.mbid -HAVING EXISTS ( - SELECT 1 FROM wants w - WHERE w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid) - AND NOT EXISTS ( - SELECT 1 FROM wants w - WHERE (w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid) - AND (w.fulfilled_at IS NULL OR w.fulfilled_at > MAX(tracks.missing_since))) - ORDER BY MIN(tracks.missing_since), albums.sort_title - LIMIT $2 -` - -type ListAlbumsDueReacquisitionParams struct { - GraceHours int32 - PageLimit int32 -} - -type ListAlbumsDueReacquisitionRow struct { - AlbumID pgtype.UUID - AlbumTitle string - AlbumMbid *string - AlbumReleaseGroupMbid *string - ArtistName string - ArtistMbid *string - MissingTrackCount int64 - LastMissingSince pgtype.Timestamptz -} - -// The sweeper's selection. An album qualifies when: -// -// - it still has at least one track whose file has been missing longer than -// the grace window. Measured on missing_since, which reconcile never -// re-stamps, so it is a genuine "gone since" clock; -// - MusicBrainz can name it: the artist has an MBID, and the album a -// release MBID or a release group. The release MBID is only ever used to -// find the group, and an album matched to a group may carry no release -// id. Albums failing this are counted separately -// (CountAlbumsMissingWithoutMbid); -// - it is on the wanted list: an album taken off the list, or -// dropped into the library by hand, is not fetched back; -// - no want already covers it: none open, and none held since its files -// went missing. A want held after the loss means the library has a full -// copy despite the missing rows, so asking again would loop. -func (q *Queries) ListAlbumsDueReacquisition(ctx context.Context, arg ListAlbumsDueReacquisitionParams) ([]ListAlbumsDueReacquisitionRow, error) { - rows, err := q.db.Query(ctx, listAlbumsDueReacquisition, arg.GraceHours, arg.PageLimit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListAlbumsDueReacquisitionRow - for rows.Next() { - var i ListAlbumsDueReacquisitionRow - if err := rows.Scan( - &i.AlbumID, - &i.AlbumTitle, - &i.AlbumMbid, - &i.AlbumReleaseGroupMbid, - &i.ArtistName, - &i.ArtistMbid, - &i.MissingTrackCount, - &i.LastMissingSince, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const updateReacquisitionSettings = `-- name: UpdateReacquisitionSettings :one -UPDATE reacquisition_settings - SET enabled = $1, - grace_hours = $2, - max_per_pass = $3 - WHERE id = true -RETURNING id, enabled, grace_hours, max_per_pass -` - -type UpdateReacquisitionSettingsParams struct { - Enabled bool - GraceHours int32 - MaxPerPass int32 -} - -// Whole-row write from the admin card; the CHECKs in migration 0056 are the -// validation, so a bad value fails loudly rather than being clamped silently. -func (q *Queries) UpdateReacquisitionSettings(ctx context.Context, arg UpdateReacquisitionSettingsParams) (ReacquisitionSetting, error) { - row := q.db.QueryRow(ctx, updateReacquisitionSettings, arg.Enabled, arg.GraceHours, arg.MaxPerPass) - var i ReacquisitionSetting - err := row.Scan( - &i.ID, - &i.Enabled, - &i.GraceHours, - &i.MaxPerPass, - ) - return i, err -} - -const wantMissingAlbum = `-- name: WantMissingAlbum :one -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id) -VALUES ($1, $2, $3, - $4, 'missing', $5) -ON CONFLICT (release_group_mbid) DO UPDATE - SET reason = 'missing', - album_id = EXCLUDED.album_id, - wanted_at = now(), - fulfilled_at = NULL, - updated_at = now() - WHERE wants.fulfilled_at IS NOT NULL -RETURNING id, release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date, reason, album_id, created_by, wanted_at, fulfilled_at, created_at, updated_at, searched_at, search_outcome, search_considered, best_release, best_verdict, search_error, upgrade, held_tier, held_quality, upgrade_checked_at -` - -type WantMissingAlbumParams struct { - ReleaseGroupMbid string - ArtistMbid string - ArtistName string - Title string - AlbumID pgtype.UUID -} - -// Records an album with missing files as wanted. A held want for the same -// group is reopened; an open one is left as it is, and no row comes back. -func (q *Queries) WantMissingAlbum(ctx context.Context, arg WantMissingAlbumParams) (Want, error) { - row := q.db.QueryRow(ctx, wantMissingAlbum, - arg.ReleaseGroupMbid, - arg.ArtistMbid, - arg.ArtistName, - arg.Title, - arg.AlbumID, - ) - var i Want - err := row.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.Title, - &i.PrimaryType, - &i.FirstReleaseDate, - &i.Reason, - &i.AlbumID, - &i.CreatedBy, - &i.WantedAt, - &i.FulfilledAt, - &i.CreatedAt, - &i.UpdatedAt, - &i.SearchedAt, - &i.SearchOutcome, - &i.SearchConsidered, - &i.BestRelease, - &i.BestVerdict, - &i.SearchError, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.UpgradeCheckedAt, - ) - return i, err -} diff --git a/internal/db/dbq/recommendation.sql.go b/internal/db/dbq/recommendation.sql.go index 80c8aede..495529e0 100644 --- a/internal/db/dbq/recommendation.sql.go +++ b/internal/db/dbq/recommendation.sql.go @@ -208,7 +208,7 @@ WITH plays AS ( WHERE user_id = $2 AND was_skipped = false GROUP BY track_id ) -SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit, albums.title AS album_title, artists.name AS artist_name FROM plays p @@ -276,6 +276,9 @@ func (q *Queries) ListMostPlayedTracksForArtist(ctx context.Context, arg ListMos &i.Track.SourceVerdict, &i.Track.SourceVerdictAt, &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, &i.AlbumTitle, &i.ArtistName, ); err != nil { @@ -296,7 +299,7 @@ WITH plays AS ( WHERE user_id = $1 AND was_skipped = false GROUP BY track_id ) -SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit, albums.title AS album_title, artists.name AS artist_name FROM plays p @@ -366,6 +369,9 @@ func (q *Queries) ListMostPlayedTracksForUser(ctx context.Context, arg ListMostP &i.Track.SourceVerdict, &i.Track.SourceVerdictAt, &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, &i.AlbumTitle, &i.ArtistName, ); err != nil { @@ -380,7 +386,7 @@ func (q *Queries) ListMostPlayedTracksForUser(ctx context.Context, arg ListMostP } const listRediscoverAlbumsFallbackForUser = `-- name: ListRediscoverAlbumsFallbackForUser :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM general_likes_albums gla JOIN albums ON albums.id = gla.album_id JOIN artists ON artists.id = albums.artist_id @@ -429,6 +435,7 @@ func (q *Queries) ListRediscoverAlbumsFallbackForUser(ctx context.Context, arg L &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err @@ -470,7 +477,7 @@ eligible AS ( HAVING COALESCE(max(pe.started_at), '1970-01-01'::timestamptz) < now() - interval '14 days' ) -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM eligible e JOIN albums ON albums.id = e.album_id JOIN artists ON artists.id = albums.artist_id @@ -522,6 +529,7 @@ func (q *Queries) ListRediscoverAlbumsForUser(ctx context.Context, arg ListRedis &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err @@ -705,7 +713,7 @@ func (q *Queries) ListRediscoverArtistsForUser(ctx context.Context, arg ListRedi const loadRadioCandidates = `-- name: LoadRadioCandidates :many SELECT - t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, + t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit, (l.user_id IS NOT NULL)::bool AS is_liked, pe.last_played_at::timestamptz AS last_played_at, pe.play_count, @@ -792,6 +800,9 @@ func (q *Queries) LoadRadioCandidates(ctx context.Context, arg LoadRadioCandidat &i.Track.SourceVerdict, &i.Track.SourceVerdictAt, &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, &i.IsLiked, &i.LastPlayedAt, &i.PlayCount, @@ -952,7 +963,7 @@ random_fill AS ( LIMIT $9 ) SELECT - t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, + t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit, (l.user_id IS NOT NULL)::bool AS is_liked, pe.last_played_at::timestamptz AS last_played_at, pe.play_count, @@ -1096,6 +1107,9 @@ func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandid &i.Track.SourceVerdict, &i.Track.SourceVerdictAt, &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, &i.IsLiked, &i.LastPlayedAt, &i.PlayCount, @@ -1112,152 +1126,3 @@ func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandid } return items, nil } - -const suggestArtistsForUser = `-- name: SuggestArtistsForUser :many -WITH artist_plays AS ( - -- Completed plays only: counting every play_event would make skipping an - -- artist repeatedly INCREASE its signal and push more of its neighbours - -- at the user. - SELECT t.artist_id, count(*)::bigint AS play_count - FROM play_events pe - JOIN tracks t ON t.id = pe.track_id - WHERE pe.user_id = $1 AND pe.was_skipped = false - GROUP BY t.artist_id -), -profile_seeds AS ( - SELECT tpa.artist_id, tpa.weight AS raw_signal - FROM taste_profile_artists tpa - WHERE tpa.user_id = $1 AND tpa.weight > 0 -), -fallback_seeds AS ( - SELECT a.id AS artist_id, - 5.0 * (CASE WHEN gla.artist_id IS NOT NULL THEN 1 ELSE 0 END) - + COALESCE(SUM(EXP(- EXTRACT(epoch FROM now() - pe.started_at) / ($2::float8 * 86400.0))), 0) - AS raw_signal - FROM artists a - LEFT JOIN general_likes_artists gla ON gla.artist_id = a.id AND gla.user_id = $1 - LEFT JOIN tracks t ON t.artist_id = a.id - LEFT JOIN play_events pe - ON pe.track_id = t.id AND pe.user_id = $1 AND pe.was_skipped = false - WHERE (gla.artist_id IS NOT NULL OR pe.id IS NOT NULL) - AND NOT EXISTS (SELECT 1 FROM profile_seeds) - GROUP BY a.id, gla.artist_id -), -seeds AS ( - SELECT s.artist_id, - ln(1.0 + s.raw_signal) AS signal, - (gla.artist_id IS NOT NULL) AS is_liked, - COALESCE(ap.play_count, 0)::bigint AS play_count - FROM ( - SELECT artist_id, raw_signal FROM profile_seeds - UNION ALL - SELECT artist_id, raw_signal FROM fallback_seeds - ) s - LEFT JOIN general_likes_artists gla - ON gla.artist_id = s.artist_id AND gla.user_id = $1 - LEFT JOIN artist_plays ap ON ap.artist_id = s.artist_id - WHERE s.raw_signal > 0 -), -contributions AS ( - SELECT u.candidate_mbid, - u.candidate_name, - seeds.artist_id AS seed_id, - seeds.is_liked, - seeds.play_count, - seeds.signal * u.score AS contribution - FROM artist_similarity_unmatched u - JOIN seeds ON seeds.artist_id = u.seed_artist_id - WHERE NOT EXISTS (SELECT 1 FROM artists WHERE mbid = u.candidate_mbid) - AND NOT EXISTS ( - SELECT 1 FROM requests r - WHERE r.user_id = $1 - AND r.artist_mbid = u.candidate_mbid - AND r.status NOT IN ('rejected', 'failed') - ) - -- Snoozed by this user and not yet expired. Time-boxed and - -- per-user: the candidate returns on its own once snoozed_until - -- passes, and stays visible to everyone else meanwhile. Deliberately - -- filtered at the candidate stage, NOT folded into the score — a - -- snooze carries no opinion about the music, so it must not become a - -- ranking signal. - AND NOT EXISTS ( - SELECT 1 FROM suggestion_snoozes s - WHERE s.user_id = $1 - AND s.candidate_mbid = u.candidate_mbid - AND s.snoozed_until > now() - ) -) -SELECT candidate_mbid, - candidate_name, - SUM(contribution)::float8 AS total_score, - ((array_agg(seed_id ORDER BY contribution DESC))[1:3])::uuid[] AS top_seed_ids, - ((array_agg(contribution ORDER BY contribution DESC))[1:3])::float8[] AS top_contributions, - ((array_agg(is_liked ORDER BY contribution DESC))[1:3])::boolean[] AS top_is_liked, - ((array_agg(play_count ORDER BY contribution DESC))[1:3])::bigint[] AS top_play_counts -FROM contributions -GROUP BY candidate_mbid, candidate_name -ORDER BY total_score DESC -LIMIT $3 -` - -type SuggestArtistsForUserParams struct { - UserID pgtype.UUID - Column2 float64 - Limit int32 -} - -type SuggestArtistsForUserRow struct { - CandidateMbid string - CandidateName string - TotalScore float64 - TopSeedIds []pgtype.UUID - TopContributions []float64 - TopIsLiked []bool - TopPlayCounts []int64 -} - -// Per-user artist suggestions ranked by taste signal x similarity, projected -// through artist_similarity_unmatched (out-of-library candidates only). -// -// Seeds are TIERED so the surface never empties: -// -// tier 1 - taste_profile_artists.weight: engagement-graded, time-decayed and -// SIGNED by internal/taste, so an artist the user has drifted away -// from stops contributing instead of accumulating forever. -// tier 2 - likes + completed plays, used ONLY when the profile has no rows -// (new account, or before the first daily recompute). -// -// The signal is log-damped: contribution is signal x similarity, and an -// undamped sum would let one heavily-played artist's neighbours take every -// slot -- entrenching harder the MORE the user listened. -// -// Candidates already in the library, already requested and not terminal, or -// snoozed by this user, are excluded. $1=user_id, $2=half_life_days (tier 2 -// decay), $3=limit. -func (q *Queries) SuggestArtistsForUser(ctx context.Context, arg SuggestArtistsForUserParams) ([]SuggestArtistsForUserRow, error) { - rows, err := q.db.Query(ctx, suggestArtistsForUser, arg.UserID, arg.Column2, arg.Limit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []SuggestArtistsForUserRow - for rows.Next() { - var i SuggestArtistsForUserRow - if err := rows.Scan( - &i.CandidateMbid, - &i.CandidateName, - &i.TotalScore, - &i.TopSeedIds, - &i.TopContributions, - &i.TopIsLiked, - &i.TopPlayCounts, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} diff --git a/internal/db/dbq/recommendation_tuning.sql.go b/internal/db/dbq/recommendation_tuning.sql.go index 1e1f76c3..84cb968a 100644 --- a/internal/db/dbq/recommendation_tuning.sql.go +++ b/internal/db/dbq/recommendation_tuning.sql.go @@ -9,22 +9,6 @@ import ( "context" ) -const getDiscoverTuning = `-- name: GetDiscoverTuning :one -SELECT singleton, tag_overlap_weight, snooze_days, updated_at FROM discover_tuning WHERE singleton = true -` - -func (q *Queries) GetDiscoverTuning(ctx context.Context) (DiscoverTuning, error) { - row := q.db.QueryRow(ctx, getDiscoverTuning) - var i DiscoverTuning - err := row.Scan( - &i.Singleton, - &i.TagOverlapWeight, - &i.SnoozeDays, - &i.UpdatedAt, - ) - return i, err -} - const getTasteTuning = `-- name: GetTasteTuning :one SELECT singleton, half_life_days, engagement_hard_skip, engagement_neutral, engagement_full, updated_at, enriched_tag_scale, era_scale, mood_scale FROM taste_tuning WHERE singleton = true ` @@ -134,32 +118,6 @@ func (q *Queries) ListWeightProfiles(ctx context.Context) ([]RecommendationWeigh return items, nil } -const updateDiscoverTuning = `-- name: UpdateDiscoverTuning :one -UPDATE discover_tuning - SET tag_overlap_weight = $1, - snooze_days = $2, - updated_at = now() - WHERE singleton = true -RETURNING singleton, tag_overlap_weight, snooze_days, updated_at -` - -type UpdateDiscoverTuningParams struct { - TagOverlapWeight float64 - SnoozeDays float64 -} - -func (q *Queries) UpdateDiscoverTuning(ctx context.Context, arg UpdateDiscoverTuningParams) (DiscoverTuning, error) { - row := q.db.QueryRow(ctx, updateDiscoverTuning, arg.TagOverlapWeight, arg.SnoozeDays) - var i DiscoverTuning - err := row.Scan( - &i.Singleton, - &i.TagOverlapWeight, - &i.SnoozeDays, - &i.UpdatedAt, - ) - return i, err -} - const updateTasteTuning = `-- name: UpdateTasteTuning :one UPDATE taste_tuning SET half_life_days = $1, @@ -268,24 +226,6 @@ func (q *Queries) UpdateWeightProfile(ctx context.Context, arg UpdateWeightProfi return i, err } -const upsertDiscoverTuningDefaults = `-- name: UpsertDiscoverTuningDefaults :exec -INSERT INTO discover_tuning (singleton, tag_overlap_weight, snooze_days) -VALUES (true, $1, $2) -ON CONFLICT (singleton) DO NOTHING -` - -type UpsertDiscoverTuningDefaultsParams struct { - TagOverlapWeight float64 - SnoozeDays float64 -} - -// Boot reconcile for the Discover scope. Never overwrites -// admin-tuned values, same contract as the other two. -func (q *Queries) UpsertDiscoverTuningDefaults(ctx context.Context, arg UpsertDiscoverTuningDefaultsParams) error { - _, err := q.db.Exec(ctx, upsertDiscoverTuningDefaults, arg.TagOverlapWeight, arg.SnoozeDays) - return err -} - const upsertTasteTuningDefaults = `-- name: UpsertTasteTuningDefaults :exec INSERT INTO taste_tuning ( singleton, half_life_days, engagement_hard_skip, diff --git a/internal/db/dbq/registration_settings.sql.go b/internal/db/dbq/registration_settings.sql.go deleted file mode 100644 index f57b2e2e..00000000 --- a/internal/db/dbq/registration_settings.sql.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: registration_settings.sql - -package dbq - -import ( - "context" -) - -const getRegistrationMode = `-- name: GetRegistrationMode :one -SELECT mode FROM registration_settings WHERE id = true -` - -func (q *Queries) GetRegistrationMode(ctx context.Context) (string, error) { - row := q.db.QueryRow(ctx, getRegistrationMode) - var mode string - err := row.Scan(&mode) - return mode, err -} - -const setRegistrationMode = `-- name: SetRegistrationMode :exec -UPDATE registration_settings SET mode = $1 WHERE id = true -` - -func (q *Queries) SetRegistrationMode(ctx context.Context, mode string) error { - _, err := q.db.Exec(ctx, setRegistrationMode, mode) - return err -} diff --git a/internal/db/dbq/requests.sql.go b/internal/db/dbq/requests.sql.go deleted file mode 100644 index c2e2b6d1..00000000 --- a/internal/db/dbq/requests.sql.go +++ /dev/null @@ -1,528 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: requests.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const approveRequest = `-- name: ApproveRequest :one -UPDATE requests - SET status = 'approved', - decided_at = now(), - decided_by = $2, - updated_at = now() - WHERE id = $1 AND status = 'pending' - RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at -` - -type ApproveRequestParams struct { - ID pgtype.UUID - DecidedBy pgtype.UUID -} - -func (q *Queries) ApproveRequest(ctx context.Context, arg ApproveRequestParams) (Request, error) { - row := q.db.QueryRow(ctx, approveRequest, arg.ID, arg.DecidedBy) - var i Request - err := row.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ) - return i, err -} - -const cancelRequest = `-- name: CancelRequest :one -UPDATE requests - SET status = 'rejected', - notes = 'cancelled by user', - decided_at = now(), - decided_by = $2, - updated_at = now() - WHERE id = $1 AND user_id = $2 AND status = 'pending' - RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at -` - -type CancelRequestParams struct { - ID pgtype.UUID - DecidedBy pgtype.UUID -} - -// $2 serves as both the ownership guard (user_id = $2) and the -// decided_by audit field. The generated parameter struct names it -// DecidedBy — callers must pass the cancelling user's UUID, and -// a wrong UUID will silently no-op (zero rows updated) rather than -// erroring at the SQL layer. -func (q *Queries) CancelRequest(ctx context.Context, arg CancelRequestParams) (Request, error) { - row := q.db.QueryRow(ctx, cancelRequest, arg.ID, arg.DecidedBy) - var i Request - err := row.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ) - return i, err -} - -const completeRequest = `-- name: CompleteRequest :one -UPDATE requests - SET status = 'completed', - matched_track_id = $2, - matched_album_id = $3, - matched_artist_id = $4, - completed_at = now(), - updated_at = now() - WHERE id = $1 AND status = 'approved' - RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at -` - -type CompleteRequestParams struct { - ID pgtype.UUID - MatchedTrackID pgtype.UUID - MatchedAlbumID pgtype.UUID - MatchedArtistID pgtype.UUID -} - -// Reconciler transitions an approved request to completed when its -// target track/album/artist has appeared in the library. Callers -// should set ONLY the matched_*_id corresponding to the request's -// kind and pass pgtype.UUID{} (Valid: false) for the others — -// per-kind one-of-three is the contract, NULL for the others -// preserves auditability if the matched row is later evicted. -func (q *Queries) CompleteRequest(ctx context.Context, arg CompleteRequestParams) (Request, error) { - row := q.db.QueryRow(ctx, completeRequest, - arg.ID, - arg.MatchedTrackID, - arg.MatchedAlbumID, - arg.MatchedArtistID, - ) - var i Request - err := row.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ) - return i, err -} - -const createRequest = `-- name: CreateRequest :one -INSERT INTO requests ( - user_id, kind, - artist_mbid, album_mbid, track_mbid, - artist_name, album_title, track_title -) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) -RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at -` - -type CreateRequestParams struct { - UserID pgtype.UUID - Kind RequestKind - ArtistMbid string - AlbumMbid *string - TrackMbid *string - ArtistName string - AlbumTitle *string - TrackTitle *string -} - -func (q *Queries) CreateRequest(ctx context.Context, arg CreateRequestParams) (Request, error) { - row := q.db.QueryRow(ctx, createRequest, - arg.UserID, - arg.Kind, - arg.ArtistMbid, - arg.AlbumMbid, - arg.TrackMbid, - arg.ArtistName, - arg.AlbumTitle, - arg.TrackTitle, - ) - var i Request - err := row.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ) - return i, err -} - -const getNonTerminalRequestForMBID = `-- name: GetNonTerminalRequestForMBID :one -SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests - WHERE status IN ('pending', 'approved', 'completed') - AND ((kind = 'artist' AND artist_mbid = $1) - OR (kind = 'album' AND album_mbid = $1) - OR (kind = 'track' AND track_mbid = $1)) - ORDER BY requested_at ASC - LIMIT 1 -` - -// Returns the oldest non-terminal (pending/approved/completed) request -// whose own-kind MBID matches @mbid, or pgx.ErrNoRows when none. Create() -// uses this to dedupe: a re-request for something already in flight -// returns the existing row instead of inserting a duplicate. -func (q *Queries) GetNonTerminalRequestForMBID(ctx context.Context, mbid string) (Request, error) { - row := q.db.QueryRow(ctx, getNonTerminalRequestForMBID, mbid) - var i Request - err := row.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ) - return i, err -} - -const getRequestByID = `-- name: GetRequestByID :one -SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests WHERE id = $1 -` - -func (q *Queries) GetRequestByID(ctx context.Context, id pgtype.UUID) (Request, error) { - row := q.db.QueryRow(ctx, getRequestByID, id) - var i Request - err := row.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ) - return i, err -} - -const hasNonTerminalRequestForMBID = `-- name: HasNonTerminalRequestForMBID :one -SELECT (EXISTS ( - SELECT 1 FROM requests r - WHERE r.status IN ('pending', 'approved', 'completed') - AND ((r.kind = 'artist' AND r.artist_mbid = $1) - OR (r.kind = 'album' AND r.album_mbid = $1) - OR (r.kind = 'track' AND r.track_mbid = $1)) -) OR EXISTS ( - SELECT 1 FROM wants w WHERE w.release_group_mbid = $1 AND w.fulfilled_at IS NULL -) OR EXISTS ( - SELECT 1 FROM follows f WHERE f.artist_mbid = $1 -))::bool AS requested -` - -// Whether something is already on its way: a pending, approved or completed -// request at the given level, an open want for the release group, or a -// follow of the artist. Sets the `requested` flag on catalogue search. -// Terminal-status (rejected, failed) requests do not count. MBIDs are unique -// per entity type, so checking one id against every column cannot -// false-match. -func (q *Queries) HasNonTerminalRequestForMBID(ctx context.Context, mbid string) (bool, error) { - row := q.db.QueryRow(ctx, hasNonTerminalRequestForMBID, mbid) - var requested bool - err := row.Scan(&requested) - return requested, err -} - -const listApprovedRequestsForReconcile = `-- name: ListApprovedRequestsForReconcile :many -SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests -WHERE status = 'approved' -ORDER BY decided_at ASC -LIMIT $1 -` - -func (q *Queries) ListApprovedRequestsForReconcile(ctx context.Context, limit int32) ([]Request, error) { - rows, err := q.db.Query(ctx, listApprovedRequestsForReconcile, limit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []Request - for rows.Next() { - var i Request - if err := rows.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listRequestsByStatus = `-- name: ListRequestsByStatus :many -SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests -WHERE status = $1 -ORDER BY requested_at DESC -LIMIT $2 -` - -type ListRequestsByStatusParams struct { - Status RequestStatus - Limit int32 -} - -func (q *Queries) ListRequestsByStatus(ctx context.Context, arg ListRequestsByStatusParams) ([]Request, error) { - rows, err := q.db.Query(ctx, listRequestsByStatus, arg.Status, arg.Limit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []Request - for rows.Next() { - var i Request - if err := rows.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listRequestsForUser = `-- name: ListRequestsForUser :many -SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests -WHERE user_id = $1 -ORDER BY requested_at DESC -LIMIT $2 -` - -type ListRequestsForUserParams struct { - UserID pgtype.UUID - Limit int32 -} - -func (q *Queries) ListRequestsForUser(ctx context.Context, arg ListRequestsForUserParams) ([]Request, error) { - rows, err := q.db.Query(ctx, listRequestsForUser, arg.UserID, arg.Limit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []Request - for rows.Next() { - var i Request - if err := rows.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const rejectRequest = `-- name: RejectRequest :one -UPDATE requests - SET status = 'rejected', - notes = $2, - decided_at = now(), - decided_by = $3, - updated_at = now() - WHERE id = $1 AND status = 'pending' - RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at -` - -type RejectRequestParams struct { - ID pgtype.UUID - Notes *string - DecidedBy pgtype.UUID -} - -func (q *Queries) RejectRequest(ctx context.Context, arg RejectRequestParams) (Request, error) { - row := q.db.QueryRow(ctx, rejectRequest, arg.ID, arg.Notes, arg.DecidedBy) - var i Request - err := row.Scan( - &i.ID, - &i.UserID, - &i.Status, - &i.Kind, - &i.ArtistMbid, - &i.AlbumMbid, - &i.TrackMbid, - &i.ArtistName, - &i.AlbumTitle, - &i.TrackTitle, - &i.DecidedAt, - &i.DecidedBy, - &i.Notes, - &i.CompletedAt, - &i.MatchedTrackID, - &i.MatchedAlbumID, - &i.MatchedArtistID, - &i.RequestedAt, - &i.UpdatedAt, - ) - return i, err -} - -const repointRequestsAlbumMbid = `-- name: RepointRequestsAlbumMbid :exec -UPDATE requests - SET album_mbid = $1, - updated_at = now() - WHERE album_mbid = $2 -` - -type RepointRequestsAlbumMbidParams struct { - NewMbid *string - OldMbid *string -} - -// A want moved from a release id to its group takes the requests -// that name it along, so the reconciler finds it. -func (q *Queries) RepointRequestsAlbumMbid(ctx context.Context, arg RepointRequestsAlbumMbidParams) error { - _, err := q.db.Exec(ctx, repointRequestsAlbumMbid, arg.NewMbid, arg.OldMbid) - return err -} diff --git a/internal/db/dbq/scan_runs.sql.go b/internal/db/dbq/scan_runs.sql.go index 45727164..340e98b1 100644 --- a/internal/db/dbq/scan_runs.sql.go +++ b/internal/db/dbq/scan_runs.sql.go @@ -11,6 +11,24 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const failUnfinishedScanRuns = `-- name: FailUnfinishedScanRuns :execrows +UPDATE scan_runs + SET finished_at = now(), + error_message = 'The server stopped while the scan was running.' + WHERE finished_at IS NULL +` + +// At startup no scan can be running yet, so a row still unfinished was cut +// off when the server last stopped. Closing it keeps it from reading as a +// scan in progress, which would block saving library folders. +func (q *Queries) FailUnfinishedScanRuns(ctx context.Context) (int64, error) { + result, err := q.db.Exec(ctx, failUnfinishedScanRuns) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const finishScanRun = `-- name: FinishScanRun :exec UPDATE scan_runs SET finished_at = now(), diff --git a/internal/db/dbq/scrobble.sql.go b/internal/db/dbq/scrobble.sql.go index 5a538e5b..6fc89dff 100644 --- a/internal/db/dbq/scrobble.sql.go +++ b/internal/db/dbq/scrobble.sql.go @@ -47,7 +47,8 @@ SELECT t.mbid AS track_mbid, al.title AS album_title, al.mbid AS album_mbid, - ar.name AS artist_name, + -- The full credit: ListenBrainz and Last.fm match "A feat. B" as written. + COALESCE(t.artist_credit, ar.name) AS artist_name, ar.mbid AS artist_mbid FROM scrobble_queue sq JOIN users u ON u.id = sq.user_id diff --git a/internal/db/dbq/search.sql.go b/internal/db/dbq/search.sql.go deleted file mode 100644 index 3e5986e1..00000000 --- a/internal/db/dbq/search.sql.go +++ /dev/null @@ -1,680 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: search.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const blockRelease = `-- name: BlockRelease :exec -INSERT INTO release_blocks (info_hash, name, reason, detail, want_id, blocked_by, expires_at) -VALUES ($1, $2, $3, $4, - $5, $6, $7) -ON CONFLICT (info_hash) DO UPDATE - SET reason = EXCLUDED.reason, detail = EXCLUDED.detail, blocked_at = now(), - expires_at = EXCLUDED.expires_at, blocked_by = EXCLUDED.blocked_by - WHERE release_blocks.expires_at IS NOT NULL OR EXCLUDED.expires_at IS NULL -` - -type BlockReleaseParams struct { - InfoHash string - Name string - Reason string - Detail string - WantID pgtype.UUID - BlockedBy pgtype.UUID - ExpiresAt pgtype.Timestamptz -} - -// A release set aside. expires_at NULL is for good. A block for good is never -// shortened by a timed one: only a timed block, or another for good, is -// replaced. -func (q *Queries) BlockRelease(ctx context.Context, arg BlockReleaseParams) error { - _, err := q.db.Exec(ctx, blockRelease, - arg.InfoHash, - arg.Name, - arg.Reason, - arg.Detail, - arg.WantID, - arg.BlockedBy, - arg.ExpiresAt, - ) - return err -} - -const deleteWantCandidates = `-- name: DeleteWantCandidates :exec -DELETE FROM want_candidates WHERE want_id = $1 -` - -func (q *Queries) DeleteWantCandidates(ctx context.Context, wantID pgtype.UUID) error { - _, err := q.db.Exec(ctx, deleteWantCandidates, wantID) - return err -} - -const editionTrackSpan = `-- name: EditionTrackSpan :one -SELECT COALESCE(MIN(track_count) FILTER (WHERE status = 'Official'), MIN(track_count), 0)::int AS min_tracks, - COALESCE(MAX(track_count), 0)::int AS max_tracks - FROM mb_releases - WHERE release_group_mbid = $1 AND track_count > 0 -` - -type EditionTrackSpanRow struct { - MinTracks int32 - MaxTracks int32 -} - -// The fewest tracks an official edition of the group has (any edition when -// none is official), and the most any has. Zero when none is catalogued. -func (q *Queries) EditionTrackSpan(ctx context.Context, releaseGroupMbid string) (EditionTrackSpanRow, error) { - row := q.db.QueryRow(ctx, editionTrackSpan, releaseGroupMbid) - var i EditionTrackSpanRow - err := row.Scan(&i.MinTracks, &i.MaxTracks) - return i, err -} - -const endGrab = `-- name: EndGrab :exec -UPDATE grabs - SET ended_at = now(), end_reason = $1, end_detail = $2 - WHERE id = $3 AND ended_at IS NULL -` - -type EndGrabParams struct { - EndReason string - EndDetail string - ID pgtype.UUID -} - -func (q *Queries) EndGrab(ctx context.Context, arg EndGrabParams) error { - _, err := q.db.Exec(ctx, endGrab, arg.EndReason, arg.EndDetail, arg.ID) - return err -} - -const getAcquisitionSettings = `-- name: GetAcquisitionSettings :one - -SELECT id, auto_grab, search_interval_hours, allowed_qualities, last_pass_at, last_pass, updated_at, import_root, seed_ratio, seed_days, stall_hours, library_listing_started_at, library_listed_at, library_unlisted, upgrade_until FROM acquisition_settings WHERE id = true -` - -// Searching for wants and grabbing releases. -func (q *Queries) GetAcquisitionSettings(ctx context.Context) (AcquisitionSetting, error) { - row := q.db.QueryRow(ctx, getAcquisitionSettings) - var i AcquisitionSetting - err := row.Scan( - &i.ID, - &i.AutoGrab, - &i.SearchIntervalHours, - &i.AllowedQualities, - &i.LastPassAt, - &i.LastPass, - &i.UpdatedAt, - &i.ImportRoot, - &i.SeedRatio, - &i.SeedDays, - &i.StallHours, - &i.LibraryListingStartedAt, - &i.LibraryListedAt, - &i.LibraryUnlisted, - &i.UpgradeUntil, - ) - return i, err -} - -const getLiveGrab = `-- name: GetLiveGrab :one -SELECT id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at FROM grabs WHERE want_id = $1 AND ended_at IS NULL -` - -func (q *Queries) GetLiveGrab(ctx context.Context, wantID pgtype.UUID) (Grab, error) { - row := q.db.QueryRow(ctx, getLiveGrab, wantID) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const getWantCandidate = `-- name: GetWantCandidate :one -SELECT want_id, key, name, info_hash, indexer, source, size_bytes, seeders, files_count, format, quality, year, verdict, reason, reasons, folded_from, rank, searched_at FROM want_candidates WHERE want_id = $1 AND key = $2 -` - -type GetWantCandidateParams struct { - WantID pgtype.UUID - Key string -} - -func (q *Queries) GetWantCandidate(ctx context.Context, arg GetWantCandidateParams) (WantCandidate, error) { - row := q.db.QueryRow(ctx, getWantCandidate, arg.WantID, arg.Key) - var i WantCandidate - err := row.Scan( - &i.WantID, - &i.Key, - &i.Name, - &i.InfoHash, - &i.Indexer, - &i.Source, - &i.SizeBytes, - &i.Seeders, - &i.FilesCount, - &i.Format, - &i.Quality, - &i.Year, - &i.Verdict, - &i.Reason, - &i.Reasons, - &i.FoldedFrom, - &i.Rank, - &i.SearchedAt, - ) - return i, err -} - -const getWantForSearch = `-- name: GetWantForSearch :one -SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.reason, w.fulfilled_at, - w.upgrade, w.held_tier, w.held_quality, w.album_id, - COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type, - COALESCE(g.secondary_types, '{}')::text[] AS secondary_types, - COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date - FROM wants w - LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid - WHERE w.id = $1 -` - -type GetWantForSearchRow struct { - ID pgtype.UUID - ReleaseGroupMbid string - ArtistMbid string - ArtistName string - Title string - Reason string - FulfilledAt pgtype.Timestamptz - Upgrade string - HeldTier string - HeldQuality string - AlbumID pgtype.UUID - PrimaryType string - SecondaryTypes []string - FirstReleaseDate string -} - -func (q *Queries) GetWantForSearch(ctx context.Context, id pgtype.UUID) (GetWantForSearchRow, error) { - row := q.db.QueryRow(ctx, getWantForSearch, id) - var i GetWantForSearchRow - err := row.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.Title, - &i.Reason, - &i.FulfilledAt, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.AlbumID, - &i.PrimaryType, - &i.SecondaryTypes, - &i.FirstReleaseDate, - ) - return i, err -} - -const insertGrab = `-- name: InsertGrab :one -INSERT INTO grabs (want_id, info_hash, name, key, indexer, source, client, save_path, quality, - origin, forced, grabbed_by) -VALUES ($1, $2, $3, $4, $5, - $6, $7, $8, $9, - $10, $11, $12) -RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at -` - -type InsertGrabParams struct { - WantID pgtype.UUID - InfoHash string - Name string - Key string - Indexer string - Source string - Client string - SavePath string - Quality string - Origin string - Forced bool - GrabbedBy pgtype.UUID -} - -func (q *Queries) InsertGrab(ctx context.Context, arg InsertGrabParams) (Grab, error) { - row := q.db.QueryRow(ctx, insertGrab, - arg.WantID, - arg.InfoHash, - arg.Name, - arg.Key, - arg.Indexer, - arg.Source, - arg.Client, - arg.SavePath, - arg.Quality, - arg.Origin, - arg.Forced, - arg.GrabbedBy, - ) - var i Grab - err := row.Scan( - &i.ID, - &i.WantID, - &i.InfoHash, - &i.Name, - &i.Key, - &i.Indexer, - &i.Source, - &i.Client, - &i.SavePath, - &i.Quality, - &i.Origin, - &i.Forced, - &i.GrabbedBy, - &i.GrabbedAt, - &i.EndedAt, - &i.EndReason, - &i.EndDetail, - &i.Progress, - &i.ImportState, - &i.ImportReason, - &i.ImportDetail, - &i.ImportForced, - &i.ImportAttempts, - &i.ImportUpdatedAt, - &i.ImportedAt, - &i.ImportedFiles, - &i.Destination, - &i.Seeding, - &i.Ratio, - &i.SeedReleasedAt, - ) - return i, err -} - -const insertWantCandidate = `-- name: InsertWantCandidate :exec -INSERT INTO want_candidates (want_id, key, name, info_hash, indexer, source, size_bytes, seeders, - files_count, format, quality, year, verdict, reason, reasons, folded_from, rank) -VALUES ($1, $2, $3, $4, $5, - $6, $7, $8, $9, $10, - $11, $12, $13, $14, $15, - $16, $17) -ON CONFLICT (want_id, key) DO NOTHING -` - -type InsertWantCandidateParams struct { - WantID pgtype.UUID - Key string - Name string - InfoHash string - Indexer string - Source string - SizeBytes int64 - Seeders int32 - FilesCount int32 - Format string - Quality string - Year int32 - Verdict string - Reason string - Reasons []byte - FoldedFrom []string - Rank int32 -} - -func (q *Queries) InsertWantCandidate(ctx context.Context, arg InsertWantCandidateParams) error { - _, err := q.db.Exec(ctx, insertWantCandidate, - arg.WantID, - arg.Key, - arg.Name, - arg.InfoHash, - arg.Indexer, - arg.Source, - arg.SizeBytes, - arg.Seeders, - arg.FilesCount, - arg.Format, - arg.Quality, - arg.Year, - arg.Verdict, - arg.Reason, - arg.Reasons, - arg.FoldedFrom, - arg.Rank, - ) - return err -} - -const listReleaseBlocks = `-- name: ListReleaseBlocks :many -SELECT info_hash, name, reason, detail, want_id, blocked_by, blocked_at, expires_at FROM release_blocks - WHERE expires_at IS NULL OR expires_at > now() - ORDER BY blocked_at DESC -` - -// Every release set aside and still held back: a stalled one lifts by itself -// at expires_at. -func (q *Queries) ListReleaseBlocks(ctx context.Context) ([]ReleaseBlock, error) { - rows, err := q.db.Query(ctx, listReleaseBlocks) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ReleaseBlock - for rows.Next() { - var i ReleaseBlock - if err := rows.Scan( - &i.InfoHash, - &i.Name, - &i.Reason, - &i.Detail, - &i.WantID, - &i.BlockedBy, - &i.BlockedAt, - &i.ExpiresAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listWantCandidates = `-- name: ListWantCandidates :many -SELECT want_id, key, name, info_hash, indexer, source, size_bytes, seeders, files_count, format, quality, year, verdict, reason, reasons, folded_from, rank, searched_at FROM want_candidates WHERE want_id = $1 ORDER BY rank, key -` - -func (q *Queries) ListWantCandidates(ctx context.Context, wantID pgtype.UUID) ([]WantCandidate, error) { - rows, err := q.db.Query(ctx, listWantCandidates, wantID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []WantCandidate - for rows.Next() { - var i WantCandidate - if err := rows.Scan( - &i.WantID, - &i.Key, - &i.Name, - &i.InfoHash, - &i.Indexer, - &i.Source, - &i.SizeBytes, - &i.Seeders, - &i.FilesCount, - &i.Format, - &i.Quality, - &i.Year, - &i.Verdict, - &i.Reason, - &i.Reasons, - &i.FoldedFrom, - &i.Rank, - &i.SearchedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listWantsDueForSearch = `-- name: ListWantsDueForSearch :many -SELECT w.id, w.release_group_mbid, w.artist_name, w.title, w.reason, w.upgrade, w.held_tier, w.held_quality, - COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type, - COALESCE(g.secondary_types, '{}')::text[] AS secondary_types, - COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date - FROM wants w - LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid - WHERE (w.fulfilled_at IS NULL OR w.upgrade <> '') - AND NOT EXISTS (SELECT 1 FROM grabs gr WHERE gr.want_id = w.id AND gr.ended_at IS NULL) - AND (w.searched_at IS NULL - OR w.searched_at < now() - make_interval(hours => CASE WHEN w.fulfilled_at IS NULL - THEN $1::int - ELSE GREATEST($1::int, 168) END)) - ORDER BY w.fulfilled_at IS NOT NULL, - w.searched_at IS NOT NULL, - CASE w.reason WHEN 'request' THEN 0 WHEN 'missing' THEN 1 ELSE 2 END, - w.searched_at NULLS FIRST, w.wanted_at, w.id - LIMIT $2 -` - -type ListWantsDueForSearchParams struct { - Hours int32 - MaxRows int32 -} - -type ListWantsDueForSearchRow struct { - ID pgtype.UUID - ReleaseGroupMbid string - ArtistName string - Title string - Reason string - Upgrade string - HeldTier string - HeldQuality string - PrimaryType string - SecondaryTypes []string - FirstReleaseDate string -} - -// Wants with no download running that were never searched or not since -// @hours ago: open wants first (never-searched, then requests, then missing -// files, then followed artists' releases), then held albums wanted for an -// upgrade, which are searched at most weekly. -func (q *Queries) ListWantsDueForSearch(ctx context.Context, arg ListWantsDueForSearchParams) ([]ListWantsDueForSearchRow, error) { - rows, err := q.db.Query(ctx, listWantsDueForSearch, arg.Hours, arg.MaxRows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListWantsDueForSearchRow - for rows.Next() { - var i ListWantsDueForSearchRow - if err := rows.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistName, - &i.Title, - &i.Reason, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.PrimaryType, - &i.SecondaryTypes, - &i.FirstReleaseDate, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const markCandidatesBlocked = `-- name: MarkCandidatesBlocked :exec -UPDATE want_candidates - SET verdict = 'blocked', reason = $1, - reasons = jsonb_build_array(jsonb_build_object('kind', 'hard', 'code', 'blocked', 'text', $1::text)) - WHERE info_hash = $2 -` - -type MarkCandidatesBlockedParams struct { - Reason string - InfoHash string -} - -func (q *Queries) MarkCandidatesBlocked(ctx context.Context, arg MarkCandidatesBlockedParams) error { - _, err := q.db.Exec(ctx, markCandidatesBlocked, arg.Reason, arg.InfoHash) - return err -} - -const markCandidatesUnblocked = `-- name: MarkCandidatesUnblocked :exec -UPDATE want_candidates - SET verdict = 'review', reason = $1, - reasons = jsonb_build_array(jsonb_build_object('kind', 'soft', 'code', 'unblocked', 'text', $1::text)) - WHERE info_hash = $2 AND verdict = 'blocked' -` - -type MarkCandidatesUnblockedParams struct { - Reason string - InfoHash string -} - -func (q *Queries) MarkCandidatesUnblocked(ctx context.Context, arg MarkCandidatesUnblockedParams) error { - _, err := q.db.Exec(ctx, markCandidatesUnblocked, arg.Reason, arg.InfoHash) - return err -} - -const recordSearchPass = `-- name: RecordSearchPass :exec -UPDATE acquisition_settings SET last_pass_at = now(), last_pass = $1 WHERE id = true -` - -func (q *Queries) RecordSearchPass(ctx context.Context, report []byte) error { - _, err := q.db.Exec(ctx, recordSearchPass, report) - return err -} - -const recordWantSearch = `-- name: RecordWantSearch :exec -UPDATE wants - SET searched_at = now(), - search_outcome = $1, - search_considered = $2, - best_release = $3, - best_verdict = $4, - search_error = $5, - updated_at = now() - WHERE id = $6 -` - -type RecordWantSearchParams struct { - Outcome string - Considered int32 - BestRelease string - BestVerdict string - SearchError string - ID pgtype.UUID -} - -func (q *Queries) RecordWantSearch(ctx context.Context, arg RecordWantSearchParams) error { - _, err := q.db.Exec(ctx, recordWantSearch, - arg.Outcome, - arg.Considered, - arg.BestRelease, - arg.BestVerdict, - arg.SearchError, - arg.ID, - ) - return err -} - -const unblockRelease = `-- name: UnblockRelease :execrows -DELETE FROM release_blocks WHERE info_hash = $1 -` - -func (q *Queries) UnblockRelease(ctx context.Context, infoHash string) (int64, error) { - result, err := q.db.Exec(ctx, unblockRelease, infoHash) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const updateAcquisitionSettings = `-- name: UpdateAcquisitionSettings :one -UPDATE acquisition_settings - SET auto_grab = $1, - search_interval_hours = $2, - allowed_qualities = $3, - import_root = $4, - seed_ratio = $5, - seed_days = $6, - stall_hours = $7, - upgrade_until = $8, - updated_at = now() - WHERE id = true -RETURNING id, auto_grab, search_interval_hours, allowed_qualities, last_pass_at, last_pass, updated_at, import_root, seed_ratio, seed_days, stall_hours, library_listing_started_at, library_listed_at, library_unlisted, upgrade_until -` - -type UpdateAcquisitionSettingsParams struct { - AutoGrab bool - SearchIntervalHours int32 - AllowedQualities []string - ImportRoot string - SeedRatio float32 - SeedDays int32 - StallHours int32 - UpgradeUntil string -} - -func (q *Queries) UpdateAcquisitionSettings(ctx context.Context, arg UpdateAcquisitionSettingsParams) (AcquisitionSetting, error) { - row := q.db.QueryRow(ctx, updateAcquisitionSettings, - arg.AutoGrab, - arg.SearchIntervalHours, - arg.AllowedQualities, - arg.ImportRoot, - arg.SeedRatio, - arg.SeedDays, - arg.StallHours, - arg.UpgradeUntil, - ) - var i AcquisitionSetting - err := row.Scan( - &i.ID, - &i.AutoGrab, - &i.SearchIntervalHours, - &i.AllowedQualities, - &i.LastPassAt, - &i.LastPass, - &i.UpdatedAt, - &i.ImportRoot, - &i.SeedRatio, - &i.SeedDays, - &i.StallHours, - &i.LibraryListingStartedAt, - &i.LibraryListedAt, - &i.LibraryUnlisted, - &i.UpgradeUntil, - ) - return i, err -} diff --git a/internal/db/dbq/similarity.sql.go b/internal/db/dbq/similarity.sql.go index d1f69b8a..2357be71 100644 --- a/internal/db/dbq/similarity.sql.go +++ b/internal/db/dbq/similarity.sql.go @@ -340,35 +340,3 @@ func (q *Queries) UpsertArtistSimilarity(ctx context.Context, arg UpsertArtistSi _, err := q.db.Exec(ctx, upsertArtistSimilarity, arg.ArtistAID, arg.ArtistBID, arg.Score) return err } - -const upsertArtistSimilarityUnmatched = `-- name: UpsertArtistSimilarityUnmatched :exec -INSERT INTO artist_similarity_unmatched ( - seed_artist_id, candidate_mbid, candidate_name, score, source -) VALUES ($1, $2, $3, $4, $5) -ON CONFLICT (seed_artist_id, candidate_mbid, source) DO UPDATE SET - candidate_name = EXCLUDED.candidate_name, - score = EXCLUDED.score, - fetched_at = now() -` - -type UpsertArtistSimilarityUnmatchedParams struct { - SeedArtistID pgtype.UUID - CandidateMbid string - CandidateName string - Score float64 - Source string -} - -// Persists an out-of-library similar-artist MBID. Idempotent on -// (seed_artist_id, candidate_mbid, source) — re-fetches refresh the -// name/score and bump fetched_at. -func (q *Queries) UpsertArtistSimilarityUnmatched(ctx context.Context, arg UpsertArtistSimilarityUnmatchedParams) error { - _, err := q.db.Exec(ctx, upsertArtistSimilarityUnmatched, - arg.SeedArtistID, - arg.CandidateMbid, - arg.CandidateName, - arg.Score, - arg.Source, - ) - return err -} diff --git a/internal/db/dbq/songs.sql.go b/internal/db/dbq/songs.sql.go index a441f9c6..dba271bb 100644 --- a/internal/db/dbq/songs.sql.go +++ b/internal/db/dbq/songs.sql.go @@ -34,7 +34,7 @@ type LinkTracksAsSongRow struct { } // Song links: copies of one song on different releases share a -// song_key (migration 0076). +// song_key. // Links the tracks into one song, joining any songs they already belong to. // The song keeps the lowest key among them, so linking the same set again // changes nothing. Returns that key and how many tracks moved to it. diff --git a/internal/db/dbq/suggestion_snoozes.sql.go b/internal/db/dbq/suggestion_snoozes.sql.go deleted file mode 100644 index 5da3eb77..00000000 --- a/internal/db/dbq/suggestion_snoozes.sql.go +++ /dev/null @@ -1,126 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: suggestion_snoozes.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const gcDeleteExpiredSuggestionSnoozes = `-- name: GcDeleteExpiredSuggestionSnoozes :execrows -DELETE FROM suggestion_snoozes WHERE snoozed_until < now() -` - -// Keeps the table from growing without bound. Every read already filters on -// snoozed_until > now(), so deleting an expired row changes no behaviour — -// this is purely reclamation. -func (q *Queries) GcDeleteExpiredSuggestionSnoozes(ctx context.Context) (int64, error) { - result, err := q.db.Exec(ctx, gcDeleteExpiredSuggestionSnoozes) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const listActiveSuggestionSnoozes = `-- name: ListActiveSuggestionSnoozes :many -SELECT candidate_mbid, candidate_name, snoozed_until, created_at - FROM suggestion_snoozes - WHERE user_id = $1 AND snoozed_until > now() - ORDER BY snoozed_until, candidate_mbid -` - -type ListActiveSuggestionSnoozesRow struct { - CandidateMbid string - CandidateName string - SnoozedUntil pgtype.Timestamptz - CreatedAt pgtype.Timestamptz -} - -// Backs the manage / un-snooze surface. Expired rows are filtered HERE -// rather than left to the sweeper: gc runs on an hourly tick, so a row can -// outlive its expiry by up to a tick and must not read as still-snoozed in -// the meantime. -func (q *Queries) ListActiveSuggestionSnoozes(ctx context.Context, userID pgtype.UUID) ([]ListActiveSuggestionSnoozesRow, error) { - rows, err := q.db.Query(ctx, listActiveSuggestionSnoozes, userID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListActiveSuggestionSnoozesRow - for rows.Next() { - var i ListActiveSuggestionSnoozesRow - if err := rows.Scan( - &i.CandidateMbid, - &i.CandidateName, - &i.SnoozedUntil, - &i.CreatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const snoozeSuggestion = `-- name: SnoozeSuggestion :exec - -INSERT INTO suggestion_snoozes (user_id, candidate_mbid, candidate_name, snoozed_until) -VALUES ($1, $2, $3, now() + ($4::float8 * INTERVAL '1 day')) -ON CONFLICT (user_id, candidate_mbid) DO UPDATE - SET snoozed_until = EXCLUDED.snoozed_until, - candidate_name = EXCLUDED.candidate_name -` - -type SnoozeSuggestionParams struct { - UserID pgtype.UUID - CandidateMbid string - CandidateName string - Column4 float64 -} - -// Time-boxed "not right now" on a Discover artist suggestion. -// -// See 0049_suggestion_snoozes.up.sql for why this is a snooze and not a -// dismissal: it records no verdict on the music, expires on its own, and -// must never reach the taste profile. Nothing in internal/taste may read -// this table. -// Upsert, so re-snoozing an already-snoozed candidate EXTENDS it instead of -// erroring on the PK. The name is refreshed too — a later suggestion may -// carry a corrected spelling from the similarity feed. -// $1=user_id, $2=candidate_mbid, $3=candidate_name, $4=duration in days. -func (q *Queries) SnoozeSuggestion(ctx context.Context, arg SnoozeSuggestionParams) error { - _, err := q.db.Exec(ctx, snoozeSuggestion, - arg.UserID, - arg.CandidateMbid, - arg.CandidateName, - arg.Column4, - ) - return err -} - -const unsnoozeSuggestion = `-- name: UnsnoozeSuggestion :execrows -DELETE FROM suggestion_snoozes - WHERE user_id = $1 AND candidate_mbid = $2 -` - -type UnsnoozeSuggestionParams struct { - UserID pgtype.UUID - CandidateMbid string -} - -// Row count is returned so the handler can 404 an MBID that was never -// snoozed rather than reporting success for a no-op. -func (q *Queries) UnsnoozeSuggestion(ctx context.Context, arg UnsnoozeSuggestionParams) (int64, error) { - result, err := q.db.Exec(ctx, unsnoozeSuggestion, arg.UserID, arg.CandidateMbid) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} diff --git a/internal/db/dbq/system_playlists.sql.go b/internal/db/dbq/system_playlists.sql.go index 0a892e48..9b51826d 100644 --- a/internal/db/dbq/system_playlists.sql.go +++ b/internal/db/dbq/system_playlists.sql.go @@ -11,6 +11,15 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const clearPlaylistTracks = `-- name: ClearPlaylistTracks :exec +DELETE FROM playlist_tracks WHERE playlist_id = $1 +` + +func (q *Queries) ClearPlaylistTracks(ctx context.Context, playlistID pgtype.UUID) error { + _, err := q.db.Exec(ctx, clearPlaylistTracks, playlistID) + return err +} + const clearStaleSystemPlaylistInFlight = `-- name: ClearStaleSystemPlaylistInFlight :exec UPDATE system_playlist_runs SET in_flight = false WHERE in_flight = true ` @@ -26,9 +35,9 @@ func (q *Queries) ClearStaleSystemPlaylistInFlight(ctx context.Context) error { const createSystemPlaylist = `-- name: CreateSystemPlaylist :one INSERT INTO playlists ( user_id, name, description, is_public, - kind, system_variant, seed_artist_id, cover_path -) VALUES ($1, $2, '', false, 'system', $3, $4, $5) -RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id + kind, system_variant, seed_artist_id, cover_path, shelf_rank +) VALUES ($1, $2, $6, false, 'system', $3, $4, $5, $7) +RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank ` type CreateSystemPlaylistParams struct { @@ -37,11 +46,14 @@ type CreateSystemPlaylistParams struct { SystemVariant *string SeedArtistID pgtype.UUID CoverPath *string + Description string + ShelfRank int32 } // Inserts a system-generated playlist. Used by BuildSystemPlaylists. // For 'for_you' variant, pass seed_artist_id as NULL (zero-value pgtype.UUID -// with Valid=false). +// with Valid=false). shelf_rank is the mix's place on its Home shelf, 1 +// first, or 0 for kinds the clients order themselves. func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlaylistParams) (Playlist, error) { row := q.db.QueryRow(ctx, createSystemPlaylist, arg.UserID, @@ -49,6 +61,8 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay arg.SystemVariant, arg.SeedArtistID, arg.CoverPath, + arg.Description, + arg.ShelfRank, ) var i Playlist err := row.Scan( @@ -65,18 +79,19 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ) return i, err } -const deleteSystemPlaylistsForUser = `-- name: DeleteSystemPlaylistsForUser :exec -DELETE FROM playlists WHERE user_id = $1 AND kind = 'system' +const deletePlaylistsByIDs = `-- name: DeletePlaylistsByIDs :exec +DELETE FROM playlists WHERE id = ANY($1::uuid[]) ` -// Atomic-replace step. CASCADE on playlist_tracks.playlist_id handles -// the join rows. -func (q *Queries) DeleteSystemPlaylistsForUser(ctx context.Context, userID pgtype.UUID) error { - _, err := q.db.Exec(ctx, deleteSystemPlaylistsForUser, userID) +// Mixes a rebuild no longer makes. CASCADE on playlist_tracks.playlist_id +// handles the join rows. +func (q *Queries) DeletePlaylistsByIDs(ctx context.Context, ids []pgtype.UUID) error { + _, err := q.db.Exec(ctx, deletePlaylistsByIDs, ids) return err } @@ -297,6 +312,46 @@ func (q *Queries) ListPlaylistsByUserAndKind(ctx context.Context, arg ListPlayli return items, nil } +const listSystemPlaylistsForRebuild = `-- name: ListSystemPlaylistsForRebuild :many +SELECT id, name, system_variant, seed_artist_id + FROM playlists + WHERE user_id = $1 AND kind = 'system' +` + +type ListSystemPlaylistsForRebuildRow struct { + ID pgtype.UUID + Name string + SystemVariant *string + SeedArtistID pgtype.UUID +} + +// The user's current mixes, so a rebuild can refill each in place and keep +// its id. +func (q *Queries) ListSystemPlaylistsForRebuild(ctx context.Context, userID pgtype.UUID) ([]ListSystemPlaylistsForRebuildRow, error) { + rows, err := q.db.Query(ctx, listSystemPlaylistsForRebuild, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListSystemPlaylistsForRebuildRow + for rows.Next() { + var i ListSystemPlaylistsForRebuildRow + if err := rows.Scan( + &i.ID, + &i.Name, + &i.SystemVariant, + &i.SeedArtistID, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const pickSeedArtists = `-- name: PickSeedArtists :many WITH liked AS ( SELECT gla.artist_id FROM general_likes_artists gla WHERE gla.user_id = $1 @@ -358,7 +413,7 @@ SELECT c.artist_id, FROM chosen c LEFT JOIN liked l ON l.artist_id = c.artist_id ORDER BY score DESC, c.artist_id - LIMIT 12 + LIMIT 24 ` type PickSeedArtistsRow struct { @@ -383,8 +438,8 @@ type PickSeedArtistsRow struct { // tiered pick-kind ladder and stamps the built tracks, so metrics // can compare mixes seeded from fresh vs stale engagement. // Score = unskipped-play count + 5 if user has liked the artist. The -// Go-side picker (pickSeedArtistsForDay) shuffles the 12 -// daily-deterministically and takes songsLikeSeedCount (6) so the mix +// Go-side picker (pickSeedArtistsForDay) shuffles the 24 +// daily-deterministically and takes songsLikeSeedCount (12) so the mix // set both rotates day-to-day and fills the dedicated Home row. func (q *Queries) PickSeedArtists(ctx context.Context, userID pgtype.UUID) ([]PickSeedArtistsRow, error) { rows, err := q.db.Query(ctx, pickSeedArtists, userID) @@ -406,36 +461,6 @@ func (q *Queries) PickSeedArtists(ctx context.Context, userID pgtype.UUID) ([]Pi return items, nil } -const pickTopAlbumCoverForArtistByUser = `-- name: PickTopAlbumCoverForArtistByUser :one -SELECT a.cover_art_path - FROM albums a - LEFT JOIN tracks t ON t.album_id = a.id - LEFT JOIN play_events pe - ON pe.track_id = t.id - AND pe.user_id = $1 - AND pe.was_skipped = false - WHERE a.artist_id = $2 - AND a.cover_art_path IS NOT NULL - GROUP BY a.id, a.release_date, a.cover_art_path - ORDER BY COUNT(pe.id) DESC, a.release_date DESC NULLS LAST, a.id - LIMIT 1 -` - -type PickTopAlbumCoverForArtistByUserParams struct { - UserID pgtype.UUID - ArtistID pgtype.UUID -} - -// "Songs like X" cover. Most-played album by user; tie-break by most-recent -// release. NULL if the artist has no albums or all covers are NULL. -// Note: albums uses cover_art_path (not cover_path). -func (q *Queries) PickTopAlbumCoverForArtistByUser(ctx context.Context, arg PickTopAlbumCoverForArtistByUserParams) (*string, error) { - row := q.db.QueryRow(ctx, pickTopAlbumCoverForArtistByUser, arg.UserID, arg.ArtistID) - var cover_art_path *string - err := row.Scan(&cover_art_path) - return cover_art_path, err -} - const pickTopPlayedTrackForArtistByUser = `-- name: PickTopPlayedTrackForArtistByUser :one SELECT COALESCE( (SELECT t.id @@ -552,6 +577,31 @@ func (q *Queries) PickTopPlayedTracksForUser(ctx context.Context, userID pgtype. return items, nil } +const refreshSystemPlaylist = `-- name: RefreshSystemPlaylist :exec +UPDATE playlists + SET name = $2, description = $3, shelf_rank = $4 + WHERE id = $1 +` + +type RefreshSystemPlaylistParams struct { + ID pgtype.UUID + Name string + Description string + ShelfRank int32 +} + +// A rebuild refilling an existing mix: its name, description and shelf +// place may move with the day's build. updated_at moves with the rollups. +func (q *Queries) RefreshSystemPlaylist(ctx context.Context, arg RefreshSystemPlaylistParams) error { + _, err := q.db.Exec(ctx, refreshSystemPlaylist, + arg.ID, + arg.Name, + arg.Description, + arg.ShelfRank, + ) + return err +} + const tryClaimSystemPlaylistRun = `-- name: TryClaimSystemPlaylistRun :one INSERT INTO system_playlist_runs (user_id, in_flight) VALUES ($1, true) diff --git a/internal/db/dbq/taste_profile.sql.go b/internal/db/dbq/taste_profile.sql.go index c7aa5c7f..59369642 100644 --- a/internal/db/dbq/taste_profile.sql.go +++ b/internal/db/dbq/taste_profile.sql.go @@ -196,6 +196,7 @@ JOIN tracks t ON t.id = pe.track_id JOIN albums a ON a.id = t.album_id WHERE pe.user_id = $1 AND pe.started_at > now() - ($2::float8 * INTERVAL '1 day') + AND (pe.completion_ratio IS NOT NULL OR pe.duration_played_ms IS NOT NULL) AND NOT EXISTS ( SELECT 1 FROM quarantine q WHERE q.user_id = $1 AND q.track_id = t.id @@ -223,7 +224,9 @@ type ListPlayEngagementInputsForUserRow struct { // completion ratio (precomputed column when present, else duration_played / // track duration, clamped to [0,1]); age_days drives the time-decay. Genre // is split into tags in Go; release_date derives the decade for the era -// facet. Quarantined tracks are excluded. +// facet. Quarantined tracks are excluded, and so is a play whose completion +// isn't known: one still open (playing now), or one the sweeper closed +// without hearing how it ended. Graded as 0 they would read as skips. func (q *Queries) ListPlayEngagementInputsForUser(ctx context.Context, arg ListPlayEngagementInputsForUserParams) ([]ListPlayEngagementInputsForUserRow, error) { rows, err := q.db.Query(ctx, listPlayEngagementInputsForUser, arg.UserID, arg.Column2) if err != nil { diff --git a/internal/db/dbq/tracks.sql.go b/internal/db/dbq/tracks.sql.go index 5f136d09..49028055 100644 --- a/internal/db/dbq/tracks.sql.go +++ b/internal/db/dbq/tracks.sql.go @@ -14,7 +14,9 @@ import ( const adoptTrackPath = `-- name: AdoptTrackPath :execrows UPDATE tracks SET file_path = $1, - missing_since = NULL + missing_since = NULL, + removed_reason = NULL, + removed_by = NULL WHERE id = $2 AND missing_since IS NOT NULL ` @@ -31,6 +33,7 @@ type AdoptTrackPathParams struct { // // `missing_since IS NOT NULL` again, this time as a race guard: two files can't // both adopt the same row, and :execrows reports 0 to whichever loses. +// A removal's reason goes with the mark: the track has its file again. func (q *Queries) AdoptTrackPath(ctx context.Context, arg AdoptTrackPathParams) (int64, error) { result, err := q.db.Exec(ctx, adoptTrackPath, arg.FilePath, arg.ID) if err != nil { @@ -74,7 +77,9 @@ func (q *Queries) ClearTrackMbids(ctx context.Context, ids []pgtype.UUID) error const clearTracksMissing = `-- name: ClearTracksMissing :execrows UPDATE tracks - SET missing_since = NULL + SET missing_since = NULL, + removed_reason = NULL, + removed_by = NULL WHERE id = ANY($1::uuid[]) AND missing_since IS NOT NULL ` @@ -103,6 +108,62 @@ func (q *Queries) CountMissingTracks(ctx context.Context) (int64, error) { return count, err } +const countPlayableTracks = `-- name: CountPlayableTracks :one +SELECT count(*) FROM tracks WHERE missing_since IS NULL +` + +// The songs whose files are present, for the Subsonic getScanStatus count. +func (q *Queries) CountPlayableTracks(ctx context.Context) (int64, error) { + row := q.db.QueryRow(ctx, countPlayableTracks) + var count int64 + err := row.Scan(&count) + return count, err +} + +const countPlayableTracksByAlbums = `-- name: CountPlayableTracksByAlbums :many +SELECT album_id, count(*)::int AS track_count +FROM tracks +WHERE album_id = ANY($1::uuid[]) + AND missing_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = $2 AND q.track_id = tracks.id + ) +GROUP BY album_id +` + +type CountPlayableTracksByAlbumsParams struct { + AlbumIds []pgtype.UUID + UserID pgtype.UUID +} + +type CountPlayableTracksByAlbumsRow struct { + AlbumID pgtype.UUID + TrackCount int32 +} + +// How many of each album's tracks the listener $2 can play: present on +// disk and not quarantined by them. An album with none is absent. +func (q *Queries) CountPlayableTracksByAlbums(ctx context.Context, arg CountPlayableTracksByAlbumsParams) ([]CountPlayableTracksByAlbumsRow, error) { + rows, err := q.db.Query(ctx, countPlayableTracksByAlbums, arg.AlbumIds, arg.UserID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []CountPlayableTracksByAlbumsRow + for rows.Next() { + var i CountPlayableTracksByAlbumsRow + if err := rows.Scan(&i.AlbumID, &i.TrackCount); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const countSuspectSourceTracks = `-- name: CountSuspectSourceTracks :one SELECT COUNT(*) FROM tracks t WHERE t.missing_since IS NULL @@ -128,20 +189,6 @@ func (q *Queries) CountTracksByAlbum(ctx context.Context, albumID pgtype.UUID) ( return count, err } -const countTracksByArtist = `-- name: CountTracksByArtist :one -SELECT COUNT(*) FROM tracks WHERE artist_id = $1 -` - -// Used by request-progress reporting to count tracks ingested under a -// matched artist (sum across all the artist's albums) while a request -// is still in flight. -func (q *Queries) CountTracksByArtist(ctx context.Context, artistID pgtype.UUID) (int64, error) { - row := q.db.QueryRow(ctx, countTracksByArtist, artistID) - var count int64 - err := row.Scan(&count) - return count, err -} - const countTracksMatching = `-- name: CountTracksMatching :one SELECT COUNT(*) FROM tracks WHERE title ILIKE '%' || $1::text || '%' @@ -299,7 +346,7 @@ func (q *Queries) FlagSuspectSourceTracks(ctx context.Context, pattern string) ( } const getTrackByID = `-- name: GetTrackByID :one -SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at FROM tracks WHERE id = $1 +SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE id = $1 ` func (q *Queries) GetTrackByID(ctx context.Context, id pgtype.UUID) (Track, error) { @@ -331,12 +378,15 @@ func (q *Queries) GetTrackByID(ctx context.Context, id pgtype.UUID) (Track, erro &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, ) return i, err } const getTrackByPath = `-- name: GetTrackByPath :one -SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at FROM tracks WHERE file_path = $1 +SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE file_path = $1 ` func (q *Queries) GetTrackByPath(ctx context.Context, filePath string) (Track, error) { @@ -368,12 +418,15 @@ func (q *Queries) GetTrackByPath(ctx context.Context, filePath string) (Track, e &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, ) return i, err } const getTracksByIDs = `-- name: GetTracksByIDs :many -SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at FROM tracks WHERE id = ANY($1::uuid[]) +SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE id = ANY($1::uuid[]) ` // Batched lookup used by /api/library/sync to hydrate upsert payloads @@ -413,6 +466,9 @@ func (q *Queries) GetTracksByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([ &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, ); err != nil { return nil, err } @@ -425,7 +481,7 @@ func (q *Queries) GetTracksByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([ } const listArtistTracksForUser = `-- name: ListArtistTracksForUser :many -SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit, albums.title AS album_title, artists.name AS artist_name FROM tracks t @@ -491,6 +547,9 @@ func (q *Queries) ListArtistTracksForUser(ctx context.Context, arg ListArtistTra &i.Track.SourceVerdict, &i.Track.SourceVerdictAt, &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, &i.AlbumTitle, &i.ArtistName, ); err != nil { @@ -515,12 +574,21 @@ SELECT t.id, albums.title AS album_title, artists.id AS artist_id, artists.name AS artist_name, + t.disc_number, + t.track_number, + t.mbid, + albums.release_group_mbid, + -- Why the track waits: the Collection queue its file was removed from, + -- and who removed it. NULL reason means the scan found the file gone. + t.removed_reason, + remover.username AS removed_by_name, -- Cast is load-bearing: without it sqlc infers the correlated -- subquery as interface{} and the Go layer loses the timestamp type. (SELECT MAX(pe.started_at) FROM play_events pe WHERE pe.track_id = t.id)::timestamptz AS last_played_at FROM tracks t JOIN albums ON albums.id = t.album_id JOIN artists ON artists.id = t.artist_id + LEFT JOIN users remover ON remover.id = t.removed_by WHERE t.missing_since IS NOT NULL ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title LIMIT $2 OFFSET $1 @@ -532,17 +600,23 @@ type ListMissingTracksParams struct { } type ListMissingTracksRow struct { - ID pgtype.UUID - Title string - FilePath string - Directory string - MissingSince pgtype.Timestamptz - DurationMs int32 - AlbumID pgtype.UUID - AlbumTitle string - ArtistID pgtype.UUID - ArtistName string - LastPlayedAt pgtype.Timestamptz + ID pgtype.UUID + Title string + FilePath string + Directory string + MissingSince pgtype.Timestamptz + DurationMs int32 + AlbumID pgtype.UUID + AlbumTitle string + ArtistID pgtype.UUID + ArtistName string + DiscNumber *int32 + TrackNumber *int32 + Mbid *string + ReleaseGroupMbid *string + RemovedReason *string + RemovedByName *string + LastPlayedAt pgtype.Timestamptz } // The admin review surface for files the scan could not find. @@ -577,6 +651,12 @@ func (q *Queries) ListMissingTracks(ctx context.Context, arg ListMissingTracksPa &i.AlbumTitle, &i.ArtistID, &i.ArtistName, + &i.DiscNumber, + &i.TrackNumber, + &i.Mbid, + &i.ReleaseGroupMbid, + &i.RemovedReason, + &i.RemovedByName, &i.LastPlayedAt, ); err != nil { return nil, err @@ -590,7 +670,7 @@ func (q *Queries) ListMissingTracks(ctx context.Context, arg ListMissingTracksPa } const listRandomTracksForUser = `-- name: ListRandomTracksForUser :many -SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit, albums.title AS album_title, artists.name AS artist_name FROM tracks t @@ -653,6 +733,9 @@ func (q *Queries) ListRandomTracksForUser(ctx context.Context, arg ListRandomTra &i.Track.SourceVerdict, &i.Track.SourceVerdictAt, &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, &i.AlbumTitle, &i.ArtistName, ); err != nil { @@ -716,18 +799,10 @@ SELECT t.id, artists.id AS artist_id, artists.name AS artist_name, t.source_verdict, - t.source_verdict_at, - -- The album's place on the wanted list: wanted for a clean copy, and - -- when that was last searched for. - COALESCE(w.upgrade, '')::text AS want_upgrade, - w.searched_at AS searched_at + t.source_verdict_at FROM tracks t JOIN albums ON albums.id = t.album_id JOIN artists ON artists.id = t.artist_id - LEFT JOIN LATERAL ( - SELECT x.upgrade, x.searched_at FROM wants x - WHERE x.album_id = albums.id AND x.fulfilled_at IS NOT NULL LIMIT 1 - ) w ON true WHERE t.missing_since IS NULL AND regexp_replace(t.file_path, '^.*/', '') ~* $1::text ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title @@ -754,8 +829,6 @@ type ListSuspectSourceTracksRow struct { ArtistName string SourceVerdict *string SourceVerdictAt pgtype.Timestamptz - WantUpgrade string - SearchedAt pgtype.Timestamptz } // The admin report of present tracks whose filename looks like a video rip @@ -791,8 +864,96 @@ func (q *Queries) ListSuspectSourceTracks(ctx context.Context, arg ListSuspectSo &i.ArtistName, &i.SourceVerdict, &i.SourceVerdictAt, - &i.WantUpgrade, - &i.SearchedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listTopTracksForArtistName = `-- name: ListTopTracksForArtistName :many +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit +FROM tracks t +JOIN artists ar ON ar.id = t.artist_id +JOIN albums al ON al.id = t.album_id +LEFT JOIN LATERAL ( + SELECT count(*) AS plays FROM play_events pe + WHERE pe.track_id = t.id AND pe.was_skipped = false +) p ON true +LEFT JOIN LATERAL ( + SELECT count(*) AS likes FROM general_likes gl WHERE gl.track_id = t.id +) l ON true +WHERE lower(ar.name) = lower($1::text) + AND t.missing_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = $2 AND q.track_id = t.id + ) +ORDER BY p.plays DESC, l.likes DESC, + al.release_date NULLS LAST, al.sort_title, al.id, + t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.id +LIMIT $3 +` + +type ListTopTracksForArtistNameParams struct { + ArtistName string + UserID pgtype.UUID + Lim int32 +} + +type ListTopTracksForArtistNameRow struct { + Track Track +} + +// An artist's top songs for the Subsonic getTopSongs, which names the artist +// rather than giving an id; the name matches regardless of case. "Top" is +// this server's own listening: the songs played through most often (skips +// not counted) by everyone on it, then the most liked. Songs nobody has +// played or liked follow in album order, so an artist with no history still +// has songs to play. Missing files and the listener's quarantined songs are +// left out. +func (q *Queries) ListTopTracksForArtistName(ctx context.Context, arg ListTopTracksForArtistNameParams) ([]ListTopTracksForArtistNameRow, error) { + rows, err := q.db.Query(ctx, listTopTracksForArtistName, arg.ArtistName, arg.UserID, arg.Lim) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListTopTracksForArtistNameRow + for rows.Next() { + var i ListTopTracksForArtistNameRow + if err := rows.Scan( + &i.Track.ID, + &i.Track.Title, + &i.Track.AlbumID, + &i.Track.ArtistID, + &i.Track.TrackNumber, + &i.Track.DiscNumber, + &i.Track.DurationMs, + &i.Track.FilePath, + &i.Track.FileSize, + &i.Track.FileFormat, + &i.Track.Bitrate, + &i.Track.Mbid, + &i.Track.Genre, + &i.Track.AddedAt, + &i.Track.UpdatedAt, + &i.Track.TagSource, + &i.Track.TagSourcesVersion, + &i.Track.TagReadVersion, + &i.Track.MissingSince, + &i.Track.MbidSource, + &i.Track.SongID, + &i.Track.SongKey, + &i.Track.SourceVerdict, + &i.Track.SourceVerdictAt, + &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, ); err != nil { return nil, err } @@ -840,7 +1001,7 @@ func (q *Queries) ListTrackPathsForReconcile(ctx context.Context) ([]ListTrackPa } const listTracksByAlbum = `-- name: ListTracksByAlbum :many -SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at FROM tracks +SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE album_id = $1 AND NOT EXISTS ( SELECT 1 FROM quarantine q @@ -892,6 +1053,84 @@ func (q *Queries) ListTracksByAlbum(ctx context.Context, arg ListTracksByAlbumPa &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listTracksByArtistAndTitle = `-- name: ListTracksByArtistAndTitle :many +SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit +FROM tracks t +JOIN artists ar ON ar.id = t.artist_id +WHERE lower(t.title) = lower($1::text) + AND ($2::text = '' + OR lower(ar.name) = lower($2::text) + OR lower(coalesce(t.artist_credit, '')) = lower($2::text)) + AND t.missing_since IS NULL +ORDER BY t.id +LIMIT 20 +` + +type ListTracksByArtistAndTitleParams struct { + Title string + ArtistName string +} + +type ListTracksByArtistAndTitleRow struct { + Track Track +} + +// Songs matching a title, and an artist when one is given, both regardless +// of case, for the Subsonic getLyrics, which names the song rather than +// giving an id. The artist matches the filing artist or the song's own +// credit ("Low Tide Choir feat. Ruby Calloway"). +func (q *Queries) ListTracksByArtistAndTitle(ctx context.Context, arg ListTracksByArtistAndTitleParams) ([]ListTracksByArtistAndTitleRow, error) { + rows, err := q.db.Query(ctx, listTracksByArtistAndTitle, arg.Title, arg.ArtistName) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListTracksByArtistAndTitleRow + for rows.Next() { + var i ListTracksByArtistAndTitleRow + if err := rows.Scan( + &i.Track.ID, + &i.Track.Title, + &i.Track.AlbumID, + &i.Track.ArtistID, + &i.Track.TrackNumber, + &i.Track.DiscNumber, + &i.Track.DurationMs, + &i.Track.FilePath, + &i.Track.FileSize, + &i.Track.FileFormat, + &i.Track.Bitrate, + &i.Track.Mbid, + &i.Track.Genre, + &i.Track.AddedAt, + &i.Track.UpdatedAt, + &i.Track.TagSource, + &i.Track.TagSourcesVersion, + &i.Track.TagReadVersion, + &i.Track.MissingSince, + &i.Track.MbidSource, + &i.Track.SongID, + &i.Track.SongKey, + &i.Track.SourceVerdict, + &i.Track.SourceVerdictAt, + &i.Track.EmptiedAt, + &i.Track.RemovedReason, + &i.Track.RemovedBy, + &i.Track.ArtistCredit, ); err != nil { return nil, err } @@ -941,6 +1180,52 @@ func (q *Queries) ListTracksMissingMbidWithPath(ctx context.Context, limit int32 return items, nil } +const lockTracksForForget = `-- name: LockTracksForForget :many +SELECT id, album_id, title, file_path, missing_since + FROM tracks + WHERE id = ANY($1::uuid[]) + ORDER BY id + FOR UPDATE +` + +type LockTracksForForgetRow struct { + ID pgtype.UUID + AlbumID pgtype.UUID + Title string + FilePath string + MissingSince pgtype.Timestamptz +} + +// Locks the tracks an admin asked to forget, for the forget's transaction, +// and returns what it re-checks: every one must still exist and still be +// missing. A track whose file came back since the page was read is playing +// again and is not forgotten. +func (q *Queries) LockTracksForForget(ctx context.Context, ids []pgtype.UUID) ([]LockTracksForForgetRow, error) { + rows, err := q.db.Query(ctx, lockTracksForForget, ids) + if err != nil { + return nil, err + } + defer rows.Close() + var items []LockTracksForForgetRow + for rows.Next() { + var i LockTracksForForgetRow + if err := rows.Scan( + &i.ID, + &i.AlbumID, + &i.Title, + &i.FilePath, + &i.MissingSince, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const markTracksEmptied = `-- name: MarkTracksEmptied :exec UPDATE tracks SET emptied_at = missing_since @@ -949,7 +1234,7 @@ UPDATE tracks ` // Stamps rows the duplicate resolver emptied, whose song the album holds no -// other copy of, with the time they went missing (migration 0095): missing-pair +// other copy of, with the time they went missing (emptied_at): missing-pair // folding then waits for a copy fetched again. func (q *Queries) MarkTracksEmptied(ctx context.Context, ids []pgtype.UUID) error { _, err := q.db.Exec(ctx, markTracksEmptied, ids) @@ -979,14 +1264,119 @@ func (q *Queries) MarkTracksMissing(ctx context.Context, ids []pgtype.UUID) (int return result.RowsAffected(), nil } +const markTracksRemoved = `-- name: MarkTracksRemoved :execrows +UPDATE tracks + SET missing_since = COALESCE(missing_since, now()), + removed_reason = $1::text, + removed_by = $2::uuid + WHERE id = ANY($3::uuid[]) +` + +type MarkTracksRemovedParams struct { + Reason string + RemovedBy pgtype.UUID + Ids []pgtype.UUID +} + +// Marks rows whose file an admin, or the duplicate resolver, removed on +// purpose: missing, like a file the walk did not see, with the queue it was +// removed from and who removed it (NULL for the resolver). The row keeps its +// likes, plays and playlist places, and a good copy that lands later is +// adopted or folded into it. A row already missing keeps the time it went. +func (q *Queries) MarkTracksRemoved(ctx context.Context, arg MarkTracksRemovedParams) (int64, error) { + result, err := q.db.Exec(ctx, markTracksRemoved, arg.Reason, arg.RemovedBy, arg.Ids) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const searchPlayableTracks = `-- name: SearchPlayableTracks :many +SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks +WHERE title ILIKE '%' || $1::text || '%' + AND missing_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = $2 AND q.track_id = tracks.id + ) +ORDER BY title, id +LIMIT $4 OFFSET $3 +` + +type SearchPlayableTracksParams struct { + Query string + UserID pgtype.UUID + RowOffset int32 + RowLimit int32 +} + +// Subsonic's song search: tracks whose title matches $1 that the listener +// $2 can play, so neither a missing file nor one they quarantined. Subsonic +// has no way to mark a song unplayable, and apps page through the whole +// library with this, so the filter is here rather than after the LIMIT: +// a short page reads to an app as the end of the results. +func (q *Queries) SearchPlayableTracks(ctx context.Context, arg SearchPlayableTracksParams) ([]Track, error) { + rows, err := q.db.Query(ctx, searchPlayableTracks, + arg.Query, + arg.UserID, + arg.RowOffset, + arg.RowLimit, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Track + for rows.Next() { + var i Track + if err := rows.Scan( + &i.ID, + &i.Title, + &i.AlbumID, + &i.ArtistID, + &i.TrackNumber, + &i.DiscNumber, + &i.DurationMs, + &i.FilePath, + &i.FileSize, + &i.FileFormat, + &i.Bitrate, + &i.Mbid, + &i.Genre, + &i.AddedAt, + &i.UpdatedAt, + &i.TagSource, + &i.TagSourcesVersion, + &i.TagReadVersion, + &i.MissingSince, + &i.MbidSource, + &i.SongID, + &i.SongKey, + &i.SourceVerdict, + &i.SourceVerdictAt, + &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const searchTracks = `-- name: SearchTracks :many -SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at FROM tracks +SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE title ILIKE '%' || $1::text || '%' AND NOT EXISTS ( SELECT 1 FROM quarantine q WHERE q.user_id = $2 AND q.track_id = tracks.id ) -ORDER BY title +ORDER BY title, id LIMIT $3 OFFSET $4 ` @@ -1039,6 +1429,9 @@ func (q *Queries) SearchTracks(ctx context.Context, arg SearchTracksParams) ([]T &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, ); err != nil { return nil, err } @@ -1094,9 +1487,9 @@ const upsertTrack = `-- name: UpsertTrack :one INSERT INTO tracks ( title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, - tag_read_version, mbid_source + tag_read_version, mbid_source, artist_credit ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, - CASE WHEN $11::text IS NOT NULL THEN 'tag' END) + CASE WHEN $11::text IS NOT NULL THEN 'tag' END, $14) ON CONFLICT (file_path) DO UPDATE SET title = EXCLUDED.title, album_id = EXCLUDED.album_id, @@ -1113,11 +1506,12 @@ ON CONFLICT (file_path) DO UPDATE SET mbid_source = CASE WHEN EXCLUDED.mbid IS NOT NULL THEN 'tag' WHEN tracks.mbid_source = 'acoustid' THEN 'acoustid' END, genre = EXCLUDED.genre, + artist_credit = EXCLUDED.artist_credit, -- Stamped on update too, so a tag-repair pass marks rows as done and the -- next scan can short-circuit them again. tag_read_version = EXCLUDED.tag_read_version, updated_at = now() -RETURNING id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at +RETURNING id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit ` type UpsertTrackParams struct { @@ -1134,6 +1528,7 @@ type UpsertTrackParams struct { Mbid *string Genre *string TagReadVersion int16 + ArtistCredit *string } // file_path is the canonical identity for library scan; mbid is secondary. @@ -1154,6 +1549,7 @@ func (q *Queries) UpsertTrack(ctx context.Context, arg UpsertTrackParams) (Track arg.Mbid, arg.Genre, arg.TagReadVersion, + arg.ArtistCredit, ) var i Track err := row.Scan( @@ -1182,6 +1578,9 @@ func (q *Queries) UpsertTrack(ctx context.Context, arg UpsertTrackParams) (Track &i.SourceVerdict, &i.SourceVerdictAt, &i.EmptiedAt, + &i.RemovedReason, + &i.RemovedBy, + &i.ArtistCredit, ) return i, err } diff --git a/internal/db/dbq/users.sql.go b/internal/db/dbq/users.sql.go index d21696fa..34fc4c54 100644 --- a/internal/db/dbq/users.sql.go +++ b/internal/db/dbq/users.sql.go @@ -54,7 +54,7 @@ func (q *Queries) CountUsers(ctx context.Context) (int64, error) { const createUser = `-- name: CreateUser :one INSERT INTO users (username, password_hash, api_token_hash, is_admin, display_name) VALUES ($1, $2, $3, $4, $5) -RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash +RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash ` type CreateUserParams struct { @@ -84,7 +84,6 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -97,7 +96,7 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e const createUserAdmin = `-- name: CreateUserAdmin :one INSERT INTO users (username, password_hash, api_token_hash, is_admin, display_name) VALUES ($1, $2, $3, $4, $5) -RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash +RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash ` type CreateUserAdminParams struct { @@ -130,7 +129,6 @@ func (q *Queries) CreateUserAdmin(ctx context.Context, arg CreateUserAdminParams &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -147,7 +145,7 @@ VALUES ( (SELECT NOT EXISTS (SELECT 1 FROM users)), $4 ) -RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash +RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash ` type CreateUserFirstAdminRaceParams struct { @@ -188,7 +186,6 @@ func (q *Queries) CreateUserFirstAdminRace(ctx context.Context, arg CreateUserFi &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -240,7 +237,7 @@ func (q *Queries) GetListenBrainzConfig(ctx context.Context, id pgtype.UUID) (Ge } const getUserByAPITokenHash = `-- name: GetUserByAPITokenHash :one -SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE api_token_hash = $1 +SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE api_token_hash = $1 ` func (q *Queries) GetUserByAPITokenHash(ctx context.Context, apiTokenHash string) (User, error) { @@ -256,7 +253,6 @@ func (q *Queries) GetUserByAPITokenHash(ctx context.Context, apiTokenHash string &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -267,7 +263,7 @@ func (q *Queries) GetUserByAPITokenHash(ctx context.Context, apiTokenHash string } const getUserByEmail = `-- name: GetUserByEmail :one -SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE lower(email) = lower($1) +SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE lower(email) = lower($1) ` // Used by forgot-password lookup. Lowercase comparison both sides @@ -286,7 +282,6 @@ func (q *Queries) GetUserByEmail(ctx context.Context, lower string) (User, error &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -297,7 +292,7 @@ func (q *Queries) GetUserByEmail(ctx context.Context, lower string) (User, error } const getUserByID = `-- name: GetUserByID :one -SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE id = $1 +SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE id = $1 ` func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) { @@ -313,7 +308,6 @@ func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -324,7 +318,7 @@ func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) } const getUserByUsername = `-- name: GetUserByUsername :one -SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE username = $1 +SELECT id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash FROM users WHERE username = $1 ` func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) { @@ -340,7 +334,6 @@ func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -388,52 +381,20 @@ func (q *Queries) ListActiveUsersWithTimezones(ctx context.Context) ([]ListActiv return items, nil } -const listUsernamesByIDs = `-- name: ListUsernamesByIDs :many -SELECT id, username FROM users WHERE id = ANY($1::uuid[]) -` - -type ListUsernamesByIDsRow struct { - ID pgtype.UUID - Username string -} - -// Names a list's people in one round trip, e.g. who made each request on -// /admin/requests. -func (q *Queries) ListUsernamesByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([]ListUsernamesByIDsRow, error) { - rows, err := q.db.Query(ctx, listUsernamesByIDs, dollar_1) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListUsernamesByIDsRow - for rows.Next() { - var i ListUsernamesByIDsRow - if err := rows.Scan(&i.ID, &i.Username); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const listUsers = `-- name: ListUsers :many -SELECT id, username, display_name, is_admin, auto_approve_requests, +SELECT id, username, display_name, is_admin, debug_mode_enabled, created_at FROM users ORDER BY created_at DESC ` type ListUsersRow struct { - ID pgtype.UUID - Username string - DisplayName *string - IsAdmin bool - AutoApproveRequests bool - DebugModeEnabled bool - CreatedAt pgtype.Timestamptz + ID pgtype.UUID + Username string + DisplayName *string + IsAdmin bool + DebugModeEnabled bool + CreatedAt pgtype.Timestamptz } // Admin user-management list. Sort newest-first. @@ -451,7 +412,6 @@ func (q *Queries) ListUsers(ctx context.Context) ([]ListUsersRow, error) { &i.Username, &i.DisplayName, &i.IsAdmin, - &i.AutoApproveRequests, &i.DebugModeEnabled, &i.CreatedAt, ); err != nil { @@ -506,7 +466,7 @@ const setDebugMode = `-- name: SetDebugMode :one UPDATE users SET debug_mode_enabled = $2 WHERE id = $1 -RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash +RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash ` type SetDebugModeParams struct { @@ -530,7 +490,6 @@ func (q *Queries) SetDebugMode(ctx context.Context, arg SetDebugModeParams) (Use &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -583,7 +542,7 @@ type SetSubsonicPasswordParams struct { } // Stores (or clears with NULL) the per-user Subsonic legacy credential used -// for t/s and p auth on /rest/*. Must be plaintext; see migration 0003. Only +// for t/s and p auth on /rest/*. Must be plaintext: t/s auth hashes it with a salt. Only // ever a server-generated value, never the login password. func (q *Queries) SetSubsonicPassword(ctx context.Context, arg SetSubsonicPasswordParams) error { _, err := q.db.Exec(ctx, setSubsonicPassword, arg.ID, arg.SubsonicPassword) @@ -594,7 +553,7 @@ const updateUserAdmin = `-- name: UpdateUserAdmin :one UPDATE users SET is_admin = $2 WHERE id = $1 -RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash +RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash ` type UpdateUserAdminParams struct { @@ -617,43 +576,6 @@ func (q *Queries) UpdateUserAdmin(ctx context.Context, arg UpdateUserAdminParams &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, - &i.Email, - &i.Timezone, - &i.TimezoneUpdatedAt, - &i.DebugModeEnabled, - &i.ApiTokenHash, - ) - return i, err -} - -const updateUserAutoApprove = `-- name: UpdateUserAutoApprove :one -UPDATE users - SET auto_approve_requests = $2 - WHERE id = $1 -RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash -` - -type UpdateUserAutoApproveParams struct { - ID pgtype.UUID - AutoApproveRequests bool -} - -// Toggle the per-user auto_approve_requests flag. -func (q *Queries) UpdateUserAutoApprove(ctx context.Context, arg UpdateUserAutoApproveParams) (User, error) { - row := q.db.QueryRow(ctx, updateUserAutoApprove, arg.ID, arg.AutoApproveRequests) - var i User - err := row.Scan( - &i.ID, - &i.Username, - &i.PasswordHash, - &i.IsAdmin, - &i.CreatedAt, - &i.SubsonicPassword, - &i.ListenbrainzToken, - &i.ListenbrainzEnabled, - &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, @@ -668,7 +590,7 @@ UPDATE users SET display_name = $2, email = $3 WHERE id = $1 -RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash +RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash ` type UpdateUserProfileParams struct { @@ -692,7 +614,6 @@ func (q *Queries) UpdateUserProfile(ctx context.Context, arg UpdateUserProfilePa &i.ListenbrainzToken, &i.ListenbrainzEnabled, &i.DisplayName, - &i.AutoApproveRequests, &i.Email, &i.Timezone, &i.TimezoneUpdatedAt, diff --git a/internal/db/dbq/wanted.sql.go b/internal/db/dbq/wanted.sql.go deleted file mode 100644 index efe87083..00000000 --- a/internal/db/dbq/wanted.sql.go +++ /dev/null @@ -1,1697 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 -// source: wanted.sql - -package dbq - -import ( - "context" - - "github.com/jackc/pgx/v5/pgtype" -) - -const clearDefaultReleaseTypeProfile = `-- name: ClearDefaultReleaseTypeProfile :exec -UPDATE release_type_profiles SET is_default = false, updated_at = now() WHERE is_default -` - -func (q *Queries) ClearDefaultReleaseTypeProfile(ctx context.Context) error { - _, err := q.db.Exec(ctx, clearDefaultReleaseTypeProfile) - return err -} - -const clearHeldUpgrades = `-- name: ClearHeldUpgrades :execrows -UPDATE wants SET upgrade = '', held_tier = '', held_quality = '', upgrade_checked_at = now() - WHERE fulfilled_at IS NOT NULL AND upgrade <> '' - AND NOT EXISTS (SELECT 1 FROM tracks t - WHERE t.album_id = wants.album_id AND t.missing_since IS NULL AND t.duration_ms > 0) -` - -// A held want whose album has no track left to judge is not wanted again. -func (q *Queries) ClearHeldUpgrades(ctx context.Context) (int64, error) { - result, err := q.db.Exec(ctx, clearHeldUpgrades) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const countAlbumsToMatch = `-- name: CountAlbumsToMatch :one -SELECT COUNT(*) - FROM albums a - WHERE (a.created_at <= $1::timestamptz - OR EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.added_at <= $1::timestamptz)) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) - AND NOT EXISTS (SELECT 1 FROM library_album_matches m - WHERE m.album_id = a.id - AND (m.outcome IN ('listed', 'dismissed') - OR (m.matcher >= $2::int - AND NOT EXISTS (SELECT 1 FROM tracks t - WHERE t.album_id = a.id AND t.updated_at > m.decided_at)))) -` - -type CountAlbumsToMatchParams struct { - Cutoff pgtype.Timestamptz - Matcher int32 -} - -// Whether a finished listing has albums to go back to: those -// ListAlbumsToMatch would hand it. -func (q *Queries) CountAlbumsToMatch(ctx context.Context, arg CountAlbumsToMatchParams) (int64, error) { - row := q.db.QueryRow(ctx, countAlbumsToMatch, arg.Cutoff, arg.Matcher) - var count int64 - err := row.Scan(&count) - return count, err -} - -const countWants = `-- name: CountWants :one -SELECT COUNT(*) FILTER (WHERE fulfilled_at IS NULL AND reason <> 'missing')::bigint AS wanted, - COUNT(*) FILTER (WHERE fulfilled_at IS NULL AND reason = 'missing')::bigint AS missing, - COUNT(*) FILTER (WHERE fulfilled_at IS NOT NULL)::bigint AS held, - -- Held albums wanted for a better copy. - COUNT(*) FILTER (WHERE fulfilled_at IS NOT NULL AND upgrade <> '')::bigint AS upgrades, - COUNT(DISTINCT artist_mbid)::bigint AS artists, - -- Library albums waiting to be matched by hand. - (SELECT COUNT(*) FROM library_album_matches m - WHERE m.outcome = 'unmatched' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id))::bigint AS unmatched, - (SELECT COUNT(*) FROM follows)::bigint AS following, - -- The Wanted view's other tabs: downloads running, those - -- waiting on a person, and releases set aside. - (SELECT COUNT(*) FROM grabs WHERE ended_at IS NULL)::bigint AS activity, - (SELECT COUNT(*) FROM grabs - WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::bigint AS attention, - (SELECT COUNT(*) FROM release_blocks b - WHERE b.expires_at IS NULL OR b.expires_at > now())::bigint AS blocked - FROM wants -` - -type CountWantsRow struct { - Wanted int64 - Missing int64 - Held int64 - Upgrades int64 - Artists int64 - Unmatched int64 - Following int64 - Activity int64 - Attention int64 - Blocked int64 -} - -func (q *Queries) CountWants(ctx context.Context) (CountWantsRow, error) { - row := q.db.QueryRow(ctx, countWants) - var i CountWantsRow - err := row.Scan( - &i.Wanted, - &i.Missing, - &i.Held, - &i.Upgrades, - &i.Artists, - &i.Unmatched, - &i.Following, - &i.Activity, - &i.Attention, - &i.Blocked, - ) - return i, err -} - -const createReleaseTypeProfile = `-- name: CreateReleaseTypeProfile :one -INSERT INTO release_type_profiles (name, primary_types, secondary_types) -VALUES ($1, $2, $3) -RETURNING id, name, primary_types, secondary_types, is_default, created_at, updated_at -` - -type CreateReleaseTypeProfileParams struct { - Name string - PrimaryTypes []string - SecondaryTypes []string -} - -func (q *Queries) CreateReleaseTypeProfile(ctx context.Context, arg CreateReleaseTypeProfileParams) (ReleaseTypeProfile, error) { - row := q.db.QueryRow(ctx, createReleaseTypeProfile, arg.Name, arg.PrimaryTypes, arg.SecondaryTypes) - var i ReleaseTypeProfile - err := row.Scan( - &i.ID, - &i.Name, - &i.PrimaryTypes, - &i.SecondaryTypes, - &i.IsDefault, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} - -const deleteFollow = `-- name: DeleteFollow :execrows -DELETE FROM follows WHERE artist_mbid = $1 -` - -func (q *Queries) DeleteFollow(ctx context.Context, artistMbid string) (int64, error) { - result, err := q.db.Exec(ctx, deleteFollow, artistMbid) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const deleteReleaseTypeProfile = `-- name: DeleteReleaseTypeProfile :execrows -DELETE FROM release_type_profiles WHERE id = $1 AND NOT is_default -` - -// The default stays; one in use is refused by the follows foreign key. -func (q *Queries) DeleteReleaseTypeProfile(ctx context.Context, id pgtype.UUID) (int64, error) { - result, err := q.db.Exec(ctx, deleteReleaseTypeProfile, id) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const deleteWant = `-- name: DeleteWant :execrows -DELETE FROM wants WHERE id = $1 -` - -func (q *Queries) DeleteWant(ctx context.Context, id pgtype.UUID) (int64, error) { - result, err := q.db.Exec(ctx, deleteWant, id) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const finishLibraryListing = `-- name: FinishLibraryListing :one -UPDATE acquisition_settings - SET library_listed_at = COALESCE(library_listed_at, now()), - library_unlisted = (SELECT COUNT(*) FROM library_album_matches m - WHERE m.outcome = 'unmatched' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id)) - WHERE id = true -RETURNING library_listed_at, library_unlisted -` - -type FinishLibraryListingRow struct { - LibraryListedAt pgtype.Timestamptz - LibraryUnlisted int32 -} - -// The listing is done, or done again after a newer matcher's retries: -// count the albums no match was found for. The first finish is kept. -func (q *Queries) FinishLibraryListing(ctx context.Context) (FinishLibraryListingRow, error) { - row := q.db.QueryRow(ctx, finishLibraryListing) - var i FinishLibraryListingRow - err := row.Scan(&i.LibraryListedAt, &i.LibraryUnlisted) - return i, err -} - -const fulfillWant = `-- name: FulfillWant :exec -UPDATE wants - SET fulfilled_at = now(), - album_id = $1, - updated_at = now() - WHERE id = $2 AND fulfilled_at IS NULL -` - -type FulfillWantParams struct { - AlbumID pgtype.UUID - ID pgtype.UUID -} - -func (q *Queries) FulfillWant(ctx context.Context, arg FulfillWantParams) error { - _, err := q.db.Exec(ctx, fulfillWant, arg.AlbumID, arg.ID) - return err -} - -const getAlbumToMatch = `-- name: GetAlbumToMatch :one -SELECT a.id, a.title, a.mbid, a.release_group_mbid, ar.name AS artist_name, ar.mbid AS artist_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - JOIN library_album_matches m ON m.album_id = a.id AND m.outcome IN ('unmatched', 'dismissed') - WHERE a.id = $1 -` - -type GetAlbumToMatchRow struct { - ID pgtype.UUID - Title string - Mbid *string - ReleaseGroupMbid *string - ArtistName string - ArtistMbid *string -} - -// One album a person is matching by hand, as the matcher reads albums. -func (q *Queries) GetAlbumToMatch(ctx context.Context, id pgtype.UUID) (GetAlbumToMatchRow, error) { - row := q.db.QueryRow(ctx, getAlbumToMatch, id) - var i GetAlbumToMatchRow - err := row.Scan( - &i.ID, - &i.Title, - &i.Mbid, - &i.ReleaseGroupMbid, - &i.ArtistName, - &i.ArtistMbid, - ) - return i, err -} - -const getDefaultReleaseTypeProfile = `-- name: GetDefaultReleaseTypeProfile :one -SELECT id, name, primary_types, secondary_types, is_default, created_at, updated_at FROM release_type_profiles WHERE is_default -` - -func (q *Queries) GetDefaultReleaseTypeProfile(ctx context.Context) (ReleaseTypeProfile, error) { - row := q.db.QueryRow(ctx, getDefaultReleaseTypeProfile) - var i ReleaseTypeProfile - err := row.Scan( - &i.ID, - &i.Name, - &i.PrimaryTypes, - &i.SecondaryTypes, - &i.IsDefault, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} - -const getFollow = `-- name: GetFollow :one -SELECT f.artist_mbid, f.artist_name, f.profile_id, f.followed_by, f.followed_at, f.baseline_at, f.want_existing, f.checked_at, f.updated_at, p.name AS profile_name - FROM follows f - JOIN release_type_profiles p ON p.id = f.profile_id - WHERE f.artist_mbid = $1 -` - -type GetFollowRow struct { - ArtistMbid string - ArtistName string - ProfileID pgtype.UUID - FollowedBy pgtype.UUID - FollowedAt pgtype.Timestamptz - BaselineAt pgtype.Timestamptz - WantExisting bool - CheckedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz - ProfileName string -} - -func (q *Queries) GetFollow(ctx context.Context, artistMbid string) (GetFollowRow, error) { - row := q.db.QueryRow(ctx, getFollow, artistMbid) - var i GetFollowRow - err := row.Scan( - &i.ArtistMbid, - &i.ArtistName, - &i.ProfileID, - &i.FollowedBy, - &i.FollowedAt, - &i.BaselineAt, - &i.WantExisting, - &i.CheckedAt, - &i.UpdatedAt, - &i.ProfileName, - ) - return i, err -} - -const getLibraryListing = `-- name: GetLibraryListing :one - -SELECT library_listing_started_at, library_listed_at, library_unlisted - FROM acquisition_settings WHERE id = true -` - -type GetLibraryListingRow struct { - LibraryListingStartedAt pgtype.Timestamptz - LibraryListedAt pgtype.Timestamptz - LibraryUnlisted int32 -} - -// The one-time listing of the library. --------------------------- -func (q *Queries) GetLibraryListing(ctx context.Context) (GetLibraryListingRow, error) { - row := q.db.QueryRow(ctx, getLibraryListing) - var i GetLibraryListingRow - err := row.Scan(&i.LibraryListingStartedAt, &i.LibraryListedAt, &i.LibraryUnlisted) - return i, err -} - -const getReleaseTypeProfile = `-- name: GetReleaseTypeProfile :one -SELECT id, name, primary_types, secondary_types, is_default, created_at, updated_at FROM release_type_profiles WHERE id = $1 -` - -func (q *Queries) GetReleaseTypeProfile(ctx context.Context, id pgtype.UUID) (ReleaseTypeProfile, error) { - row := q.db.QueryRow(ctx, getReleaseTypeProfile, id) - var i ReleaseTypeProfile - err := row.Scan( - &i.ID, - &i.Name, - &i.PrimaryTypes, - &i.SecondaryTypes, - &i.IsDefault, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} - -const getWantAlbum = `-- name: GetWantAlbum :one -SELECT id, release_group_mbid, album_id FROM wants WHERE id = $1 -` - -type GetWantAlbumRow struct { - ID pgtype.UUID - ReleaseGroupMbid string - AlbumID pgtype.UUID -} - -// What the Wanted view's track list needs of a want. -func (q *Queries) GetWantAlbum(ctx context.Context, id pgtype.UUID) (GetWantAlbumRow, error) { - row := q.db.QueryRow(ctx, getWantAlbum, id) - var i GetWantAlbumRow - err := row.Scan(&i.ID, &i.ReleaseGroupMbid, &i.AlbumID) - return i, err -} - -const getWantByReleaseGroup = `-- name: GetWantByReleaseGroup :one -SELECT id, release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date, reason, album_id, created_by, wanted_at, fulfilled_at, created_at, updated_at, searched_at, search_outcome, search_considered, best_release, best_verdict, search_error, upgrade, held_tier, held_quality, upgrade_checked_at FROM wants WHERE release_group_mbid = $1 -` - -func (q *Queries) GetWantByReleaseGroup(ctx context.Context, releaseGroupMbid string) (Want, error) { - row := q.db.QueryRow(ctx, getWantByReleaseGroup, releaseGroupMbid) - var i Want - err := row.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.Title, - &i.PrimaryType, - &i.FirstReleaseDate, - &i.Reason, - &i.AlbumID, - &i.CreatedBy, - &i.WantedAt, - &i.FulfilledAt, - &i.CreatedAt, - &i.UpdatedAt, - &i.SearchedAt, - &i.SearchOutcome, - &i.SearchConsidered, - &i.BestRelease, - &i.BestVerdict, - &i.SearchError, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.UpgradeCheckedAt, - ) - return i, err -} - -const insertLibraryWant = `-- name: InsertLibraryWant :execrows -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date, - reason, album_id, wanted_at, fulfilled_at) -VALUES ($1, $2, $3, $4, - $5, $6, 'library', $7::uuid, now(), - COALESCE((SELECT MIN(t.missing_since) FROM tracks t WHERE t.album_id = $7::uuid) - - interval '1 second', now())) -ON CONFLICT (release_group_mbid) DO NOTHING -` - -type InsertLibraryWantParams struct { - ReleaseGroupMbid string - ArtistMbid string - ArtistName string - Title string - PrimaryType string - FirstReleaseDate string - AlbumID pgtype.UUID -} - -// Puts one matched album on the list as held, from just before its first -// lost track if it has one. A group already on the list is left as it is. -func (q *Queries) InsertLibraryWant(ctx context.Context, arg InsertLibraryWantParams) (int64, error) { - result, err := q.db.Exec(ctx, insertLibraryWant, - arg.ReleaseGroupMbid, - arg.ArtistMbid, - arg.ArtistName, - arg.Title, - arg.PrimaryType, - arg.FirstReleaseDate, - arg.AlbumID, - ) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const libraryHoldsReleaseGroup = `-- name: LibraryHoldsReleaseGroup :one -SELECT EXISTS ( - SELECT 1 FROM albums a - WHERE (a.release_group_mbid = $1::text - OR a.mbid = $1 - OR a.mbid IN (SELECT r.mbid FROM mb_releases r WHERE r.release_group_mbid = $1) - OR (lower(a.title) = lower($2::text) - AND a.artist_id IN (SELECT ar.id FROM artists ar WHERE ar.mbid = $3::text))) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL) -) -` - -type LibraryHoldsReleaseGroupParams struct { - GroupMbid string - Title string - ArtistMbid string -} - -// Whether the library already has the group: an album tagged with it or -// with one of its releases, or failing that an album of the artist's with -// the same title. Only albums with a track on disk count. -func (q *Queries) LibraryHoldsReleaseGroup(ctx context.Context, arg LibraryHoldsReleaseGroupParams) (bool, error) { - row := q.db.QueryRow(ctx, libraryHoldsReleaseGroup, arg.GroupMbid, arg.Title, arg.ArtistMbid) - var exists bool - err := row.Scan(&exists) - return exists, err -} - -const listAlbumTracksToMatch = `-- name: ListAlbumTracksToMatch :many -SELECT title, disc_number, track_number, duration_ms, mbid - FROM tracks - WHERE album_id = $1 - ORDER BY disc_number NULLS FIRST, track_number NULLS LAST, title -` - -type ListAlbumTracksToMatchRow struct { - Title string - DiscNumber *int32 - TrackNumber *int32 - DurationMs int32 - Mbid *string -} - -// What an album's tracks say about themselves, to check a match against. -func (q *Queries) ListAlbumTracksToMatch(ctx context.Context, albumID pgtype.UUID) ([]ListAlbumTracksToMatchRow, error) { - rows, err := q.db.Query(ctx, listAlbumTracksToMatch, albumID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListAlbumTracksToMatchRow - for rows.Next() { - var i ListAlbumTracksToMatchRow - if err := rows.Scan( - &i.Title, - &i.DiscNumber, - &i.TrackNumber, - &i.DurationMs, - &i.Mbid, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listAlbumsToMatch = `-- name: ListAlbumsToMatch :many -SELECT a.id, a.title, a.mbid, a.release_group_mbid, ar.name AS artist_name, ar.mbid AS artist_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - WHERE (a.created_at <= $1::timestamptz - OR EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.added_at <= $1::timestamptz)) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) - AND NOT EXISTS (SELECT 1 FROM library_album_matches m - WHERE m.album_id = a.id - AND (m.outcome IN ('listed', 'dismissed') - OR (m.matcher >= $2::int - AND NOT EXISTS (SELECT 1 FROM tracks t - WHERE t.album_id = a.id AND t.updated_at > m.decided_at)))) - ORDER BY a.created_at, a.id - LIMIT $3 -` - -type ListAlbumsToMatchParams struct { - Cutoff pgtype.Timestamptz - Matcher int32 - MaxRows int32 -} - -type ListAlbumsToMatchRow struct { - ID pgtype.UUID - Title string - Mbid *string - ReleaseGroupMbid *string - ArtistName string - ArtistMbid *string -} - -// Library albums the listing has not decided, or that an older matcher -// refused, or whose tracks changed since they were refused: each is matched -// to MusicBrainz. A library album is one from before the cutoff, or -// one whose tracks were: a re-tag files a track under a new album row but -// keeps the track. An album row with no tracks is not an album in -// the library; one a person left off stays off. -func (q *Queries) ListAlbumsToMatch(ctx context.Context, arg ListAlbumsToMatchParams) ([]ListAlbumsToMatchRow, error) { - rows, err := q.db.Query(ctx, listAlbumsToMatch, arg.Cutoff, arg.Matcher, arg.MaxRows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListAlbumsToMatchRow - for rows.Next() { - var i ListAlbumsToMatchRow - if err := rows.Scan( - &i.ID, - &i.Title, - &i.Mbid, - &i.ReleaseGroupMbid, - &i.ArtistName, - &i.ArtistMbid, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listFollowGroups = `-- name: ListFollowGroups :many -SELECT g.mbid, g.title, g.primary_type, g.secondary_types, g.first_release_date, - EXISTS (SELECT 1 FROM follow_seen_groups s - WHERE s.artist_mbid = $1 AND s.release_group_mbid = g.mbid) AS seen - FROM mb_artist_release_groups ag - JOIN mb_release_groups g ON g.mbid = ag.release_group_mbid - WHERE ag.artist_mbid = $1 - ORDER BY g.first_release_date, g.title -` - -type ListFollowGroupsRow struct { - Mbid string - Title string - PrimaryType string - SecondaryTypes []string - FirstReleaseDate string - Seen bool -} - -// An artist's release groups from the catalogue, each with whether the -// follow has judged it before. -func (q *Queries) ListFollowGroups(ctx context.Context, artistMbid string) ([]ListFollowGroupsRow, error) { - rows, err := q.db.Query(ctx, listFollowGroups, artistMbid) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListFollowGroupsRow - for rows.Next() { - var i ListFollowGroupsRow - if err := rows.Scan( - &i.Mbid, - &i.Title, - &i.PrimaryType, - &i.SecondaryTypes, - &i.FirstReleaseDate, - &i.Seen, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listFollows = `-- name: ListFollows :many -SELECT f.artist_mbid, f.artist_name, f.profile_id, f.followed_at, f.baseline_at, f.checked_at, - p.name AS profile_name, - (SELECT a.id FROM artists a WHERE a.mbid = f.artist_mbid) AS artist_id, - (SELECT COUNT(*) FROM wants w - WHERE w.artist_mbid = f.artist_mbid AND w.fulfilled_at IS NULL)::bigint AS open_wants - FROM follows f - JOIN release_type_profiles p ON p.id = f.profile_id - ORDER BY lower(f.artist_name), f.artist_mbid -` - -type ListFollowsRow struct { - ArtistMbid string - ArtistName string - ProfileID pgtype.UUID - FollowedAt pgtype.Timestamptz - BaselineAt pgtype.Timestamptz - CheckedAt pgtype.Timestamptz - ProfileName string - ArtistID pgtype.UUID - OpenWants int64 -} - -func (q *Queries) ListFollows(ctx context.Context) ([]ListFollowsRow, error) { - rows, err := q.db.Query(ctx, listFollows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListFollowsRow - for rows.Next() { - var i ListFollowsRow - if err := rows.Scan( - &i.ArtistMbid, - &i.ArtistName, - &i.ProfileID, - &i.FollowedAt, - &i.BaselineAt, - &i.CheckedAt, - &i.ProfileName, - &i.ArtistID, - &i.OpenWants, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listFollowsDue = `-- name: ListFollowsDue :many -SELECT f.artist_mbid, f.artist_name, f.profile_id, f.followed_by, f.followed_at, f.baseline_at, f.want_existing, f.checked_at, f.updated_at - FROM follows f - WHERE f.baseline_at IS NULL OR f.checked_at IS NULL OR f.checked_at < $1 - ORDER BY f.baseline_at NULLS FIRST, f.checked_at NULLS FIRST, f.artist_mbid - LIMIT $2 -` - -type ListFollowsDueParams struct { - Before pgtype.Timestamptz - MaxRows int32 -} - -// Follows whose discography has not been applied since @before, never-read -// first, so a new follow's baseline is not stuck behind daily re-checks. -func (q *Queries) ListFollowsDue(ctx context.Context, arg ListFollowsDueParams) ([]Follow, error) { - rows, err := q.db.Query(ctx, listFollowsDue, arg.Before, arg.MaxRows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []Follow - for rows.Next() { - var i Follow - if err := rows.Scan( - &i.ArtistMbid, - &i.ArtistName, - &i.ProfileID, - &i.FollowedBy, - &i.FollowedAt, - &i.BaselineAt, - &i.WantExisting, - &i.CheckedAt, - &i.UpdatedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listHeldWantFormats = `-- name: ListHeldWantFormats :many - -SELECT w.id AS want_id, w.upgrade, w.held_tier, w.held_quality, - lower(t.file_format)::text AS file_format, - SUM(t.file_size)::bigint AS bytes, - SUM(t.duration_ms)::bigint AS duration_ms, - COUNT(*)::int AS tracks, - COUNT(*) FILTER (WHERE t.source_verdict = 'suspect')::int AS rips - FROM wants w - JOIN tracks t ON t.album_id = w.album_id - WHERE w.fulfilled_at IS NOT NULL - AND t.missing_since IS NULL AND t.duration_ms > 0 - GROUP BY w.id, lower(t.file_format) - ORDER BY w.id -` - -type ListHeldWantFormatsRow struct { - WantID pgtype.UUID - Upgrade string - HeldTier string - HeldQuality string - FileFormat string - Bytes int64 - DurationMs int64 - Tracks int32 - Rips int32 -} - -// Upgrades. ------------------------------------------------------- -// What each held album's copy is made of, for judging whether it is worth -// upgrading: its present tracks grouped by format, with their bytes and -// length summed, and how many are held back as video rips. A held want whose -// album has no track with a length yet has no rows. -func (q *Queries) ListHeldWantFormats(ctx context.Context) ([]ListHeldWantFormatsRow, error) { - rows, err := q.db.Query(ctx, listHeldWantFormats) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListHeldWantFormatsRow - for rows.Next() { - var i ListHeldWantFormatsRow - if err := rows.Scan( - &i.WantID, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.FileFormat, - &i.Bytes, - &i.DurationMs, - &i.Tracks, - &i.Rips, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listLibraryAlbumTracks = `-- name: ListLibraryAlbumTracks :many -SELECT title, disc_number, track_number, duration_ms, (missing_since IS NOT NULL)::bool AS missing - FROM tracks - WHERE album_id = $1 - ORDER BY disc_number NULLS FIRST, track_number NULLS LAST, title -` - -type ListLibraryAlbumTracksRow struct { - Title string - DiscNumber *int32 - TrackNumber *int32 - DurationMs int32 - Missing bool -} - -// A held or missing album's own tracks, for the Wanted view's track list; -// missing says its file is gone. -func (q *Queries) ListLibraryAlbumTracks(ctx context.Context, albumID pgtype.UUID) ([]ListLibraryAlbumTracksRow, error) { - rows, err := q.db.Query(ctx, listLibraryAlbumTracks, albumID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListLibraryAlbumTracksRow - for rows.Next() { - var i ListLibraryAlbumTracksRow - if err := rows.Scan( - &i.Title, - &i.DiscNumber, - &i.TrackNumber, - &i.DurationMs, - &i.Missing, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listLibraryAlbums = `-- name: ListLibraryAlbums :execrows -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id, wanted_at, fulfilled_at) -SELECT DISTINCT ON (a.release_group_mbid) - a.release_group_mbid, ar.mbid, ar.name, a.title, 'library', a.id, now(), - COALESCE((SELECT MIN(t.missing_since) FROM tracks t WHERE t.album_id = a.id) - interval '1 second', now()) - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - WHERE a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> '' - AND ar.mbid IS NOT NULL AND ar.mbid <> '' - AND a.created_at <= $1::timestamptz - AND ($2::uuid IS NULL OR a.id = $2::uuid) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) - ORDER BY a.release_group_mbid, - (SELECT COUNT(*) FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL) DESC, a.id -ON CONFLICT (release_group_mbid) DO NOTHING -` - -type ListLibraryAlbumsParams struct { - Cutoff pgtype.Timestamptz - AlbumID pgtype.UUID -} - -// Puts library albums on the list as held: each release group once, by the -// album holding the most tracks. Only albums the library had at the cutoff, -// and with album_id given only that album. A group already on the list is -// left as it is. An album with tracks already missing is held from just -// before the first loss, so re-acquisition still fetches it back. -func (q *Queries) ListLibraryAlbums(ctx context.Context, arg ListLibraryAlbumsParams) (int64, error) { - result, err := q.db.Exec(ctx, listLibraryAlbums, arg.Cutoff, arg.AlbumID) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const listOpenWants = `-- name: ListOpenWants :many -SELECT id, release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date, reason, album_id, created_by, wanted_at, fulfilled_at, created_at, updated_at, searched_at, search_outcome, search_considered, best_release, best_verdict, search_error, upgrade, held_tier, held_quality, upgrade_checked_at FROM wants - WHERE fulfilled_at IS NULL - ORDER BY wanted_at, id - LIMIT $1 -` - -func (q *Queries) ListOpenWants(ctx context.Context, limit int32) ([]Want, error) { - rows, err := q.db.Query(ctx, listOpenWants, limit) - if err != nil { - return nil, err - } - defer rows.Close() - var items []Want - for rows.Next() { - var i Want - if err := rows.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.Title, - &i.PrimaryType, - &i.FirstReleaseDate, - &i.Reason, - &i.AlbumID, - &i.CreatedBy, - &i.WantedAt, - &i.FulfilledAt, - &i.CreatedAt, - &i.UpdatedAt, - &i.SearchedAt, - &i.SearchOutcome, - &i.SearchConsidered, - &i.BestRelease, - &i.BestVerdict, - &i.SearchError, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.UpgradeCheckedAt, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listReleaseTypeProfiles = `-- name: ListReleaseTypeProfiles :many - -SELECT p.id, p.name, p.primary_types, p.secondary_types, p.is_default, p.created_at, p.updated_at, - (SELECT COUNT(*) FROM follows f WHERE f.profile_id = p.id)::bigint AS follow_count - FROM release_type_profiles p - ORDER BY p.is_default DESC, p.name -` - -type ListReleaseTypeProfilesRow struct { - ID pgtype.UUID - Name string - PrimaryTypes []string - SecondaryTypes []string - IsDefault bool - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz - FollowCount int64 -} - -// The wanted list: release-type profiles, follows and wants. -func (q *Queries) ListReleaseTypeProfiles(ctx context.Context) ([]ListReleaseTypeProfilesRow, error) { - rows, err := q.db.Query(ctx, listReleaseTypeProfiles) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListReleaseTypeProfilesRow - for rows.Next() { - var i ListReleaseTypeProfilesRow - if err := rows.Scan( - &i.ID, - &i.Name, - &i.PrimaryTypes, - &i.SecondaryTypes, - &i.IsDefault, - &i.CreatedAt, - &i.UpdatedAt, - &i.FollowCount, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listUnmatchedLibraryAlbums = `-- name: ListUnmatchedLibraryAlbums :many -SELECT m.album_id, a.title, ar.name AS artist_name, m.detail, m.outcome, m.decided_at, - (SELECT COUNT(*) FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL)::int AS tracks - FROM library_album_matches m - JOIN albums a ON a.id = m.album_id - JOIN artists ar ON ar.id = a.artist_id - WHERE m.outcome IN ('unmatched', 'dismissed') - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id) - ORDER BY m.outcome DESC, lower(ar.name), lower(a.title) - LIMIT $1 -` - -type ListUnmatchedLibraryAlbumsRow struct { - AlbumID pgtype.UUID - Title string - ArtistName string - Detail string - Outcome string - DecidedAt pgtype.Timestamptz - Tracks int32 -} - -// The Collection's Unmatched section: the albums the listing could -// not match, and below them the ones a person left off. An album whose -// tracks have all moved to another row is gone, not unmatched. -func (q *Queries) ListUnmatchedLibraryAlbums(ctx context.Context, maxRows int32) ([]ListUnmatchedLibraryAlbumsRow, error) { - rows, err := q.db.Query(ctx, listUnmatchedLibraryAlbums, maxRows) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListUnmatchedLibraryAlbumsRow - for rows.Next() { - var i ListUnmatchedLibraryAlbumsRow - if err := rows.Scan( - &i.AlbumID, - &i.Title, - &i.ArtistName, - &i.Detail, - &i.Outcome, - &i.DecidedAt, - &i.Tracks, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listWantArtists = `-- name: ListWantArtists :many -WITH a AS ( - SELECT w.artist_mbid, - (array_agg(w.artist_name ORDER BY w.wanted_at DESC))[1] AS artist_name, - COUNT(*) FILTER (WHERE w.fulfilled_at IS NOT NULL)::int AS held, - COUNT(*) FILTER (WHERE w.fulfilled_at IS NULL AND w.reason <> 'missing')::int AS wanted, - COUNT(*) FILTER (WHERE w.fulfilled_at IS NULL AND w.reason = 'missing')::int AS missing, - COUNT(*)::int AS albums, - bool_or($1::text <> '' AND strpos(lower(w.title), lower($1::text)) > 0) AS title_match - FROM wants w - WHERE $4::text = '' OR w.artist_mbid = $4::text - GROUP BY w.artist_mbid -) -SELECT a.artist_mbid, a.artist_name::text AS artist_name, a.held, a.wanted, a.missing, a.albums, - COALESCE(NULLIF(la.sort_name, ''), a.artist_name)::text AS sort_name, - la.id AS library_artist_id, - (f.artist_mbid IS NOT NULL)::bool AS following, - (SELECT COUNT(*) FROM grabs g JOIN wants x ON x.id = g.want_id - WHERE x.artist_mbid = a.artist_mbid AND g.ended_at IS NULL)::int AS downloading, - COUNT(*) OVER () AS total - FROM a - LEFT JOIN LATERAL (SELECT ar.id, ar.sort_name FROM artists ar WHERE ar.mbid = a.artist_mbid LIMIT 1) la ON true - LEFT JOIN follows f ON f.artist_mbid = a.artist_mbid - WHERE $1::text = '' - OR strpos(lower(a.artist_name), lower($1::text)) > 0 - OR a.title_match - ORDER BY lower(COALESCE(NULLIF(la.sort_name, ''), a.artist_name)), a.artist_mbid - LIMIT $3 OFFSET $2 -` - -type ListWantArtistsParams struct { - Q string - Skip int32 - MaxRows int32 - ArtistMbid string -} - -type ListWantArtistsRow struct { - ArtistMbid string - ArtistName string - Held int32 - Wanted int32 - Missing int32 - Albums int32 - SortName string - LibraryArtistID pgtype.UUID - Following bool - Downloading int32 - Total int64 -} - -// The Wanted view's main page: every artist on the list, A–Z like -// the library, with how many of their albums are held of how many are on -// the list. q matches the artist's name or any of their albums' titles; -// artist_mbid narrows to one artist, for their page's header. -func (q *Queries) ListWantArtists(ctx context.Context, arg ListWantArtistsParams) ([]ListWantArtistsRow, error) { - rows, err := q.db.Query(ctx, listWantArtists, - arg.Q, - arg.Skip, - arg.MaxRows, - arg.ArtistMbid, - ) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListWantArtistsRow - for rows.Next() { - var i ListWantArtistsRow - if err := rows.Scan( - &i.ArtistMbid, - &i.ArtistName, - &i.Held, - &i.Wanted, - &i.Missing, - &i.Albums, - &i.SortName, - &i.LibraryArtistID, - &i.Following, - &i.Downloading, - &i.Total, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listWants = `-- name: ListWants :many -SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.reason, - w.album_id, w.wanted_at, w.fulfilled_at, - -- Why a held album is wanted again, and the copy it has. - w.upgrade, w.held_quality, - -- A request names an album before the catalogue has read it: the - -- catalogue's type and date fill in once it has. - COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type, - COALESCE(g.secondary_types, '{}')::text[] AS secondary_types, - COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date, - u.username AS requested_by, - la.id AS library_artist_id, - COUNT(*) OVER () AS total, - -- The search schedule's last look, and the download running. - w.searched_at, w.search_outcome, w.search_considered, w.best_release, w.best_verdict, w.search_error, - -- Its latest download, running or ended, and what the import made of - -- it. - gr.id AS grab_id, gr.name AS grab_name, gr.grabbed_at, gr.origin AS grab_origin, - gr.quality AS grab_quality, gr.ended_at AS grab_ended_at, gr.end_reason AS grab_end_reason, - gr.progress AS grab_progress, gr.import_state AS grab_import_state, - gr.import_reason AS grab_import_reason, gr.end_detail AS grab_end_detail, gr.imported_at AS grab_imported_at, - gr.imported_files AS grab_imported_files - FROM wants w - LEFT JOIN users u ON u.id = w.created_by - LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid - LEFT JOIN LATERAL (SELECT ar.id, ar.sort_name FROM artists ar WHERE ar.mbid = w.artist_mbid LIMIT 1) la ON true - LEFT JOIN grabs gr ON gr.id = (SELECT x.id FROM grabs x WHERE x.want_id = w.id - ORDER BY x.ended_at IS NULL DESC, x.grabbed_at DESC LIMIT 1) - WHERE CASE $1::text - WHEN 'all' THEN true - WHEN 'held' THEN w.fulfilled_at IS NOT NULL - WHEN 'upgrade' THEN w.fulfilled_at IS NOT NULL AND w.upgrade <> '' - WHEN 'missing' THEN w.fulfilled_at IS NULL AND w.reason = 'missing' - ELSE w.fulfilled_at IS NULL AND w.reason <> 'missing' - END - AND ($2::text = '' OR w.artist_mbid = $2::text) - -- want_ids narrows to given wants: the Missing page's folders. - AND (COALESCE(cardinality($3::uuid[]), 0) = 0 OR w.id = ANY($3::uuid[])) - AND ($4::text = '' - OR strpos(lower(w.artist_name), lower($4::text)) > 0 - OR strpos(lower(w.title), lower($4::text)) > 0) - ORDER BY lower(COALESCE(NULLIF(la.sort_name, ''), w.artist_name)), w.artist_mbid, - NULLIF(COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, ''), '') NULLS LAST, - lower(w.title), w.id - LIMIT $6 OFFSET $5 -` - -type ListWantsParams struct { - State string - ArtistMbid string - WantIds []pgtype.UUID - Q string - Skip int32 - MaxRows int32 -} - -type ListWantsRow struct { - ID pgtype.UUID - ReleaseGroupMbid string - ArtistMbid string - ArtistName string - Title string - Reason string - AlbumID pgtype.UUID - WantedAt pgtype.Timestamptz - FulfilledAt pgtype.Timestamptz - Upgrade string - HeldQuality string - PrimaryType string - SecondaryTypes []string - FirstReleaseDate string - RequestedBy *string - LibraryArtistID pgtype.UUID - Total int64 - SearchedAt pgtype.Timestamptz - SearchOutcome string - SearchConsidered int32 - BestRelease string - BestVerdict string - SearchError string - GrabID pgtype.UUID - GrabName *string - GrabbedAt pgtype.Timestamptz - GrabOrigin *string - GrabQuality *string - GrabEndedAt pgtype.Timestamptz - GrabEndReason *string - GrabProgress *float32 - GrabImportState *string - GrabImportReason *string - GrabEndDetail *string - GrabImportedAt pgtype.Timestamptz - GrabImportedFiles *int32 -} - -// The Wanted page: open wants (all but missing ones, or only missing ones), -// the held ones, or all of them; artist_mbid narrows to one artist's page, -// want_ids to given wants. Ordered like the library: artists A–Z by the -// library's sort name when it holds the artist, each artist's albums by -// release date, so the page groups them as they arrive. q narrows to an -// artist or album title; total counts every match, past the page. -func (q *Queries) ListWants(ctx context.Context, arg ListWantsParams) ([]ListWantsRow, error) { - rows, err := q.db.Query(ctx, listWants, - arg.State, - arg.ArtistMbid, - arg.WantIds, - arg.Q, - arg.Skip, - arg.MaxRows, - ) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListWantsRow - for rows.Next() { - var i ListWantsRow - if err := rows.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.Title, - &i.Reason, - &i.AlbumID, - &i.WantedAt, - &i.FulfilledAt, - &i.Upgrade, - &i.HeldQuality, - &i.PrimaryType, - &i.SecondaryTypes, - &i.FirstReleaseDate, - &i.RequestedBy, - &i.LibraryArtistID, - &i.Total, - &i.SearchedAt, - &i.SearchOutcome, - &i.SearchConsidered, - &i.BestRelease, - &i.BestVerdict, - &i.SearchError, - &i.GrabID, - &i.GrabName, - &i.GrabbedAt, - &i.GrabOrigin, - &i.GrabQuality, - &i.GrabEndedAt, - &i.GrabEndReason, - &i.GrabProgress, - &i.GrabImportState, - &i.GrabImportReason, - &i.GrabEndDetail, - &i.GrabImportedAt, - &i.GrabImportedFiles, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const markFollowChecked = `-- name: MarkFollowChecked :exec -UPDATE follows - SET checked_at = now(), - baseline_at = COALESCE(baseline_at, now()), - want_existing = false, - updated_at = now() - WHERE artist_mbid = $1 -` - -func (q *Queries) MarkFollowChecked(ctx context.Context, artistMbid string) error { - _, err := q.db.Exec(ctx, markFollowChecked, artistMbid) - return err -} - -const markGroupSeen = `-- name: MarkGroupSeen :exec -INSERT INTO follow_seen_groups (artist_mbid, release_group_mbid) -VALUES ($1, $2) -ON CONFLICT DO NOTHING -` - -type MarkGroupSeenParams struct { - ArtistMbid string - ReleaseGroupMbid string -} - -func (q *Queries) MarkGroupSeen(ctx context.Context, arg MarkGroupSeenParams) error { - _, err := q.db.Exec(ctx, markGroupSeen, arg.ArtistMbid, arg.ReleaseGroupMbid) - return err -} - -const recordAlbumMatch = `-- name: RecordAlbumMatch :exec -INSERT INTO library_album_matches (album_id, outcome, method, release_group_mbid, detail, matcher) -VALUES ($1, $2, $3, $4, $5, - $6) -ON CONFLICT (album_id) DO UPDATE - SET outcome = EXCLUDED.outcome, method = EXCLUDED.method, release_group_mbid = EXCLUDED.release_group_mbid, - detail = EXCLUDED.detail, matcher = EXCLUDED.matcher, decided_at = now() -` - -type RecordAlbumMatchParams struct { - AlbumID pgtype.UUID - Outcome string - Method string - ReleaseGroupMbid string - Detail string - Matcher int32 -} - -func (q *Queries) RecordAlbumMatch(ctx context.Context, arg RecordAlbumMatchParams) error { - _, err := q.db.Exec(ctx, recordAlbumMatch, - arg.AlbumID, - arg.Outcome, - arg.Method, - arg.ReleaseGroupMbid, - arg.Detail, - arg.Matcher, - ) - return err -} - -const recordListedAlbums = `-- name: RecordListedAlbums :exec -INSERT INTO library_album_matches (album_id, outcome, method, release_group_mbid) -SELECT a.id, 'listed', 'tags', a.release_group_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - WHERE a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> '' - AND ar.mbid IS NOT NULL AND ar.mbid <> '' - AND a.created_at <= $1::timestamptz - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) -ON CONFLICT (album_id) DO NOTHING -` - -// The albums ListLibraryAlbums takes are decided as listed by their tags, -// so the matching that follows leaves them alone. -func (q *Queries) RecordListedAlbums(ctx context.Context, cutoff pgtype.Timestamptz) error { - _, err := q.db.Exec(ctx, recordListedAlbums, cutoff) - return err -} - -const recountLibraryUnlisted = `-- name: RecountLibraryUnlisted :exec -UPDATE acquisition_settings - SET library_unlisted = (SELECT COUNT(*) FROM library_album_matches m - WHERE m.outcome = 'unmatched' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id)) - WHERE id = true -` - -// After a person matches or leaves off an album, the count the catalogue -// shows. -func (q *Queries) RecountLibraryUnlisted(ctx context.Context) error { - _, err := q.db.Exec(ctx, recountLibraryUnlisted) - return err -} - -const repointWant = `-- name: RepointWant :exec -UPDATE wants SET release_group_mbid = $2, updated_at = now() WHERE id = $1 -` - -type RepointWantParams struct { - ID pgtype.UUID - ReleaseGroupMbid string -} - -// A want recorded under a release id is moved to its group. -func (q *Queries) RepointWant(ctx context.Context, arg RepointWantParams) error { - _, err := q.db.Exec(ctx, repointWant, arg.ID, arg.ReleaseGroupMbid) - return err -} - -const setAlbumMatchOutcome = `-- name: SetAlbumMatchOutcome :execrows -UPDATE library_album_matches SET outcome = $1, decided_at = now() - WHERE album_id = $2 AND outcome = $3 -` - -type SetAlbumMatchOutcomeParams struct { - Outcome string - AlbumID pgtype.UUID - Was string -} - -// Leave an unmatched album off the list, or put a left-off one back. -func (q *Queries) SetAlbumMatchOutcome(ctx context.Context, arg SetAlbumMatchOutcomeParams) (int64, error) { - result, err := q.db.Exec(ctx, setAlbumMatchOutcome, arg.Outcome, arg.AlbumID, arg.Was) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const setAlbumReleaseGroup = `-- name: SetAlbumReleaseGroup :exec -UPDATE albums SET release_group_mbid = $1, updated_at = now() - WHERE id = $2 AND (release_group_mbid IS NULL OR release_group_mbid = '') -` - -type SetAlbumReleaseGroupParams struct { - ReleaseGroupMbid *string - ID pgtype.UUID -} - -// Names a matched album's release group, filling only what nothing named. -func (q *Queries) SetAlbumReleaseGroup(ctx context.Context, arg SetAlbumReleaseGroupParams) error { - _, err := q.db.Exec(ctx, setAlbumReleaseGroup, arg.ReleaseGroupMbid, arg.ID) - return err -} - -const setDefaultReleaseTypeProfile = `-- name: SetDefaultReleaseTypeProfile :execrows -UPDATE release_type_profiles SET is_default = true, updated_at = now() WHERE id = $1 -` - -func (q *Queries) SetDefaultReleaseTypeProfile(ctx context.Context, id pgtype.UUID) (int64, error) { - result, err := q.db.Exec(ctx, setDefaultReleaseTypeProfile, id) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - -const setWantUpgrades = `-- name: SetWantUpgrades :exec -UPDATE wants w - SET upgrade = v.upgrade, - held_tier = v.held_tier, - held_quality = v.held_quality, - upgrade_checked_at = now(), - updated_at = CASE WHEN w.upgrade <> v.upgrade THEN now() ELSE w.updated_at END - FROM (SELECT unnest($1::uuid[]) AS id, - unnest($2::text[]) AS upgrade, - unnest($3::text[]) AS held_tier, - unnest($4::text[]) AS held_quality) v - WHERE w.id = v.id -` - -type SetWantUpgradesParams struct { - Ids []pgtype.UUID - Upgrades []string - HeldTiers []string - HeldQualities []string -} - -// Writes the upgrade check's verdicts, one row per want. -func (q *Queries) SetWantUpgrades(ctx context.Context, arg SetWantUpgradesParams) error { - _, err := q.db.Exec(ctx, setWantUpgrades, - arg.Ids, - arg.Upgrades, - arg.HeldTiers, - arg.HeldQualities, - ) - return err -} - -const startLibraryListing = `-- name: StartLibraryListing :one -UPDATE acquisition_settings - SET library_listing_started_at = COALESCE(library_listing_started_at, now()) - WHERE id = true -RETURNING library_listing_started_at -` - -// Marks the listing begun, once; its time is the cutoff for which albums -// count as the library's. -func (q *Queries) StartLibraryListing(ctx context.Context) (pgtype.Timestamptz, error) { - row := q.db.QueryRow(ctx, startLibraryListing) - var library_listing_started_at pgtype.Timestamptz - err := row.Scan(&library_listing_started_at) - return library_listing_started_at, err -} - -const updateReleaseTypeProfile = `-- name: UpdateReleaseTypeProfile :one -UPDATE release_type_profiles - SET name = $2, - primary_types = $3, - secondary_types = $4, - updated_at = now() - WHERE id = $1 -RETURNING id, name, primary_types, secondary_types, is_default, created_at, updated_at -` - -type UpdateReleaseTypeProfileParams struct { - ID pgtype.UUID - Name string - PrimaryTypes []string - SecondaryTypes []string -} - -func (q *Queries) UpdateReleaseTypeProfile(ctx context.Context, arg UpdateReleaseTypeProfileParams) (ReleaseTypeProfile, error) { - row := q.db.QueryRow(ctx, updateReleaseTypeProfile, - arg.ID, - arg.Name, - arg.PrimaryTypes, - arg.SecondaryTypes, - ) - var i ReleaseTypeProfile - err := row.Scan( - &i.ID, - &i.Name, - &i.PrimaryTypes, - &i.SecondaryTypes, - &i.IsDefault, - &i.CreatedAt, - &i.UpdatedAt, - ) - return i, err -} - -const upsertFollow = `-- name: UpsertFollow :one -INSERT INTO follows (artist_mbid, artist_name, profile_id, followed_by, want_existing) -VALUES ($1, $2, $3, - $4, $5) -ON CONFLICT (artist_mbid) DO UPDATE - SET artist_name = EXCLUDED.artist_name, - profile_id = EXCLUDED.profile_id, - want_existing = follows.want_existing OR EXCLUDED.want_existing, - baseline_at = CASE WHEN EXCLUDED.want_existing THEN NULL ELSE follows.baseline_at END, - updated_at = now() -RETURNING artist_mbid, artist_name, profile_id, followed_by, followed_at, baseline_at, want_existing, checked_at, updated_at -` - -type UpsertFollowParams struct { - ArtistMbid string - ArtistName string - ProfileID pgtype.UUID - FollowedBy pgtype.UUID - WantExisting bool -} - -// Following an artist already followed changes its profile. want_existing -// only ever turns on here; the worker turns it off once applied, and turning -// it on again re-reads the baseline so the existing releases are judged. -func (q *Queries) UpsertFollow(ctx context.Context, arg UpsertFollowParams) (Follow, error) { - row := q.db.QueryRow(ctx, upsertFollow, - arg.ArtistMbid, - arg.ArtistName, - arg.ProfileID, - arg.FollowedBy, - arg.WantExisting, - ) - var i Follow - err := row.Scan( - &i.ArtistMbid, - &i.ArtistName, - &i.ProfileID, - &i.FollowedBy, - &i.FollowedAt, - &i.BaselineAt, - &i.WantExisting, - &i.CheckedAt, - &i.UpdatedAt, - ) - return i, err -} - -const wantHoldings = `-- name: WantHoldings :many -SELECT a.id AS album_id, - COUNT(*) FILTER (WHERE t.missing_since IS NULL)::int AS present, - COALESCE(bool_or(t.missing_since IS NULL AND t.added_at > $1::timestamptz), false)::bool AS arrived_since, - COALESCE(bool_or(t.missing_since IS NOT NULL AND t.missing_since < $1::timestamptz), false)::bool AS missing_before, - -- Missing tracks no track on disk stands in for, by position or - -- title. A missing row whose song is back at a new path is - -- covered; a lost bonus track is not. A track with no disc number is - -- on disc 1, so a missing track 6 with no disc beside a present 1/6 - -- does not keep the album wanted. - COUNT(*) FILTER (WHERE t.missing_since IS NOT NULL AND NOT EXISTS ( - SELECT 1 FROM tracks p - WHERE p.album_id = a.id AND p.missing_since IS NULL - AND ((p.track_number = t.track_number AND COALESCE(p.disc_number, 1) = COALESCE(t.disc_number, 1)) - OR lower(p.title) = lower(t.title))))::int AS uncovered_missing - FROM albums a - JOIN tracks t ON t.album_id = a.id - WHERE a.release_group_mbid = $2::text - OR a.mbid = $2 - OR a.id = $3 - OR a.mbid IN (SELECT r.mbid FROM mb_releases r WHERE r.release_group_mbid = $2) - GROUP BY a.id - ORDER BY present DESC, a.id -` - -type WantHoldingsParams struct { - Since pgtype.Timestamptz - GroupMbid string - AlbumID pgtype.UUID -} - -type WantHoldingsRow struct { - AlbumID pgtype.UUID - Present int32 - ArrivedSince bool - MissingBefore bool - UncoveredMissing int32 -} - -// Each library album that may answer a want, with what it has on disk: -// tracks present, whether one arrived since the want, and whether a track -// missing before the want is still missing. -func (q *Queries) WantHoldings(ctx context.Context, arg WantHoldingsParams) ([]WantHoldingsRow, error) { - rows, err := q.db.Query(ctx, wantHoldings, arg.Since, arg.GroupMbid, arg.AlbumID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []WantHoldingsRow - for rows.Next() { - var i WantHoldingsRow - if err := rows.Scan( - &i.AlbumID, - &i.Present, - &i.ArrivedSince, - &i.MissingBefore, - &i.UncoveredMissing, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const wantReleaseGroup = `-- name: WantReleaseGroup :one -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, primary_type, - first_release_date, reason, created_by) -VALUES ($1, $2, $3, $4, - $5, $6, $7, $8) -ON CONFLICT (release_group_mbid) DO UPDATE SET updated_at = wants.updated_at -RETURNING id, release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date, reason, album_id, created_by, wanted_at, fulfilled_at, created_at, updated_at, searched_at, search_outcome, search_considered, best_release, best_verdict, search_error, upgrade, held_tier, held_quality, upgrade_checked_at -` - -type WantReleaseGroupParams struct { - ReleaseGroupMbid string - ArtistMbid string - ArtistName string - Title string - PrimaryType string - FirstReleaseDate string - Reason string - CreatedBy pgtype.UUID -} - -// Wants a release group, or returns the want already recorded for it. A -// held want is not reopened here: the library has it. -func (q *Queries) WantReleaseGroup(ctx context.Context, arg WantReleaseGroupParams) (Want, error) { - row := q.db.QueryRow(ctx, wantReleaseGroup, - arg.ReleaseGroupMbid, - arg.ArtistMbid, - arg.ArtistName, - arg.Title, - arg.PrimaryType, - arg.FirstReleaseDate, - arg.Reason, - arg.CreatedBy, - ) - var i Want - err := row.Scan( - &i.ID, - &i.ReleaseGroupMbid, - &i.ArtistMbid, - &i.ArtistName, - &i.Title, - &i.PrimaryType, - &i.FirstReleaseDate, - &i.Reason, - &i.AlbumID, - &i.CreatedBy, - &i.WantedAt, - &i.FulfilledAt, - &i.CreatedAt, - &i.UpdatedAt, - &i.SearchedAt, - &i.SearchOutcome, - &i.SearchConsidered, - &i.BestRelease, - &i.BestVerdict, - &i.SearchError, - &i.Upgrade, - &i.HeldTier, - &i.HeldQuality, - &i.UpgradeCheckedAt, - ) - return i, err -} diff --git a/internal/db/dbq/you_might_like.sql.go b/internal/db/dbq/you_might_like.sql.go index a389b7e2..a2127f91 100644 --- a/internal/db/dbq/you_might_like.sql.go +++ b/internal/db/dbq/you_might_like.sql.go @@ -102,7 +102,7 @@ WITH liked_album_ids AS ( JOIN tracks trk ON trk.id = likt.track_id WHERE likt.user_id = $1 ) -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM liked_album_ids lai JOIN albums ON albums.id = lai.album_id JOIN artists ON artists.id = albums.artist_id @@ -144,6 +144,7 @@ func (q *Queries) ListYouMightLikeAlbumFallbackForUser(ctx context.Context, arg &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err @@ -157,7 +158,7 @@ func (q *Queries) ListYouMightLikeAlbumFallbackForUser(ctx context.Context, arg } const listYouMightLikeAlbumsForUser = `-- name: ListYouMightLikeAlbumsForUser :many -SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.name AS artist_name +SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, albums.announced_at, artists.name AS artist_name FROM you_might_like_albums yml JOIN albums ON albums.id = yml.album_id JOIN artists ON artists.id = albums.artist_id @@ -203,6 +204,7 @@ func (q *Queries) ListYouMightLikeAlbumsForUser(ctx context.Context, arg ListYou &i.Album.CoverArtSource, &i.Album.CoverArtSourcesVersion, &i.Album.ReleaseGroupMbid, + &i.Album.AnnouncedAt, &i.ArtistName, ); err != nil { return nil, err diff --git a/internal/db/errors.go b/internal/db/errors.go new file mode 100644 index 00000000..14e91922 --- /dev/null +++ b/internal/db/errors.go @@ -0,0 +1,17 @@ +package db + +import ( + "errors" + + "github.com/jackc/pgerrcode" + "github.com/jackc/pgx/v5/pgconn" +) + +// IsUniqueViolation reports whether err is Postgres refusing a row because +// another row already holds the same unique value: a username or email +// that is taken, or a second album row claiming one MBID. Callers use it to +// tell "that already exists" apart from a write that failed. +func IsUniqueViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation +} diff --git a/internal/db/migrations/0001_init.down.sql b/internal/db/migrations/0001_init.down.sql deleted file mode 100644 index f1ce7100..00000000 --- a/internal/db/migrations/0001_init.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Placeholder down migration — nothing to reverse. -SELECT 1; diff --git a/internal/db/migrations/0001_init.up.sql b/internal/db/migrations/0001_init.up.sql deleted file mode 100644 index 25f4c2ce..00000000 --- a/internal/db/migrations/0001_init.up.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Placeholder to establish the migration runner. Real schema lands in 0002. -SELECT 1; diff --git a/internal/db/migrations/0002_core_library.down.sql b/internal/db/migrations/0002_core_library.down.sql deleted file mode 100644 index e6b4bf3e..00000000 --- a/internal/db/migrations/0002_core_library.down.sql +++ /dev/null @@ -1,5 +0,0 @@ -DROP TABLE IF EXISTS users; -DROP TABLE IF EXISTS tracks; -DROP TABLE IF EXISTS albums; -DROP TABLE IF EXISTS artists; --- pgcrypto left installed; other extensions may depend on it. diff --git a/internal/db/migrations/0002_core_library.up.sql b/internal/db/migrations/0002_core_library.up.sql deleted file mode 100644 index 80cc3fe0..00000000 --- a/internal/db/migrations/0002_core_library.up.sql +++ /dev/null @@ -1,60 +0,0 @@ --- Core library schema: artists, albums, tracks and users. Likes, sessions, --- scrobbling and similarity get tables of their own in later migrations. - -CREATE EXTENSION IF NOT EXISTS "pgcrypto"; - -CREATE TABLE artists ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - name text NOT NULL, - sort_name text NOT NULL, - mbid text, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -CREATE UNIQUE INDEX artists_mbid_unique ON artists (mbid) WHERE mbid IS NOT NULL; -CREATE INDEX artists_sort_name ON artists (sort_name); - -CREATE TABLE albums ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - title text NOT NULL, - sort_title text NOT NULL, - artist_id uuid NOT NULL REFERENCES artists (id) ON DELETE CASCADE, - release_date date, - mbid text, - cover_art_path text, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -CREATE UNIQUE INDEX albums_mbid_unique ON albums (mbid) WHERE mbid IS NOT NULL; -CREATE INDEX albums_artist ON albums (artist_id); -CREATE INDEX albums_sort_title ON albums (sort_title); - -CREATE TABLE tracks ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - title text NOT NULL, - album_id uuid NOT NULL REFERENCES albums (id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists (id) ON DELETE CASCADE, - track_number integer, - disc_number integer, - duration_ms integer NOT NULL, - file_path text NOT NULL UNIQUE, - file_size bigint NOT NULL, - file_format text NOT NULL, - bitrate integer, - mbid text, - genre text, - added_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -CREATE UNIQUE INDEX tracks_mbid_unique ON tracks (mbid) WHERE mbid IS NOT NULL; -CREATE INDEX tracks_album ON tracks (album_id, disc_number, track_number); -CREATE INDEX tracks_artist ON tracks (artist_id); - -CREATE TABLE users ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - username text NOT NULL UNIQUE, - password_hash text NOT NULL, - api_token text NOT NULL UNIQUE, - is_admin boolean NOT NULL DEFAULT false, - created_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0003_subsonic_password.down.sql b/internal/db/migrations/0003_subsonic_password.down.sql deleted file mode 100644 index c46bad35..00000000 --- a/internal/db/migrations/0003_subsonic_password.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users DROP COLUMN IF EXISTS subsonic_password; diff --git a/internal/db/migrations/0003_subsonic_password.up.sql b/internal/db/migrations/0003_subsonic_password.up.sql deleted file mode 100644 index 304e0192..00000000 --- a/internal/db/migrations/0003_subsonic_password.up.sql +++ /dev/null @@ -1,7 +0,0 @@ --- Subsonic's token auth (t = md5(password + salt)) requires the server to --- compute md5 over the user's plaintext password. bcrypt (password_hash) is --- not reversible, so we store a *separate*, opt-in, plaintext credential used --- exclusively for the /rest/* legacy auth path. NULL means the user has not --- opted into Subsonic t/s auth and must use apiKey (OpenSubsonic) instead. - -ALTER TABLE users ADD COLUMN subsonic_password text; diff --git a/internal/db/migrations/0004_sessions.down.sql b/internal/db/migrations/0004_sessions.down.sql deleted file mode 100644 index 0d6115ac..00000000 --- a/internal/db/migrations/0004_sessions.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS sessions_user_id_idx; -DROP TABLE IF EXISTS sessions; diff --git a/internal/db/migrations/0004_sessions.up.sql b/internal/db/migrations/0004_sessions.up.sql deleted file mode 100644 index cac6544a..00000000 --- a/internal/db/migrations/0004_sessions.up.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Session tokens authenticate /api/* requests. We store sha256(token) so a --- read-only DB leak doesn't grant active sessions; the raw token lives only --- in the client's cookie (web) or bearer header (native clients). --- --- last_seen_at and user_agent (captured at issue time) are for an "active --- sessions" list. - -CREATE TABLE sessions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - token_hash bytea NOT NULL UNIQUE, - user_agent text NOT NULL DEFAULT '', - created_at timestamptz NOT NULL DEFAULT now(), - last_seen_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX sessions_user_id_idx ON sessions (user_id); diff --git a/internal/db/migrations/0005_events.down.sql b/internal/db/migrations/0005_events.down.sql deleted file mode 100644 index 96175523..00000000 --- a/internal/db/migrations/0005_events.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS skip_events; -DROP TABLE IF EXISTS play_events; -DROP TABLE IF EXISTS play_sessions; diff --git a/internal/db/migrations/0005_events.up.sql b/internal/db/migrations/0005_events.up.sql deleted file mode 100644 index bcfc20b0..00000000 --- a/internal/db/migrations/0005_events.up.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Listening telemetry: play_sessions, play_events, skip_events. --- The table is named play_sessions (not sessions — that table already --- exists from migration 0004 and holds HTTP auth sessions). Listening --- sessions are an entirely separate concept. --- --- session_vector_at_play is nullable: plays are recorded before the --- recommendation engine fills it. - -CREATE TABLE play_sessions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - started_at timestamptz NOT NULL, - ended_at timestamptz, - last_event_at timestamptz NOT NULL, - track_count integer NOT NULL DEFAULT 0, - client_id text -); -CREATE INDEX play_sessions_user_last_event_idx ON play_sessions (user_id, last_event_at DESC); - -CREATE TABLE play_events ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - session_id uuid NOT NULL REFERENCES play_sessions(id) ON DELETE CASCADE, - started_at timestamptz NOT NULL, - ended_at timestamptz, - duration_played_ms integer, - completion_ratio double precision, - was_skipped boolean NOT NULL DEFAULT false, - client_id text, - session_vector_at_play jsonb, - scrobbled_at timestamptz -); -CREATE INDEX play_events_user_started_idx ON play_events (user_id, started_at DESC); -CREATE INDEX play_events_user_track_idx ON play_events (user_id, track_id); - -CREATE TABLE skip_events ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - session_id uuid NOT NULL REFERENCES play_sessions(id) ON DELETE CASCADE, - skipped_at timestamptz NOT NULL, - position_ms integer NOT NULL -); -CREATE INDEX skip_events_user_skipped_idx ON skip_events (user_id, skipped_at DESC); diff --git a/internal/db/migrations/0006_likes.down.sql b/internal/db/migrations/0006_likes.down.sql deleted file mode 100644 index b3ca0692..00000000 --- a/internal/db/migrations/0006_likes.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS general_likes_artists; -DROP TABLE IF EXISTS general_likes_albums; -DROP TABLE IF EXISTS general_likes; diff --git a/internal/db/migrations/0006_likes.up.sql b/internal/db/migrations/0006_likes.up.sql deleted file mode 100644 index 9f34df31..00000000 --- a/internal/db/migrations/0006_likes.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Likes: three tables, one per entity type. general_likes was track-only; --- albums and artists get the same shape for Subsonic star/unstar. - -CREATE TABLE general_likes ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, track_id) -); -CREATE INDEX general_likes_user_liked_at_idx ON general_likes (user_id, liked_at DESC); - -CREATE TABLE general_likes_albums ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - album_id uuid NOT NULL REFERENCES albums(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, album_id) -); -CREATE INDEX general_likes_albums_user_liked_at_idx ON general_likes_albums (user_id, liked_at DESC); - -CREATE TABLE general_likes_artists ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, artist_id) -); -CREATE INDEX general_likes_artists_user_liked_at_idx ON general_likes_artists (user_id, liked_at DESC); diff --git a/internal/db/migrations/0007_contextual_likes.down.sql b/internal/db/migrations/0007_contextual_likes.down.sql deleted file mode 100644 index 942b4de2..00000000 --- a/internal/db/migrations/0007_contextual_likes.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS contextual_likes; diff --git a/internal/db/migrations/0007_contextual_likes.up.sql b/internal/db/migrations/0007_contextual_likes.up.sql deleted file mode 100644 index 69f14ae9..00000000 --- a/internal/db/migrations/0007_contextual_likes.up.sql +++ /dev/null @@ -1,28 +0,0 @@ --- contextual_likes captures a per-session-context snapshot at the time of each --- like. The recommendation engine uses these rows to compute --- contextual_match_score per (current session, candidate track). --- --- Multiple rows per (user, track) are allowed and expected — each row --- represents a like in a specific session context. Soft-deleted rows --- remain in the table (deleted_at populated) but are filtered out of the --- engine's queries via the partial index. Re-liking a previously-unliked --- track adds a NEW row (does not undelete the old one). - -CREATE TABLE contextual_likes ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - deleted_at timestamptz, - session_vector jsonb, - session_id uuid REFERENCES play_sessions(id) ON DELETE SET NULL -); - --- Hot path for both the engine's lookups and the soft-delete UPDATE. -CREATE INDEX contextual_likes_active_idx - ON contextual_likes (user_id, track_id) - WHERE deleted_at IS NULL; - --- For the engine's vector similarity queries. -CREATE INDEX contextual_likes_vector_idx - ON contextual_likes USING gin (session_vector); diff --git a/internal/db/migrations/0008_scrobble.down.sql b/internal/db/migrations/0008_scrobble.down.sql deleted file mode 100644 index c5721872..00000000 --- a/internal/db/migrations/0008_scrobble.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS scrobble_queue; -ALTER TABLE users DROP COLUMN IF EXISTS listenbrainz_enabled; -ALTER TABLE users DROP COLUMN IF EXISTS listenbrainz_token; diff --git a/internal/db/migrations/0008_scrobble.up.sql b/internal/db/migrations/0008_scrobble.up.sql deleted file mode 100644 index 32f3e15a..00000000 --- a/internal/db/migrations/0008_scrobble.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Outbound ListenBrainz scrobble worker. --- Per-user LB config (plaintext token; users rotate via /settings if leaked). --- scrobble_queue is a work list, not a log: successfully-sent rows are --- DELETEd by the worker (the canonical record stays in --- play_events.scrobbled_at). Only `pending` and `failed` states exist. - -ALTER TABLE users - ADD COLUMN listenbrainz_token TEXT NULL, - ADD COLUMN listenbrainz_enabled BOOLEAN NOT NULL DEFAULT FALSE; - -CREATE TABLE scrobble_queue ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - play_event_id uuid NOT NULL REFERENCES play_events(id) ON DELETE CASCADE, - status TEXT NOT NULL CHECK (status IN ('pending', 'failed')), - attempts INTEGER NOT NULL DEFAULT 0, - next_attempt_at timestamptz NOT NULL DEFAULT now(), - last_error TEXT NULL, - enqueued_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (play_event_id) -); - --- Hot path for the worker's per-tick query. -CREATE INDEX scrobble_queue_pending_idx - ON scrobble_queue (next_attempt_at) - WHERE status = 'pending'; diff --git a/internal/db/migrations/0009_similarity.down.sql b/internal/db/migrations/0009_similarity.down.sql deleted file mode 100644 index b6718a77..00000000 --- a/internal/db/migrations/0009_similarity.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS artist_similarity; -DROP TABLE IF EXISTS track_similarity; diff --git a/internal/db/migrations/0009_similarity.up.sql b/internal/db/migrations/0009_similarity.up.sql deleted file mode 100644 index 382631c2..00000000 --- a/internal/db/migrations/0009_similarity.up.sql +++ /dev/null @@ -1,33 +0,0 @@ --- ListenBrainz similarity ingest. Two symmetric tables — tracks and --- artists — both keyed by (a_id, b_id, source) so the schema reserves room --- for additional similarity sources (musicbrainz_tag, user_cooccurrence) --- alongside listenbrainz. M4b only writes 'listenbrainz' rows. --- --- The (a_id, score DESC) index satisfies M4c's hot path: "for seed S, give --- me top-N similar tracks/artists descending by score." - -CREATE TABLE track_similarity ( - track_a_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - track_b_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - score DOUBLE PRECISION NOT NULL, - source TEXT NOT NULL CHECK (source IN ('listenbrainz', 'musicbrainz_tag', 'user_cooccurrence')), - fetched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (track_a_id, track_b_id, source), - CHECK (track_a_id <> track_b_id) -); - -CREATE INDEX track_similarity_a_score_idx - ON track_similarity (track_a_id, score DESC); - -CREATE TABLE artist_similarity ( - artist_a_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - artist_b_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - score DOUBLE PRECISION NOT NULL, - source TEXT NOT NULL CHECK (source IN ('listenbrainz', 'musicbrainz_tag', 'user_cooccurrence')), - fetched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (artist_a_id, artist_b_id, source), - CHECK (artist_a_id <> artist_b_id) -); - -CREATE INDEX artist_similarity_a_score_idx - ON artist_similarity (artist_a_id, score DESC); diff --git a/internal/db/migrations/0010_lidarr.down.sql b/internal/db/migrations/0010_lidarr.down.sql deleted file mode 100644 index a6aabe02..00000000 --- a/internal/db/migrations/0010_lidarr.down.sql +++ /dev/null @@ -1,8 +0,0 @@ -DROP INDEX IF EXISTS lidarr_requests_album_mbid_idx; -DROP INDEX IF EXISTS lidarr_requests_artist_mbid_idx; -DROP INDEX IF EXISTS lidarr_requests_status_idx; -DROP INDEX IF EXISTS lidarr_requests_user_id_idx; -DROP TABLE IF EXISTS lidarr_requests; -DROP TYPE IF EXISTS lidarr_request_kind; -DROP TYPE IF EXISTS lidarr_request_status; -DROP TABLE IF EXISTS lidarr_config; diff --git a/internal/db/migrations/0010_lidarr.up.sql b/internal/db/migrations/0010_lidarr.up.sql deleted file mode 100644 index b2586ed1..00000000 --- a/internal/db/migrations/0010_lidarr.up.sql +++ /dev/null @@ -1,63 +0,0 @@ --- Lidarr integration. Two tables: --- --- lidarr_config — singleton (CHECK id=1) holding the Lidarr --- connection. enabled=false is the unconfigured state. --- --- lidarr_requests — per-request lifecycle row created by users at --- /discover, transitioned by admin at /admin/requests, and matched --- back to library tracks by the reconciler worker. Three matched_*_id --- FKs (one per kind) instead of polymorphic — clean SQL, ON DELETE --- SET NULL preserves audit even if the matched track is later removed. - -CREATE TABLE lidarr_config ( - id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), - enabled boolean NOT NULL DEFAULT false, - base_url text, - api_key text, - default_quality_profile_id int, - default_root_folder_path text, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -INSERT INTO lidarr_config (id, enabled) VALUES (1, false); - -CREATE TYPE lidarr_request_status AS ENUM ( - 'pending', 'approved', 'rejected', 'completed', 'failed' -); -CREATE TYPE lidarr_request_kind AS ENUM ('artist', 'album', 'track'); - -CREATE TABLE lidarr_requests ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - status lidarr_request_status NOT NULL DEFAULT 'pending', - kind lidarr_request_kind NOT NULL, - - lidarr_artist_mbid text NOT NULL, - lidarr_album_mbid text, - lidarr_track_mbid text, - artist_name text NOT NULL, - album_title text, - track_title text, - - quality_profile_id int, - root_folder_path text, - - decided_at timestamptz, - decided_by uuid REFERENCES users(id) ON DELETE SET NULL, - notes text, - - completed_at timestamptz, - matched_track_id uuid REFERENCES tracks(id) ON DELETE SET NULL, - matched_album_id uuid REFERENCES albums(id) ON DELETE SET NULL, - matched_artist_id uuid REFERENCES artists(id) ON DELETE SET NULL, - - requested_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX lidarr_requests_user_id_idx ON lidarr_requests (user_id); -CREATE INDEX lidarr_requests_status_idx ON lidarr_requests (status); -CREATE INDEX lidarr_requests_artist_mbid_idx ON lidarr_requests (lidarr_artist_mbid); -CREATE INDEX lidarr_requests_album_mbid_idx ON lidarr_requests (lidarr_album_mbid) - WHERE lidarr_album_mbid IS NOT NULL; diff --git a/internal/db/migrations/0011_lidarr_quarantine.down.sql b/internal/db/migrations/0011_lidarr_quarantine.down.sql deleted file mode 100644 index bd086c54..00000000 --- a/internal/db/migrations/0011_lidarr_quarantine.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -DROP INDEX IF EXISTS lidarr_quarantine_actions_created_idx; -DROP INDEX IF EXISTS lidarr_quarantine_actions_track_idx; -DROP TABLE IF EXISTS lidarr_quarantine_actions; -DROP TYPE IF EXISTS lidarr_quarantine_action_kind; -DROP INDEX IF EXISTS lidarr_quarantine_track_idx; -DROP TABLE IF EXISTS lidarr_quarantine; -DROP TYPE IF EXISTS lidarr_quarantine_reason; diff --git a/internal/db/migrations/0011_lidarr_quarantine.up.sql b/internal/db/migrations/0011_lidarr_quarantine.up.sql deleted file mode 100644 index 1d2443c9..00000000 --- a/internal/db/migrations/0011_lidarr_quarantine.up.sql +++ /dev/null @@ -1,48 +0,0 @@ --- Per-user track quarantines + admin action audit log. --- --- lidarr_quarantine — one row per (user, track) complaint. PK matches --- the general_likes pattern. Re-flagging the same track upserts. Deleted --- on user resolution (un-hide), admin Resolve, or any of the deletes. --- --- lidarr_quarantine_actions — audit log of admin destructive actions. --- Snapshot text columns let the log stay readable after the underlying --- track/album rows are gone. - -CREATE TYPE lidarr_quarantine_reason AS ENUM ( - 'bad_rip', 'wrong_file', 'wrong_tags', 'duplicate', 'other' -); - -CREATE TABLE lidarr_quarantine ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - reason lidarr_quarantine_reason NOT NULL, - notes text, - created_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, track_id) -); - --- Only the track_id index is non-redundant: the composite PK --- (user_id, track_id) already serves WHERE user_id = $1 lookups, so a --- separate (user_id, created_at DESC) index would just amplify writes --- without paying for itself at household-scale row counts. -CREATE INDEX lidarr_quarantine_track_idx ON lidarr_quarantine (track_id); - -CREATE TYPE lidarr_quarantine_action_kind AS ENUM ( - 'resolved', 'deleted_file', 'deleted_via_lidarr' -); - -CREATE TABLE lidarr_quarantine_actions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - track_id uuid NOT NULL, - track_title text NOT NULL, - artist_name text NOT NULL, - album_title text, - action lidarr_quarantine_action_kind NOT NULL, - admin_id uuid REFERENCES users(id) ON DELETE SET NULL, - lidarr_album_mbid text, - affected_users int NOT NULL, - created_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX lidarr_quarantine_actions_track_idx ON lidarr_quarantine_actions (track_id); -CREATE INDEX lidarr_quarantine_actions_created_idx ON lidarr_quarantine_actions (created_at DESC); diff --git a/internal/db/migrations/0012_artist_similarity_unmatched.down.sql b/internal/db/migrations/0012_artist_similarity_unmatched.down.sql deleted file mode 100644 index 29d52c9e..00000000 --- a/internal/db/migrations/0012_artist_similarity_unmatched.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS artist_similarity_unmatched_seed_score_idx; -DROP TABLE IF EXISTS artist_similarity_unmatched; diff --git a/internal/db/migrations/0012_artist_similarity_unmatched.up.sql b/internal/db/migrations/0012_artist_similarity_unmatched.up.sql deleted file mode 100644 index b89b7bb1..00000000 --- a/internal/db/migrations/0012_artist_similarity_unmatched.up.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Persist unmatched-similar-artist MBIDs that the M4b worker would --- otherwise discard. Mirrors artist_similarity shape: same composite PK --- with source, same (seed_id, score DESC) index, same source enum check. --- The candidate side is text + name (no FK) — that's the whole point. - -CREATE TABLE artist_similarity_unmatched ( - seed_artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - candidate_mbid text NOT NULL, - candidate_name text NOT NULL, - score DOUBLE PRECISION NOT NULL, - source text NOT NULL CHECK (source IN ('listenbrainz', 'musicbrainz_tag', 'user_cooccurrence')), - fetched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (seed_artist_id, candidate_mbid, source) -); - -CREATE INDEX artist_similarity_unmatched_seed_score_idx - ON artist_similarity_unmatched (seed_artist_id, score DESC); diff --git a/internal/db/migrations/0013_lidarr_metadata_profile.down.sql b/internal/db/migrations/0013_lidarr_metadata_profile.down.sql deleted file mode 100644 index 4f97bdba..00000000 --- a/internal/db/migrations/0013_lidarr_metadata_profile.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE lidarr_config - DROP COLUMN default_metadata_profile_id; diff --git a/internal/db/migrations/0013_lidarr_metadata_profile.up.sql b/internal/db/migrations/0013_lidarr_metadata_profile.up.sql deleted file mode 100644 index 627d46f9..00000000 --- a/internal/db/migrations/0013_lidarr_metadata_profile.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- Persist the chosen Lidarr metadata profile alongside quality profile + --- root folder. Lidarr POST /api/v1/artist requires metadataProfileId; --- without storing it every Approve would refetch and pick the first. --- Nullable: existing rows get NULL and the service falls back to "fetch --- list and pick first" until an admin saves. - -ALTER TABLE lidarr_config - ADD COLUMN default_metadata_profile_id integer; diff --git a/internal/db/migrations/0014_playlists.down.sql b/internal/db/migrations/0014_playlists.down.sql deleted file mode 100644 index 0e7e724d..00000000 --- a/internal/db/migrations/0014_playlists.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS playlist_tracks; -DROP TABLE IF EXISTS playlists; diff --git a/internal/db/migrations/0014_playlists.up.sql b/internal/db/migrations/0014_playlists.up.sql deleted file mode 100644 index 6cf9d825..00000000 --- a/internal/db/migrations/0014_playlists.up.sql +++ /dev/null @@ -1,38 +0,0 @@ --- User playlists. - -CREATE TABLE playlists ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - name text NOT NULL, - description text NOT NULL DEFAULT '', - is_public boolean NOT NULL DEFAULT false, - cover_path text, - track_count integer NOT NULL DEFAULT 0, - duration_sec integer NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX playlists_user_idx ON playlists (user_id, updated_at DESC); -CREATE INDEX playlists_public_idx ON playlists (is_public, updated_at DESC) WHERE is_public; - --- track_id is nullable + ON DELETE SET NULL so deleting a track from --- the library doesn't silently drop entries from operators' playlists. --- Denormalized title/artist/album/duration carry a snapshot so the row --- is still legible after the upstream track row is gone. -CREATE TABLE playlist_tracks ( - playlist_id uuid NOT NULL REFERENCES playlists(id) ON DELETE CASCADE, - position integer NOT NULL, - track_id uuid REFERENCES tracks(id) ON DELETE SET NULL, - title text NOT NULL, - artist_name text NOT NULL, - album_title text NOT NULL, - duration_sec integer NOT NULL, - added_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (playlist_id, position) -); - --- Partial index supports the FK lookup that fires when a track is --- deleted (ON DELETE SET NULL) — without it, deleting a track triggers --- a full scan of playlist_tracks. -CREATE INDEX playlist_tracks_track_idx ON playlist_tracks (track_id) WHERE track_id IS NOT NULL; diff --git a/internal/db/migrations/0015_system_playlists.down.sql b/internal/db/migrations/0015_system_playlists.down.sql deleted file mode 100644 index 9e7ef182..00000000 --- a/internal/db/migrations/0015_system_playlists.down.sql +++ /dev/null @@ -1,10 +0,0 @@ -DROP TABLE IF EXISTS system_playlist_runs; -DROP INDEX IF EXISTS playlists_user_kind_idx; -ALTER TABLE playlists - DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - DROP COLUMN IF EXISTS seed_artist_id, - DROP COLUMN IF EXISTS system_variant, - DROP COLUMN IF EXISTS kind; diff --git a/internal/db/migrations/0015_system_playlists.up.sql b/internal/db/migrations/0015_system_playlists.up.sql deleted file mode 100644 index 7e138ec5..00000000 --- a/internal/db/migrations/0015_system_playlists.up.sql +++ /dev/null @@ -1,46 +0,0 @@ --- System-generated playlists. --- Adds kind/system_variant/seed_artist_id columns to playlists and a --- per-user run-tracking table. Backfills existing playlists to --- kind='user'. - --- Discriminator on existing playlists table. -ALTER TABLE playlists - ADD COLUMN kind text NOT NULL DEFAULT 'user', - ADD COLUMN system_variant text, - ADD COLUMN seed_artist_id uuid REFERENCES artists(id) ON DELETE SET NULL; - --- Belt-and-braces backfill in case the DEFAULT didn't apply on some --- runtime branches; a no-op when the column metadata already filled. -UPDATE playlists SET kind = 'user' WHERE kind IS NULL OR kind = ''; - --- Constraint: kind/system_variant pair is consistent. -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent - CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist')) - ); - --- Constraint: 'songs_like_artist' has a seed artist; nothing else does. -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent - CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); - --- Filter index for kind=user vs kind=system queries on the user's row. -CREATE INDEX playlists_user_kind_idx ON playlists (user_id, kind); - --- Per-user run tracking — one row per user. -CREATE TABLE system_playlist_runs ( - user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - last_run_at timestamptz, - last_run_date date, - in_flight boolean NOT NULL DEFAULT false, - last_error text -); diff --git a/internal/db/migrations/0016_album_cover_source.down.sql b/internal/db/migrations/0016_album_cover_source.down.sql deleted file mode 100644 index 86c33bed..00000000 --- a/internal/db/migrations/0016_album_cover_source.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS albums_cover_art_source_idx; -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums DROP COLUMN IF EXISTS cover_art_source; diff --git a/internal/db/migrations/0016_album_cover_source.up.sql b/internal/db/migrations/0016_album_cover_source.up.sql deleted file mode 100644 index b198c989..00000000 --- a/internal/db/migrations/0016_album_cover_source.up.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Album cover origin attribution. --- 'embedded' — extracted from audio file (reserved). --- 'sidecar' — found in the album directory (cover.jpg/folder.jpg/etc). --- 'mbcaa' — fetched from MusicBrainz Cover Art Archive. --- 'none' — tried, no cover available. Skip auto-retry; only manual. -ALTER TABLE albums ADD COLUMN cover_art_source text; - -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded', 'sidecar', 'mbcaa', 'none')); - --- Backfill existing rows with cover_art_path set (defensive: scanner has --- never populated cover_art_path in current dev, but keeps re-runs idempotent). -UPDATE albums SET cover_art_source = 'sidecar' - WHERE cover_art_path IS NOT NULL AND cover_art_source IS NULL; - --- Index supports "find missing covers" queries. -CREATE INDEX albums_cover_art_source_idx ON albums (cover_art_source); diff --git a/internal/db/migrations/0017_scan_runs.down.sql b/internal/db/migrations/0017_scan_runs.down.sql deleted file mode 100644 index a498146a..00000000 --- a/internal/db/migrations/0017_scan_runs.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS scan_runs_started_at_idx; -DROP TABLE IF EXISTS scan_runs; diff --git a/internal/db/migrations/0017_scan_runs.up.sql b/internal/db/migrations/0017_scan_runs.up.sql deleted file mode 100644 index ed3a528b..00000000 --- a/internal/db/migrations/0017_scan_runs.up.sql +++ /dev/null @@ -1,20 +0,0 @@ --- Track library-scan / MBID-backfill / cover-enrich runs so the --- admin overview can show last-run results + manual trigger state. -CREATE TABLE scan_runs ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - started_at timestamptz NOT NULL DEFAULT now(), - finished_at timestamptz, - -- Per-stage tallies are jsonb so the schema doesn't need to grow when - -- a stage gains/loses a counter. Each stage's value matches the Go - -- struct emitted by that worker (e.g. library.Stats). - library jsonb, - mbid_backfill jsonb, - cover_enrich jsonb, - -- Non-empty when the run as a whole errored (a stage panic, or the - -- worker hit a fatal error before writing stage tallies). - error_message text -); - --- The status endpoint always reads the latest row; the in-flight guard --- needs to find rows where finished_at IS NULL. Both hit started_at DESC. -CREATE INDEX scan_runs_started_at_idx ON scan_runs (started_at DESC); diff --git a/internal/db/migrations/0018_artist_art_and_provider_settings.down.sql b/internal/db/migrations/0018_artist_art_and_provider_settings.down.sql deleted file mode 100644 index fae6f46c..00000000 --- a/internal/db/migrations/0018_artist_art_and_provider_settings.down.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Reverse of 0018. - -ALTER TABLE scan_runs DROP COLUMN IF EXISTS artist_art_enrich; - -DROP TABLE IF EXISTS cover_art_sources_meta; -DROP TABLE IF EXISTS cover_art_provider_settings; - -ALTER TABLE artists DROP COLUMN IF EXISTS artist_art_sources_version; -ALTER TABLE albums DROP COLUMN IF EXISTS cover_art_sources_version; - -DROP INDEX IF EXISTS artists_artist_art_source_idx; -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists DROP COLUMN IF EXISTS artist_art_source; -ALTER TABLE artists DROP COLUMN IF EXISTS artist_fanart_path; -ALTER TABLE artists DROP COLUMN IF EXISTS artist_thumb_path; - --- Restore the original albums.cover_art_source CHECK from migration 0016. -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','none')); --- Note: rows with cover_art_source='theaudiodb' will be rejected by this --- restored constraint. If down-migrating from a populated DB, run: --- UPDATE albums SET cover_art_source = NULL WHERE cover_art_source = 'theaudiodb'; --- before applying this migration. diff --git a/internal/db/migrations/0018_artist_art_and_provider_settings.up.sql b/internal/db/migrations/0018_artist_art_and_provider_settings.up.sql deleted file mode 100644 index b1ba95ba..00000000 --- a/internal/db/migrations/0018_artist_art_and_provider_settings.up.sql +++ /dev/null @@ -1,61 +0,0 @@ --- Schema for additional cover-art providers (TheAudioDB first), artist art --- (thumb + fanart), and the recheck-on-source-change trigger. - --- (0) Extend the existing albums.cover_art_source CHECK to accept the --- new 'theaudiodb' value. The constraint was created in migration 0016 --- with the IN list ('embedded','sidecar','mbcaa','none'); without this --- extension, the enricher's UPDATE setting cover_art_source='theaudiodb' --- would fail with a CHECK violation. -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','none')); - --- (1) Artist art columns parallel albums.cover_art_*. -ALTER TABLE artists - ADD COLUMN artist_thumb_path text, - ADD COLUMN artist_fanart_path text, - ADD COLUMN artist_art_source text; - -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','none')); - -CREATE INDEX artists_artist_art_source_idx ON artists (artist_art_source); - --- (2) Recheck-trigger version stamps. Default 0; current_version starts --- at 1, so every existing row is "stale" relative to current — first --- scan after migrate retries every settled row through the new chain. -ALTER TABLE albums - ADD COLUMN cover_art_sources_version int NOT NULL DEFAULT 0; -ALTER TABLE artists - ADD COLUMN artist_art_sources_version int NOT NULL DEFAULT 0; - --- (3) Per-provider settings + singleton meta row. -CREATE TABLE cover_art_provider_settings ( - provider_id text PRIMARY KEY, - enabled boolean NOT NULL DEFAULT true, - api_key text, - display_order int NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE TABLE cover_art_sources_meta ( - id boolean PRIMARY KEY DEFAULT true, - current_version int NOT NULL DEFAULT 1, - CONSTRAINT cover_art_sources_meta_singleton CHECK (id = true) -); -INSERT INTO cover_art_sources_meta (id, current_version) VALUES (true, 1); - --- Seed both v1 providers as enabled. TheAudioDB's api_key stays NULL; --- the application supplies the test key '2' when the column is NULL, --- per the no-coercive-settings principle. -INSERT INTO cover_art_provider_settings (provider_id, enabled, display_order) VALUES - ('mbcaa', true, 0), - ('theaudiodb', true, 1); - --- (4) Scan-runs gains a stage tally column for artist art enrichment. -ALTER TABLE scan_runs ADD COLUMN artist_art_enrich jsonb; diff --git a/internal/db/migrations/0019_scan_schedule.down.sql b/internal/db/migrations/0019_scan_schedule.down.sql deleted file mode 100644 index b785659c..00000000 --- a/internal/db/migrations/0019_scan_schedule.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS scan_schedule; diff --git a/internal/db/migrations/0019_scan_schedule.up.sql b/internal/db/migrations/0019_scan_schedule.up.sql deleted file mode 100644 index 0d872edb..00000000 --- a/internal/db/migrations/0019_scan_schedule.up.sql +++ /dev/null @@ -1,23 +0,0 @@ --- Recurring scans: singleton table holding the scan schedule --- config. mode is the discriminator: 'off' / 'interval' / 'daily' / 'weekly'. --- Per-mode fields are populated only when their mode is selected; others --- stay NULL. weekly_day uses ISO 8601: 1=Monday … 7=Sunday. -CREATE TABLE scan_schedule ( - id boolean PRIMARY KEY DEFAULT true, - mode text NOT NULL DEFAULT 'off', - interval_hours int, - time_of_day text, - weekly_day int, - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT scan_schedule_singleton CHECK (id = true), - CONSTRAINT scan_schedule_mode_check - CHECK (mode IN ('off', 'interval', 'daily', 'weekly')), - CONSTRAINT scan_schedule_interval_check - CHECK (mode != 'interval' OR (interval_hours IS NOT NULL AND interval_hours > 0)), - CONSTRAINT scan_schedule_daily_check - CHECK (mode != 'daily' OR time_of_day IS NOT NULL), - CONSTRAINT scan_schedule_weekly_check - CHECK (mode != 'weekly' OR (time_of_day IS NOT NULL AND weekly_day IS NOT NULL AND weekly_day BETWEEN 1 AND 7)) -); - -INSERT INTO scan_schedule (id) VALUES (true); diff --git a/internal/db/migrations/0020_relax_art_source_checks.down.sql b/internal/db/migrations/0020_relax_art_source_checks.down.sql deleted file mode 100644 index 59166599..00000000 --- a/internal/db/migrations/0020_relax_art_source_checks.down.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Restore the prior tighter CHECK constraints (pre-Deezer/Last.fm). --- This will fail if any rows currently have artist_art_source = --- 'deezer' or 'lastfm' (likewise album); operator must clear those --- rows manually before rolling back. - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','none')); - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','none')); - -ALTER TABLE cover_art_sources_meta DROP COLUMN IF EXISTS last_registered_providers_hash; diff --git a/internal/db/migrations/0020_relax_art_source_checks.up.sql b/internal/db/migrations/0020_relax_art_source_checks.up.sql deleted file mode 100644 index b663e06e..00000000 --- a/internal/db/migrations/0020_relax_art_source_checks.up.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Relax cover-art and artist-art source CHECK constraints so the new --- Deezer and Last.fm providers can persist their IDs as --- accepted source values. Also add the --- last_registered_providers_hash column to cover_art_sources_meta for --- boot-time auto-bump detection (when the registered-provider set --- changes, we bump current_version once so 'none' rows get --- re-eligibled). - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','deezer','lastfm','none')); - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','deezer','lastfm','none')); - -ALTER TABLE cover_art_sources_meta - ADD COLUMN IF NOT EXISTS last_registered_providers_hash text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0021_discover_variant.down.sql b/internal/db/migrations/0021_discover_variant.down.sql deleted file mode 100644 index d93aa89b..00000000 --- a/internal/db/migrations/0021_discover_variant.down.sql +++ /dev/null @@ -1,21 +0,0 @@ --- Restore the prior tighter CHECK constraints (pre-discover). --- This will fail if any rows currently have system_variant = 'discover'; --- operator must clear those rows manually before rolling back. - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist')) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0021_discover_variant.up.sql b/internal/db/migrations/0021_discover_variant.up.sql deleted file mode 100644 index 79af4416..00000000 --- a/internal/db/migrations/0021_discover_variant.up.sql +++ /dev/null @@ -1,27 +0,0 @@ --- Adds 'discover' as an accepted system_variant alongside 'for_you' --- and 'songs_like_artist'. Discover has no seed_artist_id (like --- for_you), so the variant->seed coherence check is extended to --- accept (system_variant = 'discover' AND seed_artist_id IS NULL). --- --- Drops + re-adds both CHECK constraints; PostgreSQL doesn't have --- ALTER CONSTRAINT for CHECK so this is the standard pattern. - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist', 'discover')) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0022_user_management.down.sql b/internal/db/migrations/0022_user_management.down.sql deleted file mode 100644 index 53632f82..00000000 --- a/internal/db/migrations/0022_user_management.down.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Reverses migration 0022. Drop tables in reverse dependency order. --- This will fail if any rows in audit_log or user_invites reference --- users that were deleted with ON DELETE SET NULL semantics; those --- references will already be NULL so the drops should succeed cleanly. - -DROP TABLE IF EXISTS audit_log; -DROP TABLE IF EXISTS user_invites; -DROP TABLE IF EXISTS registration_settings; -ALTER TABLE users DROP COLUMN IF EXISTS display_name; diff --git a/internal/db/migrations/0022_user_management.up.sql b/internal/db/migrations/0022_user_management.up.sql deleted file mode 100644 index 434a951d..00000000 --- a/internal/db/migrations/0022_user_management.up.sql +++ /dev/null @@ -1,48 +0,0 @@ --- User management: --- --- - users.display_name: optional human-readable name distinct from username. --- - user_invites: admin-generated tokens; user redeems during signup. --- - registration_settings (singleton): controls whether registration is --- 'invite_only' (default after first admin) or 'open' (admin can --- re-enable). The registration handler also has a special-case for the --- "no users yet" state where it ignores invites and lets the first --- register as admin. --- - audit_log: append-only record of admin-driven user mutations. --- No retention policy. - -ALTER TABLE users ADD COLUMN IF NOT EXISTS display_name text; - -CREATE TABLE user_invites ( - token text PRIMARY KEY, - invited_by uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - note text, - created_at timestamptz NOT NULL DEFAULT now(), - expires_at timestamptz NOT NULL, - redeemed_at timestamptz, - redeemed_by uuid REFERENCES users(id) ON DELETE SET NULL -); -CREATE INDEX user_invites_active_idx - ON user_invites (expires_at) - WHERE redeemed_at IS NULL; - -CREATE TABLE registration_settings ( - id boolean PRIMARY KEY DEFAULT true, - mode text NOT NULL DEFAULT 'invite_only', - CONSTRAINT registration_settings_singleton CHECK (id = true), - CONSTRAINT registration_settings_mode_check - CHECK (mode IN ('invite_only', 'open')) -); -INSERT INTO registration_settings (id) VALUES (true) - ON CONFLICT (id) DO NOTHING; - -CREATE TABLE audit_log ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - actor_id uuid REFERENCES users(id) ON DELETE SET NULL, - target_id uuid REFERENCES users(id) ON DELETE SET NULL, - action text NOT NULL, - metadata jsonb, - created_at timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX audit_log_created_at_idx ON audit_log (created_at DESC); -CREATE INDEX audit_log_actor_id_idx ON audit_log (actor_id); -CREATE INDEX audit_log_target_id_idx ON audit_log (target_id); diff --git a/internal/db/migrations/0023_user_auto_approve.down.sql b/internal/db/migrations/0023_user_auto_approve.down.sql deleted file mode 100644 index 65295c6c..00000000 --- a/internal/db/migrations/0023_user_auto_approve.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users DROP COLUMN IF EXISTS auto_approve_requests; diff --git a/internal/db/migrations/0023_user_auto_approve.up.sql b/internal/db/migrations/0023_user_auto_approve.up.sql deleted file mode 100644 index 76f0b333..00000000 --- a/internal/db/migrations/0023_user_auto_approve.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- Adds users.auto_approve_requests for the per-user auto-approve toggle: --- the request submission flow approves that user's requests at once. --- --- Default false: existing users keep manual approval, opt-in via the --- admin user-management UI. - -ALTER TABLE users - ADD COLUMN IF NOT EXISTS auto_approve_requests boolean NOT NULL DEFAULT false; diff --git a/internal/db/migrations/0024_user_management_u3.down.sql b/internal/db/migrations/0024_user_management_u3.down.sql deleted file mode 100644 index fc39e95e..00000000 --- a/internal/db/migrations/0024_user_management_u3.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DROP TABLE IF EXISTS password_resets; -DROP TABLE IF EXISTS smtp_config; -DROP INDEX IF EXISTS users_email_unique; -ALTER TABLE users DROP COLUMN IF EXISTS email; diff --git a/internal/db/migrations/0024_user_management_u3.up.sql b/internal/db/migrations/0024_user_management_u3.up.sql deleted file mode 100644 index 072daa05..00000000 --- a/internal/db/migrations/0024_user_management_u3.up.sql +++ /dev/null @@ -1,44 +0,0 @@ --- User management U3: self-service profile + email + email-based --- password reset infrastructure. --- --- - users.email: optional; required for the forgot-password flow. --- Lowercase-unique via a partial index to allow many NULL emails --- while preventing case-insensitive duplicates. --- - smtp_config singleton: SMTP server settings + from-address + --- enabled flag. The actual mailer reads this row at send time so --- config edits take effect without a server restart. --- - password_resets: short-lived single-use tokens for the --- forgot-password flow. 24h TTL enforced at issue time. - -ALTER TABLE users ADD COLUMN IF NOT EXISTS email text; -CREATE UNIQUE INDEX IF NOT EXISTS users_email_unique - ON users (lower(email)) - WHERE email IS NOT NULL; - -CREATE TABLE smtp_config ( - id boolean PRIMARY KEY DEFAULT true, - enabled boolean NOT NULL DEFAULT false, - host text NOT NULL DEFAULT '', - port int NOT NULL DEFAULT 587, - username text NOT NULL DEFAULT '', - password text NOT NULL DEFAULT '', - from_address text NOT NULL DEFAULT '', - from_name text NOT NULL DEFAULT 'Minstrel', - use_tls boolean NOT NULL DEFAULT true, - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT smtp_config_singleton CHECK (id = true) -); -INSERT INTO smtp_config (id) VALUES (true) - ON CONFLICT (id) DO NOTHING; - -CREATE TABLE password_resets ( - token text PRIMARY KEY, - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - created_at timestamptz NOT NULL DEFAULT now(), - expires_at timestamptz NOT NULL, - used_at timestamptz -); -CREATE INDEX password_resets_user_id_idx ON password_resets (user_id); -CREATE INDEX password_resets_active_idx - ON password_resets (expires_at) - WHERE used_at IS NULL; diff --git a/internal/db/migrations/0025_library_changes.down.sql b/internal/db/migrations/0025_library_changes.down.sql deleted file mode 100644 index fed8a61a..00000000 --- a/internal/db/migrations/0025_library_changes.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS library_changes; diff --git a/internal/db/migrations/0025_library_changes.up.sql b/internal/db/migrations/0025_library_changes.up.sql deleted file mode 100644 index f4252cc4..00000000 --- a/internal/db/migrations/0025_library_changes.up.sql +++ /dev/null @@ -1,20 +0,0 @@ --- Append-only change log for library entities. Every mutation on --- artists/albums/tracks/likes/playlists/playlist_tracks writes a row --- in the same transaction as the mutation itself. Powers the delta-sync --- endpoint — clients pass back the last-seen `id` as a cursor. --- --- Retention: not capped here. A cursor older than what the table keeps gets --- the reset path (410). - -CREATE TABLE library_changes ( - id BIGSERIAL PRIMARY KEY, - entity_type TEXT NOT NULL CHECK (entity_type IN ( - 'artist', 'album', 'track', 'like_track', 'like_album', 'like_artist', - 'playlist', 'playlist_track' - )), - entity_id TEXT NOT NULL, - op TEXT NOT NULL CHECK (op IN ('upsert', 'delete')), - changed_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - -CREATE INDEX idx_library_changes_id ON library_changes(id); diff --git a/internal/db/migrations/0026_users_timezone.down.sql b/internal/db/migrations/0026_users_timezone.down.sql deleted file mode 100644 index 6752f9d1..00000000 --- a/internal/db/migrations/0026_users_timezone.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE users - DROP COLUMN timezone, - DROP COLUMN timezone_updated_at; diff --git a/internal/db/migrations/0026_users_timezone.up.sql b/internal/db/migrations/0026_users_timezone.up.sql deleted file mode 100644 index ec14c39f..00000000 --- a/internal/db/migrations/0026_users_timezone.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- 0026_users_timezone.up.sql — per-user timezone for the system-playlist --- scheduler. Default 'UTC' so existing rows + brand-new --- users have a safe value before their first client check-in via --- PUT /api/me/timezone. The scheduler reads this column to decide --- which IANA zone to anchor each user's daily 03:00 build to. -ALTER TABLE users - ADD COLUMN timezone text NOT NULL DEFAULT 'UTC', - ADD COLUMN timezone_updated_at timestamptz; diff --git a/internal/db/migrations/0027_system_playlist_rotation.down.sql b/internal/db/migrations/0027_system_playlist_rotation.down.sql deleted file mode 100644 index c52a8f5f..00000000 --- a/internal/db/migrations/0027_system_playlist_rotation.down.sql +++ /dev/null @@ -1,5 +0,0 @@ --- 0027_system_playlist_rotation.down.sql -DROP TABLE IF EXISTS system_playlist_rotation_state; - -ALTER TABLE play_events - DROP COLUMN IF EXISTS source; diff --git a/internal/db/migrations/0027_system_playlist_rotation.up.sql b/internal/db/migrations/0027_system_playlist_rotation.up.sql deleted file mode 100644 index 5c604801..00000000 --- a/internal/db/migrations/0027_system_playlist_rotation.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- 0027_system_playlist_rotation.up.sql — sample-history dedup for --- system playlists. Two parts: --- --- 1. play_events.source: which system playlist a play originated --- from ('for_you' | 'discover' | future kinds), or NULL for any --- play not launched from a system-playlist surface (library, --- user playlist, radio, Subsonic). Lets the ingest path know a --- play should count against that playlist's rotation. --- --- 2. system_playlist_rotation_state: per (user, playlist_kind) set --- of track ids already played in the current rotation window. --- Shuffle-on-play prefers the unplayed tail; when the snapshot --- is exhausted the set resets and rotation_started_at advances. --- Centralized server-side so phone / web / watch share one --- rotation, mirroring how radio dedup already lives server-side. -ALTER TABLE play_events - ADD COLUMN source text; - -CREATE TABLE system_playlist_rotation_state ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - playlist_kind text NOT NULL, - played_track_ids uuid[] NOT NULL DEFAULT '{}', - rotation_started_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, playlist_kind) -); diff --git a/internal/db/migrations/0028_discovery_mix_variants.down.sql b/internal/db/migrations/0028_discovery_mix_variants.down.sql deleted file mode 100644 index e16f7ecf..00000000 --- a/internal/db/migrations/0028_discovery_mix_variants.down.sql +++ /dev/null @@ -1,24 +0,0 @@ --- Reverts to the 0021 constraint set (for_you, songs_like_artist, --- discover only). Fails if any playlists row still has one of the --- five new system_variant values — delete/rebuild system playlists --- first if rolling back. - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist', 'discover')) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0028_discovery_mix_variants.up.sql b/internal/db/migrations/0028_discovery_mix_variants.up.sql deleted file mode 100644 index e2eee325..00000000 --- a/internal/db/migrations/0028_discovery_mix_variants.up.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Before: the five discovery mixes (deep_cuts, rediscover, new_for_you, --- on_this_day, first_listens) had producers and registry entries but no --- system_variant values in the two playlists CHECK constraints, so inserting --- any of them failed playlists_kind_variant_consistent (SQLSTATE 23514) — --- and because BuildSystemPlaylists is one all-or-nothing transaction, that --- aborts the WHOLE build. After: the constraints accept them. --- --- All five are seedless (like for_you/discover): seed_artist_id IS --- NULL. Drop + re-add both constraints with the expanded set, same --- pattern as 0021_discover_variant (Postgres has no ALTER CONSTRAINT --- for CHECK). - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ( - 'for_you', 'songs_like_artist', 'discover', - 'deep_cuts', 'rediscover', 'new_for_you', - 'on_this_day', 'first_listens' - )) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'deep_cuts' AND seed_artist_id IS NULL) - OR - (system_variant = 'rediscover' AND seed_artist_id IS NULL) - OR - (system_variant = 'new_for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'on_this_day' AND seed_artist_id IS NULL) - OR - (system_variant = 'first_listens' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0029_tracks_mbid_nonunique.down.sql b/internal/db/migrations/0029_tracks_mbid_nonunique.down.sql deleted file mode 100644 index b40e0408..00000000 --- a/internal/db/migrations/0029_tracks_mbid_nonunique.down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Reverts to the unique partial index. This FAILS if any recording --- MBID is shared across releases in the library (the exact case 0029 --- exists to allow) — dedupe tracks.mbid before rolling back. - -DROP INDEX IF EXISTS tracks_mbid_idx; -CREATE UNIQUE INDEX tracks_mbid_unique ON tracks (mbid) WHERE mbid IS NOT NULL; diff --git a/internal/db/migrations/0029_tracks_mbid_nonunique.up.sql b/internal/db/migrations/0029_tracks_mbid_nonunique.up.sql deleted file mode 100644 index 714789cb..00000000 --- a/internal/db/migrations/0029_tracks_mbid_nonunique.up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- tracks.mbid holds the MusicBrainz *recording* MBID — the id the --- ListenBrainz similarity pipeline (ListPlayedTracksNeedingSimilarity, --- GetTracksByMBIDs) matches on. A single recording legitimately appears --- on multiple releases (album + compilation + single), so multiple --- tracks rows share one recording MBID. --- --- tracks_mbid_unique (added in 0002, when this column was always NULL --- and never populated) wrongly assumes one MBID == one track. Now that --- the scanner extracts the recording MBID, that uniqueness throws --- 23505 for any recording present on >1 release. Replace it with a --- non-unique partial index serving the same lookups. Zero-risk: the --- column is 100% NULL at migration time. - -DROP INDEX IF EXISTS tracks_mbid_unique; -CREATE INDEX IF NOT EXISTS tracks_mbid_idx ON tracks (mbid) WHERE mbid IS NOT NULL; diff --git a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.down.sql b/internal/db/migrations/0030_relax_art_source_check_to_nonempty.down.sql deleted file mode 100644 index 68fe224e..00000000 --- a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.down.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Restore the 0020 fixed-allowlist CHECKs. FAILS if any row holds a --- source value outside the allowlist (the exact case 0030 enables) — --- normalise such rows before rolling back. - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','deezer','lastfm','none')); - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','deezer','lastfm','none')); diff --git a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.up.sql b/internal/db/migrations/0030_relax_art_source_check_to_nonempty.up.sql deleted file mode 100644 index 7b6dd3fd..00000000 --- a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.up.sql +++ /dev/null @@ -1,18 +0,0 @@ --- The cover/artist art `*_source` column stores the recording --- provider's registry ID. coverart.Register makes the provider set --- extensible, so a fixed IN-list CHECK (0016 → 0018 → 0020) required a --- schema migration for every new provider and rejected any --- out-of-list value (e.g. test stub providers): a fixed-value CHECK --- fighting an extensible value set. Relax to "NULL or any --- non-empty string" — the registry, not the schema, is the source of --- truth for valid provider IDs. - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL OR cover_art_source <> ''); - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL OR artist_art_source <> ''); diff --git a/internal/db/migrations/0031_lidarr_add_confirmed_at.down.sql b/internal/db/migrations/0031_lidarr_add_confirmed_at.down.sql deleted file mode 100644 index 40964d14..00000000 --- a/internal/db/migrations/0031_lidarr_add_confirmed_at.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE lidarr_requests - DROP COLUMN lidarr_add_confirmed_at; diff --git a/internal/db/migrations/0031_lidarr_add_confirmed_at.up.sql b/internal/db/migrations/0031_lidarr_add_confirmed_at.up.sql deleted file mode 100644 index b5468d98..00000000 --- a/internal/db/migrations/0031_lidarr_add_confirmed_at.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- Additive: records when Lidarr accepted the add (POST artist/album) --- for an approved request. NULL = not yet sent/confirmed; the --- reconciler idempotently (re)sends the add until this is set, then --- watches for the import. Decouples the durable admin approval from the --- best-effort Lidarr call, so a transient Lidarr outage does not force a --- manual re-approve. -ALTER TABLE lidarr_requests - ADD COLUMN lidarr_add_confirmed_at timestamptz; diff --git a/internal/db/migrations/0032_playback_errors.down.sql b/internal/db/migrations/0032_playback_errors.down.sql deleted file mode 100644 index 43ae6b48..00000000 --- a/internal/db/migrations/0032_playback_errors.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS playback_errors; diff --git a/internal/db/migrations/0032_playback_errors.up.sql b/internal/db/migrations/0032_playback_errors.up.sql deleted file mode 100644 index 12de900c..00000000 --- a/internal/db/migrations/0032_playback_errors.up.sql +++ /dev/null @@ -1,41 +0,0 @@ --- Client-reported playback errors. Populated by clients when a track --- fails to play (zero duration, decode error, etc.); surfaced in the --- admin /admin/playback-errors inbox so an admin can hide / delete --- / re-request the offending track. --- --- resolved_at + resolved_by + resolution are NULL until an admin acts --- on the row. Auto-resolved by the client when the admin clicks Hide / --- Delete / Re-request from the inbox row, with the resolution string --- recording which path was taken. The partial index keeps the --- unresolved-queue lookup fast even as resolved history accumulates. --- --- CHECK constraints on kind/resolution gate the enum values so client --- typos can't pollute the data; a new value means swapping the constraint --- in the same migration as the code that writes it. - -CREATE TABLE playback_errors ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - client_id text NOT NULL, - kind text NOT NULL, - detail text, - occurred_at timestamptz NOT NULL DEFAULT now(), - resolved_at timestamptz, - resolved_by uuid REFERENCES users(id), - resolution text, - CONSTRAINT playback_errors_kind_check - CHECK (kind IN ('zero_duration', 'load_failed', 'stalled')), - CONSTRAINT playback_errors_resolution_check - CHECK (resolution IS NULL OR resolution IN - ('hidden', 'deleted', 'requested', 'fixed', 'ignored')), - CONSTRAINT playback_errors_resolved_consistency - CHECK ((resolved_at IS NULL) = (resolution IS NULL)) -); - -CREATE INDEX idx_playback_errors_unresolved - ON playback_errors (occurred_at DESC) - WHERE resolved_at IS NULL; - -CREATE INDEX idx_playback_errors_track - ON playback_errors (track_id); diff --git a/internal/db/migrations/0033_drop_scan_schedule.down.sql b/internal/db/migrations/0033_drop_scan_schedule.down.sql deleted file mode 100644 index 59b72012..00000000 --- a/internal/db/migrations/0033_drop_scan_schedule.down.sql +++ /dev/null @@ -1,21 +0,0 @@ --- Recreate the scan_schedule singleton (mirror of 0019) so the drop is --- reversible. The application no longer reads or writes this table. -CREATE TABLE scan_schedule ( - id boolean PRIMARY KEY DEFAULT true, - mode text NOT NULL DEFAULT 'off', - interval_hours int, - time_of_day text, - weekly_day int, - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT scan_schedule_singleton CHECK (id = true), - CONSTRAINT scan_schedule_mode_check - CHECK (mode IN ('off', 'interval', 'daily', 'weekly')), - CONSTRAINT scan_schedule_interval_check - CHECK (mode != 'interval' OR (interval_hours IS NOT NULL AND interval_hours > 0)), - CONSTRAINT scan_schedule_daily_check - CHECK (mode != 'daily' OR time_of_day IS NOT NULL), - CONSTRAINT scan_schedule_weekly_check - CHECK (mode != 'weekly' OR (time_of_day IS NOT NULL AND weekly_day IS NOT NULL AND weekly_day BETWEEN 1 AND 7)) -); - -INSERT INTO scan_schedule (id) VALUES (true); diff --git a/internal/db/migrations/0033_drop_scan_schedule.up.sql b/internal/db/migrations/0033_drop_scan_schedule.up.sql deleted file mode 100644 index 346ed9ca..00000000 --- a/internal/db/migrations/0033_drop_scan_schedule.up.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Retire the configurable scan scheduler. New-file pickup is now handled by --- the fsnotify watcher + a hardcoded safety-net delta walk (cmd/minstrel), --- so the configurable schedule (and its admin UI) is gone. -DROP TABLE IF EXISTS scan_schedule; diff --git a/internal/db/migrations/0034_you_might_like.down.sql b/internal/db/migrations/0034_you_might_like.down.sql deleted file mode 100644 index e31679d6..00000000 --- a/internal/db/migrations/0034_you_might_like.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Reverse 0034_you_might_like.up.sql. -DROP TABLE IF EXISTS you_might_like_artists; -DROP TABLE IF EXISTS you_might_like_albums; diff --git a/internal/db/migrations/0034_you_might_like.up.sql b/internal/db/migrations/0034_you_might_like.up.sql deleted file mode 100644 index 6be652a2..00000000 --- a/internal/db/migrations/0034_you_might_like.up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- 0034_you_might_like.up.sql — "You might like" Home rows. --- --- Per-user ranked lists of IN-LIBRARY albums/artists the listener --- doesn't actively spin but is predicted to enjoy, derived from the --- same similarity + like-weighted candidate engine that powers For-You --- (rolled up from track scores to album/artist). Built in the daily --- 3am BuildSystemPlaylists pass and atomic-replaced, exactly like the --- system playlists; read back by /api/home. --- --- Two thin tables (id + rank) rather than denormalized snapshots: the --- Home read path hydrates album/artist refs through the existing --- albums/artists joins, so a later metadata edit is reflected without --- a rebuild. CASCADE on user/album/artist deletes keeps them clean. - -CREATE TABLE you_might_like_albums ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - album_id uuid NOT NULL REFERENCES albums(id) ON DELETE CASCADE, - rank integer NOT NULL, - built_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, album_id) -); - --- Read path orders by rank within a user; the index serves it directly. -CREATE INDEX you_might_like_albums_user_rank_idx - ON you_might_like_albums (user_id, rank); - -CREATE TABLE you_might_like_artists ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - rank integer NOT NULL, - built_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, artist_id) -); - -CREATE INDEX you_might_like_artists_user_rank_idx - ON you_might_like_artists (user_id, rank); diff --git a/internal/db/migrations/0035_taste_profile.down.sql b/internal/db/migrations/0035_taste_profile.down.sql deleted file mode 100644 index 4af083e7..00000000 --- a/internal/db/migrations/0035_taste_profile.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Reverse 0035_taste_profile.up.sql. -DROP TABLE IF EXISTS taste_profile_tags; -DROP TABLE IF EXISTS taste_profile_artists; diff --git a/internal/db/migrations/0035_taste_profile.up.sql b/internal/db/migrations/0035_taste_profile.up.sql deleted file mode 100644 index 47084fa5..00000000 --- a/internal/db/migrations/0035_taste_profile.up.sql +++ /dev/null @@ -1,33 +0,0 @@ --- 0035_taste_profile.up.sql — per-user taste profile. --- --- A persistent, decaying model of each user's taste, rebuilt daily from --- graded play engagement (completion + skip position) plus explicit --- likes. Two facet tables: weighted artists and weighted genre tags. --- Weight is a signed float — positive = drawn to, negative = (passively) --- avoided; magnitude reflects decayed engagement. Candidate sourcing and --- scoring read them. --- --- CASCADE on user/artist deletes keeps them clean. Indexed by --- (user_id, weight DESC) to serve "top taste artists/tags" reads cheaply. - -CREATE TABLE taste_profile_artists ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, artist_id) -); - -CREATE INDEX taste_profile_artists_user_weight_idx - ON taste_profile_artists (user_id, weight DESC); - -CREATE TABLE taste_profile_tags ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - tag text NOT NULL, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, tag) -); - -CREATE INDEX taste_profile_tags_user_weight_idx - ON taste_profile_tags (user_id, weight DESC); diff --git a/internal/db/migrations/0036_diagnostics.down.sql b/internal/db/migrations/0036_diagnostics.down.sql deleted file mode 100644 index b53c33ba..00000000 --- a/internal/db/migrations/0036_diagnostics.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE users DROP COLUMN IF EXISTS debug_mode_enabled; -DROP TABLE IF EXISTS diagnostic_events; diff --git a/internal/db/migrations/0036_diagnostics.up.sql b/internal/db/migrations/0036_diagnostics.up.sql deleted file mode 100644 index afcab288..00000000 --- a/internal/db/migrations/0036_diagnostics.up.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Device diagnostics / debug-reporting subsystem. --- --- When an account has users.debug_mode_enabled = true, that account's --- client(s) stream a timeseries of device state here: connectivity + --- server-health transitions (roaming / poor-data recovery), UPnP/Sonos --- sync events (locked-phone desync), and power/lifecycle state (Doze / --- battery-optimization, the prime suspect for the desync). The admin --- /admin/diagnostics view filters by account + device + time window and --- exports the slice as JSON for offline analysis. --- --- `kind` is a COARSE category gated by a CHECK whitelist; the finer event --- discriminator + all event-specific fields live in the `payload` jsonb. This --- keeps the enum small and stable so new event variants don't require a --- migration (only a new *category* would: a new CHECK value means swapping the --- constraint in the same migration). If you add a category here, mirror it in --- the handler whitelist in internal/api/diagnostics.go. --- --- Two timestamps on purpose: occurred_at is the client device clock --- (when the event happened on the phone — may be skewed/wrong, e.g. in --- a dead zone), received_at is the server clock at ingest. Retention --- pruning is keyed on received_at so a bad client clock can't keep rows --- alive forever. - -CREATE TABLE diagnostic_events ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - client_id text NOT NULL, - app_version text, - os_version text, - kind text NOT NULL, - payload jsonb NOT NULL DEFAULT '{}'::jsonb, - occurred_at timestamptz NOT NULL, - received_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT diagnostic_events_kind_check - CHECK (kind IN ( - 'connectivity', 'upnp_sync', 'power', 'lifecycle', - 'heartbeat', 'http' - )) -); - --- Admin reads filter by account then device, ordered newest-first. -CREATE INDEX idx_diagnostic_events_user - ON diagnostic_events (user_id, occurred_at DESC); -CREATE INDEX idx_diagnostic_events_client - ON diagnostic_events (client_id, occurred_at DESC); --- Retention pruner deletes by server-clock age. -CREATE INDEX idx_diagnostic_events_received - ON diagnostic_events (received_at); - --- Per-account opt-in for diagnostics reporting. Admin-set primarily --- (flip remotely while a bug is live); the client also exposes a local --- OFF switch. Default false: no account reports until explicitly enabled. -ALTER TABLE users - ADD COLUMN IF NOT EXISTS debug_mode_enabled boolean NOT NULL DEFAULT false; diff --git a/internal/db/migrations/0037_diagnostics_playback_kind.down.sql b/internal/db/migrations/0037_diagnostics_playback_kind.down.sql deleted file mode 100644 index 10875ec9..00000000 --- a/internal/db/migrations/0037_diagnostics_playback_kind.down.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Drop rows using the new value first so they don't violate the restored --- (narrower) constraint, then revert the whitelist. -DELETE FROM diagnostic_events WHERE kind = 'playback'; -ALTER TABLE diagnostic_events DROP CONSTRAINT diagnostic_events_kind_check; -ALTER TABLE diagnostic_events ADD CONSTRAINT diagnostic_events_kind_check - CHECK (kind IN ( - 'connectivity', 'upnp_sync', 'power', 'lifecycle', - 'heartbeat', 'http' - )); diff --git a/internal/db/migrations/0037_diagnostics_playback_kind.up.sql b/internal/db/migrations/0037_diagnostics_playback_kind.up.sql deleted file mode 100644 index 290ee688..00000000 --- a/internal/db/migrations/0037_diagnostics_playback_kind.up.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Add 'playback' to the diagnostic_events kind whitelist. --- --- `route` and `player_state` events fire for EVERY output route (phone --- speaker, Bluetooth, UPnP/Sonos), so bucketing them under 'upnp_sync' --- was misleading — a listener on Bluetooth earbuds produced "upnp_sync" --- rows. 'upnp_sync' now means genuinely UPnP/Sonos-specific signal --- (drops, and future resync/desync); general playback + route telemetry --- moves to the new 'playback' kind. --- --- The new value lands by dropping and re-adding the constraint in the same --- migration. Existing rows tagged --- 'upnp_sync' stay as-is (debug telemetry on a 30-day retention). - -ALTER TABLE diagnostic_events DROP CONSTRAINT diagnostic_events_kind_check; -ALTER TABLE diagnostic_events ADD CONSTRAINT diagnostic_events_kind_check - CHECK (kind IN ( - 'connectivity', 'upnp_sync', 'power', 'lifecycle', - 'heartbeat', 'http', 'playback' - )); diff --git a/internal/db/migrations/0038_for_you_pick_kind.down.sql b/internal/db/migrations/0038_for_you_pick_kind.down.sql deleted file mode 100644 index 7158bd2f..00000000 --- a/internal/db/migrations/0038_for_you_pick_kind.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE play_events DROP COLUMN pick_kind; -ALTER TABLE playlist_tracks DROP COLUMN pick_kind; diff --git a/internal/db/migrations/0038_for_you_pick_kind.up.sql b/internal/db/migrations/0038_for_you_pick_kind.up.sql deleted file mode 100644 index 29b582f6..00000000 --- a/internal/db/migrations/0038_for_you_pick_kind.up.sql +++ /dev/null @@ -1,34 +0,0 @@ --- For You exploration attribution. --- --- For You is deliberately composed of two populations: a head of --- top-scored similarity matches ("taste" picks) and a tail sampled from --- deeper in the candidate ranking ("fresh" picks — the freshness --- injection). Before this the metrics could only judge For You as one --- blob, so a high skip rate couldn't be read as "the taste engine is --- missing" vs "the freshness tax is too high". --- --- Two denormalized columns, both nullable: --- --- 1. playlist_tracks.pick_kind — stamped by the system-playlist builder --- at snapshot build time. NULL for manual playlists and for system --- variants that don't split (Discover, Songs like X, discovery --- mixes). System snapshots are atomically replaced daily, so the --- column never goes stale within a snapshot. --- --- 2. play_events.pick_kind — stamped at play-ingestion time by looking --- the track up in the user's CURRENT For You snapshot. Attribution --- must be frozen at play time: For You rebuilds daily, so a 30-day --- metrics window spans ~30 snapshots and a join-at-read against the --- live snapshot would misattribute nearly everything. Plays that --- predate this feature (or whose track already rotated out, e.g. a --- late offline replay) stay NULL → reported as unattributed. - -ALTER TABLE playlist_tracks - ADD COLUMN pick_kind text - CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); - -ALTER TABLE play_events - ADD COLUMN pick_kind text - CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); diff --git a/internal/db/migrations/0039_pick_kind_vocabulary.down.sql b/internal/db/migrations/0039_pick_kind_vocabulary.down.sql deleted file mode 100644 index eb447d38..00000000 --- a/internal/db/migrations/0039_pick_kind_vocabulary.down.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Rows stamped with the widened vocabulary must be cleared before the --- narrow CHECK can be re-added; NULL reads as "unattributed", which is --- the honest downgrade. -UPDATE play_events SET pick_kind = NULL - WHERE pick_kind NOT IN ('taste', 'fresh'); -UPDATE playlist_tracks SET pick_kind = NULL - WHERE pick_kind NOT IN ('taste', 'fresh'); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); - -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); diff --git a/internal/db/migrations/0039_pick_kind_vocabulary.up.sql b/internal/db/migrations/0039_pick_kind_vocabulary.up.sql deleted file mode 100644 index c1502d73..00000000 --- a/internal/db/migrations/0039_pick_kind_vocabulary.up.sql +++ /dev/null @@ -1,41 +0,0 @@ --- Provenance as standard. --- --- 0038 introduced pick_kind as a For You one-off ('taste'/'fresh'). --- The mechanism — stamp WHY a track is in the snapshot at build time, --- freeze it onto the play at ingestion, break it down in metrics — is --- now the standard for every system mix, so the CHECK vocabulary --- widens to cover: --- --- taste / fresh For You head vs freshness-injection tail --- dormant / cross_user / random --- Discover's three candidate buckets — makes --- the 40/30/30 allocation measurable instead --- of a guess --- tier1 / tier2 / tier3 the tiered-eligibility ladder: tier 1 pins the --- mix's exact desire, each higher tier steps --- back a little. Tier --- provenance is how we measure what the --- step-back trades away. --- --- Postgres CHECK whitelists can't be altered in place: DROP + re-ADD --- with the expanded list, in the same migration. - -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); diff --git a/internal/db/migrations/0040_recommendation_tuning.down.sql b/internal/db/migrations/0040_recommendation_tuning.down.sql deleted file mode 100644 index 9575d0eb..00000000 --- a/internal/db/migrations/0040_recommendation_tuning.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE recommendation_tuning_audit; -DROP TABLE taste_tuning; -DROP TABLE recommendation_weight_profiles; diff --git a/internal/db/migrations/0040_recommendation_tuning.up.sql b/internal/db/migrations/0040_recommendation_tuning.up.sql deleted file mode 100644 index 3d3705d0..00000000 --- a/internal/db/migrations/0040_recommendation_tuning.up.sql +++ /dev/null @@ -1,56 +0,0 @@ --- Recommendation tuning lab. --- --- The scoring weights move out of YAML (radio profile) and out of the --- systemMixWeights hard-code (daily_mix profile) into DB-backed --- settings with live effect — a lab for FINDING good values, which then --- get baked into shipped defaults; nobody should need this card to get --- good recommendations. --- --- Rows are seeded by the recsettings service's boot reconcile (the --- coverart SettingsService pattern), not by this migration, so shipped --- defaults live in exactly one place (Go). - -CREATE TABLE recommendation_weight_profiles ( - profile text PRIMARY KEY - CONSTRAINT recommendation_weight_profiles_profile_check - CHECK (profile IN ('radio', 'daily_mix')), - base_weight double precision NOT NULL, - like_boost double precision NOT NULL, - recency_weight double precision NOT NULL, - skip_penalty double precision NOT NULL, - jitter_magnitude double precision NOT NULL, - context_weight double precision NOT NULL, - similarity_weight double precision NOT NULL, - taste_weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now() -); - --- Taste-profile build knobs: engagement half-life + the completion→ --- engagement curve points (taste.Config's tunable subset). -CREATE TABLE taste_tuning ( - singleton boolean PRIMARY KEY DEFAULT true - CONSTRAINT taste_tuning_singleton_check CHECK (singleton), - half_life_days double precision NOT NULL, - engagement_hard_skip double precision NOT NULL, - engagement_neutral double precision NOT NULL, - engagement_full double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now() -); - --- Every knob turn writes one audit row; the metrics trend view --- annotates these on its timeline so cause→effect is visible --- after a change. changes is a jsonb array of {field, old, new}. -CREATE TABLE recommendation_tuning_audit ( - id bigserial PRIMARY KEY, - changed_at timestamptz NOT NULL DEFAULT now(), - scope text NOT NULL - CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste')), - action text NOT NULL - CONSTRAINT recommendation_tuning_audit_action_check - CHECK (action IN ('update', 'reset')), - changes jsonb NOT NULL -); - -CREATE INDEX recommendation_tuning_audit_changed_at_idx - ON recommendation_tuning_audit (changed_at DESC); diff --git a/internal/db/migrations/0041_discover_taste_unheard.down.sql b/internal/db/migrations/0041_discover_taste_unheard.down.sql deleted file mode 100644 index 2bc620a2..00000000 --- a/internal/db/migrations/0041_discover_taste_unheard.down.sql +++ /dev/null @@ -1,27 +0,0 @@ --- Reverse 0041_discover_taste_unheard.up.sql. --- --- Null out any rows stamped with the new value before shrinking the --- CHECK back to the 0039 vocabulary, or the ADD CONSTRAINT would fail --- on existing 'taste_unheard' rows (mirrors 0039's down). -UPDATE play_events SET pick_kind = NULL WHERE pick_kind = 'taste_unheard'; -UPDATE playlist_tracks SET pick_kind = NULL WHERE pick_kind = 'taste_unheard'; - -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); diff --git a/internal/db/migrations/0041_discover_taste_unheard.up.sql b/internal/db/migrations/0041_discover_taste_unheard.up.sql deleted file mode 100644 index 4f8934d1..00000000 --- a/internal/db/migrations/0041_discover_taste_unheard.up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- Discover taste-targeted novelty bucket. --- --- Without it, Discover on a single-user server is effectively dormant + --- crude-random, and the per-user taste profile's tags go unused. This adds a --- fourth Discover candidate bucket that ranks unheard tracks by the --- user's taste-profile tag weights ("novelty that fits your vibe"), so --- its picks need a new pick_kind provenance value. --- --- Postgres CHECK whitelists can't be altered in place: DROP + re-ADD with --- the expanded list, in the same migration. -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', 'taste_unheard', - 'tier1', 'tier2', 'tier3' - )); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', 'taste_unheard', - 'tier1', 'tier2', 'tier3' - )); diff --git a/internal/db/migrations/0042_track_tags.down.sql b/internal/db/migrations/0042_track_tags.down.sql deleted file mode 100644 index e60b8a3d..00000000 --- a/internal/db/migrations/0042_track_tags.down.sql +++ /dev/null @@ -1,5 +0,0 @@ --- Reverse 0042_track_tags.up.sql. -DROP INDEX IF EXISTS tracks_tag_source_idx; -ALTER TABLE tracks DROP COLUMN IF EXISTS tag_sources_version; -ALTER TABLE tracks DROP COLUMN IF EXISTS tag_source; -DROP TABLE IF EXISTS track_tags; diff --git a/internal/db/migrations/0042_track_tags.up.sql b/internal/db/migrations/0042_track_tags.up.sql deleted file mode 100644 index 8c49156d..00000000 --- a/internal/db/migrations/0042_track_tags.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Track-level folksonomy tags for taste enrichment. --- --- A global (not per-user) cache of style/mood tags fetched from --- MusicBrainz (keyless) + Last.fm (when a key is configured), keyed by --- track. Feeds the taste recompute's tag facet alongside raw ID3 genre, --- lifting resolution from coarse "Rock" to "post-punk / shoegaze / --- melancholic". The enricher caps to the top-K tags per track at write --- time so a heavily-tagged track can't dominate the profile. weight is a --- normalized folksonomy strength in [0,1]. Mirrors the coverart --- enricher's versioned source-tracking pattern. -CREATE TABLE track_tags ( - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - tag text NOT NULL, - weight double precision NOT NULL DEFAULT 1, - PRIMARY KEY (track_id, tag) -); -CREATE INDEX track_tags_track_idx ON track_tags (track_id); - --- Enrichment bookkeeping (mirror artists.artist_art_source): --- tag_source NULL → not yet processed (eligible) --- tag_source 'lastfm' / 'musicbrainz' / 'mixed' → found, cached --- tag_source 'none' → providers returned nothing --- tag_sources_version → bump to re-process none/stale -ALTER TABLE tracks ADD COLUMN tag_source text; -ALTER TABLE tracks ADD COLUMN tag_sources_version integer NOT NULL DEFAULT 0; -CREATE INDEX tracks_tag_source_idx ON tracks (tag_source, tag_sources_version); diff --git a/internal/db/migrations/0043_tag_provider_settings.down.sql b/internal/db/migrations/0043_tag_provider_settings.down.sql deleted file mode 100644 index 6c82f9d0..00000000 --- a/internal/db/migrations/0043_tag_provider_settings.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Reverse 0043_tag_provider_settings.up.sql. -DROP TABLE IF EXISTS tag_sources_meta; -DROP TABLE IF EXISTS tag_provider_settings; diff --git a/internal/db/migrations/0043_tag_provider_settings.up.sql b/internal/db/migrations/0043_tag_provider_settings.up.sql deleted file mode 100644 index f7a87cd8..00000000 --- a/internal/db/migrations/0043_tag_provider_settings.up.sql +++ /dev/null @@ -1,38 +0,0 @@ --- Tag-enrichment provider settings. --- --- Mirrors the cover-art provider-settings substrate (migration 0018) so --- adding a new tag source later is "register a provider + it auto-upserts --- a row here" — never a schema change. The tag enricher reads the enabled --- set + api keys from tag_provider_settings and stamps the current version --- from tag_sources_meta onto tracks.tag_sources_version (added in 0042). --- --- current_version starts at 1 while tracks.tag_sources_version defaults to --- 0 (migration 0042), so every existing track is "stale" relative to --- current and gets enriched on the first pass after this migrates. - -CREATE TABLE tag_provider_settings ( - provider_id text PRIMARY KEY, - enabled boolean NOT NULL DEFAULT true, - api_key text, - display_order int NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE TABLE tag_sources_meta ( - id boolean PRIMARY KEY DEFAULT true, - current_version int NOT NULL DEFAULT 1, - last_registered_providers_hash text NOT NULL DEFAULT '', - CONSTRAINT tag_sources_meta_singleton CHECK (id = true) -); -INSERT INTO tag_sources_meta (id, current_version) VALUES (true, 1); - --- Seed the v1 providers. MusicBrainz is the keyless always-on default; --- Last.fm ships disabled and is opt-in once an admin supplies a key in --- Settings: a feature that needs a third-party account is never on by --- default. The --- SettingsService also upserts these at boot, so the seed is belt-and- --- suspenders / documents the intended defaults. -INSERT INTO tag_provider_settings (provider_id, enabled, display_order) VALUES - ('musicbrainz', true, 0), - ('lastfm', false, 1); diff --git a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.down.sql b/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.down.sql deleted file mode 100644 index 4ad01726..00000000 --- a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Reverse 0044_taste_tuning_enriched_tag_scale.up.sql. -ALTER TABLE taste_tuning DROP COLUMN IF EXISTS enriched_tag_scale; diff --git a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.up.sql b/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.up.sql deleted file mode 100644 index c02818b4..00000000 --- a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.up.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Expose EnrichedTagScale in the tuning lab. Adds the enriched-tag --- weight knob to the taste_tuning singleton so an admin can dial how much --- folksonomy tags count vs raw ID3 genre. DEFAULT 0.5 backfills the --- existing row and matches taste.DefaultConfig().EnrichedTagScale. -ALTER TABLE taste_tuning - ADD COLUMN enriched_tag_scale double precision NOT NULL DEFAULT 0.5; diff --git a/internal/db/migrations/0045_taste_profile_eras.down.sql b/internal/db/migrations/0045_taste_profile_eras.down.sql deleted file mode 100644 index bbd08459..00000000 --- a/internal/db/migrations/0045_taste_profile_eras.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE taste_tuning DROP COLUMN IF EXISTS era_scale; -DROP TABLE IF EXISTS taste_profile_eras; diff --git a/internal/db/migrations/0045_taste_profile_eras.up.sql b/internal/db/migrations/0045_taste_profile_eras.up.sql deleted file mode 100644 index b4cdbfe1..00000000 --- a/internal/db/migrations/0045_taste_profile_eras.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- 0045_taste_profile_eras.up.sql — era/decade taste facet. A third taste --- facet alongside artists + tags: --- signed weights over decade buckets ("1990s") derived from --- albums.release_date, rebuilt daily by internal/taste next to the --- artist/tag facets. Weight is a signed float — positive = drawn to --- that era, negative = passively avoided; magnitude reflects decayed --- engagement. Consumed by the recommendation scorer's taste match. --- Mirrors taste_profile_tags: CASCADE on user delete, indexed by --- (user_id, weight DESC) so "top eras" reads stay cheap. -CREATE TABLE taste_profile_eras ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - era text NOT NULL, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, era) -); - -CREATE INDEX taste_profile_eras_user_weight_idx - ON taste_profile_eras (user_id, weight DESC); - --- Era-facet build knob, tunable in the lab (mirrors enriched_tag_scale): --- scales how strongly a decade-play imprints on the profile. --- DEFAULT 0.5 backfills the existing singleton and matches --- taste.DefaultConfig().EraScale; 0 disables the era facet entirely. -ALTER TABLE taste_tuning - ADD COLUMN era_scale double precision NOT NULL DEFAULT 0.5; diff --git a/internal/db/migrations/0046_context_time_weight.down.sql b/internal/db/migrations/0046_context_time_weight.down.sql deleted file mode 100644 index d2be5249..00000000 --- a/internal/db/migrations/0046_context_time_weight.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE recommendation_weight_profiles DROP COLUMN IF EXISTS context_time_weight; diff --git a/internal/db/migrations/0046_context_time_weight.up.sql b/internal/db/migrations/0046_context_time_weight.up.sql deleted file mode 100644 index f592279a..00000000 --- a/internal/db/migrations/0046_context_time_weight.up.sql +++ /dev/null @@ -1,12 +0,0 @@ --- 0046_context_time_weight.up.sql — time-of-day/weekday context conditioning. --- Adds a per-profile scoring weight for the new --- context-affinity term: how strongly a candidate is boosted when its artist's --- play history concentrates in the current daypart × weekday-type cell (in the --- user's local timezone). Mirrors the other ScoringWeights columns. --- --- DEFAULT 1.0 backfills both existing profile rows to a modest on-value; the --- Go ShippedRadioWeights/ShippedDailyMixWeights carry the same 1.0 so fresh --- installs seed identically. Reconcile only seeds MISSING rows (ON CONFLICT DO --- NOTHING), so existing rows rely on this DEFAULT until an admin resets. -ALTER TABLE recommendation_weight_profiles - ADD COLUMN context_time_weight double precision NOT NULL DEFAULT 1.0; diff --git a/internal/db/migrations/0047_taste_profile_moods.down.sql b/internal/db/migrations/0047_taste_profile_moods.down.sql deleted file mode 100644 index ae61a7dd..00000000 --- a/internal/db/migrations/0047_taste_profile_moods.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE taste_tuning DROP COLUMN IF EXISTS mood_scale; -DROP TABLE IF EXISTS taste_profile_moods; diff --git a/internal/db/migrations/0047_taste_profile_moods.up.sql b/internal/db/migrations/0047_taste_profile_moods.up.sql deleted file mode 100644 index 5fd5ffbb..00000000 --- a/internal/db/migrations/0047_taste_profile_moods.up.sql +++ /dev/null @@ -1,25 +0,0 @@ --- 0047_taste_profile_moods.up.sql — mood taste facet. A fourth taste facet --- alongside artists + tags + eras: signed weights over canonical mood buckets --- (melancholic / energetic / chill / …) derived from a track's enriched --- folksonomy tags via the internal/mood vocabulary, rebuilt daily. Weight is a --- signed float — positive = drawn to that mood, negative = passively avoided. --- Coverage is partial (grows with tag enrichment), so it's a supplement, not a --- foundation. Mirrors taste_profile_tags: CASCADE on user delete, indexed by --- (user_id, weight DESC). -CREATE TABLE taste_profile_moods ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - mood text NOT NULL, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, mood) -); - -CREATE INDEX taste_profile_moods_user_weight_idx - ON taste_profile_moods (user_id, weight DESC); - --- Mood-facet build knob, tunable in the lab (mirrors era_scale / enriched_tag_ --- scale): scales how strongly a mood-tagged play imprints on the profile. --- DEFAULT 0.5 backfills the existing singleton and matches --- taste.DefaultConfig().MoodScale; 0 disables the mood facet entirely. -ALTER TABLE taste_tuning - ADD COLUMN mood_scale double precision NOT NULL DEFAULT 0.5; diff --git a/internal/db/migrations/0048_play_events_device_class.down.sql b/internal/db/migrations/0048_play_events_device_class.down.sql deleted file mode 100644 index 4742e15a..00000000 --- a/internal/db/migrations/0048_play_events_device_class.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE play_events DROP COLUMN IF EXISTS device_class; diff --git a/internal/db/migrations/0048_play_events_device_class.up.sql b/internal/db/migrations/0048_play_events_device_class.up.sql deleted file mode 100644 index 6177f1a7..00000000 --- a/internal/db/migrations/0048_play_events_device_class.up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- 0048_play_events_device_class.up.sql — device-class context conditioning. --- Records which class of device a play came from (mobile / web / …), sent by --- the client on play-start and normalized server-side. Extends the --- time-of-day/weekday affinity cell (0046) to (daypart × weekday × device) for --- the radio path. Nullable + no CHECK: values are normalized in Go, so a new --- client class needs no migration, and historical rows stay NULL → excluded --- from the device dimension (a graceful cold-start; the facet ramps as new --- plays land). -ALTER TABLE play_events ADD COLUMN device_class text; diff --git a/internal/db/migrations/0049_suggestion_snoozes.down.sql b/internal/db/migrations/0049_suggestion_snoozes.down.sql deleted file mode 100644 index 05f6770d..00000000 --- a/internal/db/migrations/0049_suggestion_snoozes.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS suggestion_snoozes_expiry_idx; -DROP TABLE IF EXISTS suggestion_snoozes; diff --git a/internal/db/migrations/0049_suggestion_snoozes.up.sql b/internal/db/migrations/0049_suggestion_snoozes.up.sql deleted file mode 100644 index 9b55ef27..00000000 --- a/internal/db/migrations/0049_suggestion_snoozes.up.sql +++ /dev/null @@ -1,34 +0,0 @@ --- 0049_suggestion_snoozes.up.sql — time-boxed "not right now" on a Discover --- artist suggestion. --- --- This is NOT a dislike. Minstrel has no "Not for me" / thumbs-down / --- exclusion control — taste is learned from listening — and a snooze --- deliberately isn't one: it records no verdict on --- the music, expires on its own, and MUST NEVER feed the taste profile. It is --- acquisition triage — "I don't want to request this right now" — so the same --- candidate is free to return once snoozed_until passes. Anything that reads --- this table as negative preference signal is a bug. --- --- Per-user, never global: one household member parking a --- suggestion must not remove it from anyone else's deck. --- --- candidate_mbid is text with NO foreign key, on purpose. Suggestions come --- from artist_similarity_unmatched and are out-of-library BY DEFINITION, so --- there is no artists row to reference — the MBID is the only stable identity --- available. candidate_name is denormalized for the same reason: the manage / --- un-snooze list has nowhere else to resolve a display name from. - -CREATE TABLE suggestion_snoozes ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - candidate_mbid text NOT NULL, - candidate_name text NOT NULL, - snoozed_until timestamptz NOT NULL, - created_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, candidate_mbid) -); - --- Supports the gc sweep's unqualified `WHERE snoozed_until < now()` scan. The --- composite PK already covers every per-user read, so this is the only extra --- index worth its write cost at household-scale row counts (same reasoning as --- lidarr_quarantine in 0011). -CREATE INDEX suggestion_snoozes_expiry_idx ON suggestion_snoozes (snoozed_until); diff --git a/internal/db/migrations/0050_candidate_artist_tags.down.sql b/internal/db/migrations/0050_candidate_artist_tags.down.sql deleted file mode 100644 index cd7cd862..00000000 --- a/internal/db/migrations/0050_candidate_artist_tags.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS candidate_artist_tag_state_source_idx; -DROP TABLE IF EXISTS candidate_artist_tag_state; -DROP TABLE IF EXISTS candidate_artist_tags; diff --git a/internal/db/migrations/0050_candidate_artist_tags.up.sql b/internal/db/migrations/0050_candidate_artist_tags.up.sql deleted file mode 100644 index 72896af5..00000000 --- a/internal/db/migrations/0050_candidate_artist_tags.up.sql +++ /dev/null @@ -1,53 +0,0 @@ --- 0050_candidate_artist_tags.up.sql — folksonomy tags for OUT-OF-LIBRARY --- artists. --- --- track_tags (0042) cannot hold these: it is FK'd to tracks(id), and a --- Discover candidate has no local row by definition. So this is a parallel --- cache keyed by the candidate's MusicBrainz MBID — the only stable identity --- available for an artist we don't have. --- --- Purpose: rank Discover suggestions by overlap between these tags and the --- user's taste_profile_tags, turning "neighbour of an artist you play" into --- "matches the sound you like". --- --- GLOBAL, not per-user: a candidate's tags are a property of the artist, not --- of anyone's taste. The per-user part lives entirely in the ranking. --- --- weight is a normalized folksonomy strength in [0,1], same scale as --- track_tags, so the two can be compared without a conversion step. -CREATE TABLE candidate_artist_tags ( - candidate_mbid text NOT NULL, - tag text NOT NULL, - weight double precision NOT NULL DEFAULT 1, - PRIMARY KEY (candidate_mbid, tag) -); - --- Enrichment bookkeeping. This is a SEPARATE table rather than columns on the --- tags table, because the "providers had nothing" outcome must be recordable --- for a candidate with zero tag rows — otherwise every empty candidate stays --- eligible forever and the worker re-fetches it on every tick. --- --- tracks solved the same problem with columns on `tracks` (0042), but there is --- no per-candidate row anywhere to hang them off: artist_similarity_unmatched --- is keyed (seed_artist_id, candidate_mbid, source) and holds MANY rows per --- candidate. --- --- Absence of a row here means "never processed", so unlike tracks.tag_source --- this column can be NOT NULL — there is no null-means-pending state to model. --- 'musicbrainz' | 'lastfm' | 'mixed' → found, cached --- 'none' → providers confirmed nothing --- tag_sources_version → bump to re-process settled 'none' --- --- A transient failure writes NO row at all (rather than a row it would then --- have to distinguish), which leaves the candidate eligible for the next pass. -CREATE TABLE candidate_artist_tag_state ( - candidate_mbid text PRIMARY KEY, - tag_source text NOT NULL, - tag_sources_version integer NOT NULL DEFAULT 0, - updated_at timestamptz NOT NULL DEFAULT now() -); - --- Serves the eligibility scan's "settled 'none' under an older version" --- branch. The PK already covers the per-candidate lookups. -CREATE INDEX candidate_artist_tag_state_source_idx - ON candidate_artist_tag_state (tag_source, tag_sources_version); diff --git a/internal/db/migrations/0051_discover_tuning.down.sql b/internal/db/migrations/0051_discover_tuning.down.sql deleted file mode 100644 index 1da70de4..00000000 --- a/internal/db/migrations/0051_discover_tuning.down.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Drop any audit rows under the scope the constraint is about to forbid, --- otherwise re-adding the narrower CHECK fails against existing data. -DELETE FROM recommendation_tuning_audit WHERE scope = 'discover'; -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste')); - -DROP TABLE IF EXISTS discover_tuning; diff --git a/internal/db/migrations/0051_discover_tuning.up.sql b/internal/db/migrations/0051_discover_tuning.up.sql deleted file mode 100644 index e0cdacfe..00000000 --- a/internal/db/migrations/0051_discover_tuning.up.sql +++ /dev/null @@ -1,38 +0,0 @@ --- 0051_discover_tuning.up.sql — tunable knobs for the Discover request --- surface. --- --- A FOURTH tuning scope alongside radio / daily_mix / taste. Its own scope --- rather than extra columns on taste_tuning, for a reason that matters: --- snooze_days lives here, and a snooze must never be read as taste signal --- (0049). Filing it under 'taste' would put it one careless join away from --- exactly that leak. --- --- These are DB-backed and editable in the admin UI with no restart — the --- shipped values below are defaults, not settings. -CREATE TABLE discover_tuning ( - singleton boolean PRIMARY KEY DEFAULT true - CONSTRAINT discover_tuning_singleton_check CHECK (singleton), - -- How strongly taste-tag overlap boosts a candidate's similarity score. - -- The blend is MULTIPLICATIVE: score * (1 + w * overlap), overlap in - -- [0,1]. So 0 disables the feature outright and leaves pure similarity - -- ranking, 1.0 lets a perfectly-matching candidate double its score, and - -- a candidate with no cached tags is unchanged rather than penalised - -- (tag coverage is permanently partial, so a missing tag is no signal). - tag_overlap_weight double precision NOT NULL, - -- Default snooze duration in days. Before this a Go constant in - -- internal/api/suggestions.go; now an admin setting. - snooze_days double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now() -); - -INSERT INTO discover_tuning (singleton, tag_overlap_weight, snooze_days) -VALUES (true, 1.0, 90); - --- Rule #36: a new value for a CHECK-gated column needs the constraint --- rewritten in the SAME change, or the first audit row written under the new --- scope fails at runtime rather than at migrate time. -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover')); diff --git a/internal/db/migrations/0052_session_ips.down.sql b/internal/db/migrations/0052_session_ips.down.sql deleted file mode 100644 index e1e631d6..00000000 --- a/internal/db/migrations/0052_session_ips.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE sessions - DROP COLUMN created_ip, - DROP COLUMN last_ip; diff --git a/internal/db/migrations/0052_session_ips.up.sql b/internal/db/migrations/0052_session_ips.up.sql deleted file mode 100644 index b461d925..00000000 --- a/internal/db/migrations/0052_session_ips.up.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Session provenance for the active-sessions surface. --- --- TWO addresses, not one, and the pair is the point: a session created at --- home and now being used from somewhere else is the shape of a stolen --- token. A single "current IP" column can't express that, and a single --- "origin IP" column goes stale the moment the token moves. --- --- text rather than inet, matching user_agent directly above: these are --- stored to be displayed, never queried by subnet, and inet round-trips --- through pgx/sqlc as a netip.Prefix that renders as "1.2.3.4/32" and would --- need unwrapping at every display site. --- --- DEFAULT '' rather than NULL so existing rows — and any future insert that --- genuinely can't determine an address — stay renderable without a null --- check at every call site. The UI reads empty as "unknown" rather than --- inventing a value. -ALTER TABLE sessions - ADD COLUMN created_ip text NOT NULL DEFAULT '', - ADD COLUMN last_ip text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0053_network_settings.down.sql b/internal/db/migrations/0053_network_settings.down.sql deleted file mode 100644 index 88c2e842..00000000 --- a/internal/db/migrations/0053_network_settings.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE network_settings; diff --git a/internal/db/migrations/0053_network_settings.up.sql b/internal/db/migrations/0053_network_settings.up.sql deleted file mode 100644 index a995af37..00000000 --- a/internal/db/migrations/0053_network_settings.up.sql +++ /dev/null @@ -1,34 +0,0 @@ --- Trusted reverse-proxy depth for client-IP extraction. --- --- X-Forwarded-For grows left-to-right: each proxy APPENDS the peer it --- received the request from. For client -> CDN -> own-proxy -> Minstrel the --- app sees XFF = [client, CDN] with RemoteAddr = own-proxy. So the real --- client sits at XFF[len - hops], where hops counts the proxies you trust: --- --- 0 no proxy in front — use the socket peer, ignore XFF entirely --- 1 one reverse proxy (nginx / Caddy / Traefik terminating TLS) --- 2 a CDN in front of your own proxy (Cloudflare -> nginx -> Minstrel) --- --- Default 1: a publicly reachable Minstrel needs a TLS terminator in front of --- it, and recording that terminator's own address for every session makes the --- active-sessions surface useless — created_ip and last_ip would both --- be the proxy, so the "address changed" signal could never fire. --- --- The cost, stated on the admin card rather than buried: hops >= 1 DECLARES --- that a proxy exists. If one doesn't, a client can forge X-Forwarded-For and --- choose what its own session row shows, which defeats exactly the compromise --- detection the active-sessions surface exists for. That is inherent to the --- trusted-hop model, which is why 0 is a first-class setting and not a hidden --- escape hatch. --- --- Upper bound 10 guards a typo turning into "trust the whole header"; no real --- deployment chains ten proxies. -CREATE TABLE network_settings ( - id boolean PRIMARY KEY DEFAULT true, - trusted_proxy_hops int NOT NULL DEFAULT 1, - CONSTRAINT network_settings_singleton CHECK (id = true), - CONSTRAINT network_settings_hops_range - CHECK (trusted_proxy_hops >= 0 AND trusted_proxy_hops <= 10) -); - -INSERT INTO network_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0054_track_tag_read_version.down.sql b/internal/db/migrations/0054_track_tag_read_version.down.sql deleted file mode 100644 index b948246e..00000000 --- a/internal/db/migrations/0054_track_tag_read_version.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE tracks - DROP COLUMN tag_read_version; diff --git a/internal/db/migrations/0054_track_tag_read_version.up.sql b/internal/db/migrations/0054_track_tag_read_version.up.sql deleted file mode 100644 index e9b0f3a8..00000000 --- a/internal/db/migrations/0054_track_tag_read_version.up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Records which version of the scanner's tag-extraction logic last wrote a --- track's tag-derived columns. --- --- DEFAULT 0 is the point of this migration: every existing row lands below the --- scanner's current library.tagReadVersion, so the next scan re-reads its tags --- instead of short-circuiting on the mtime check. That repairs genre values the --- old reader welded together ("Alternative Rock" + "Rock" -> "Alternative --- RockRock") without anyone wiping and rebuilding the library. --- --- Bump library.tagReadVersion in Go — not this default — whenever a tag --- extraction fix needs to reach already-indexed files. That makes tag repairs a --- self-healing scan rather than a manual full rebuild, which is why this is a --- version number and not a boolean "needs_reread" flag. -ALTER TABLE tracks - ADD COLUMN tag_read_version smallint NOT NULL DEFAULT 0; diff --git a/internal/db/migrations/0055_track_missing_since.down.sql b/internal/db/migrations/0055_track_missing_since.down.sql deleted file mode 100644 index d9bc5bc1..00000000 --- a/internal/db/migrations/0055_track_missing_since.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DROP INDEX IF EXISTS tracks_missing_since_idx; - -ALTER TABLE tracks - DROP COLUMN missing_since; diff --git a/internal/db/migrations/0055_track_missing_since.up.sql b/internal/db/migrations/0055_track_missing_since.up.sql deleted file mode 100644 index 64cdea80..00000000 --- a/internal/db/migrations/0055_track_missing_since.up.sql +++ /dev/null @@ -1,25 +0,0 @@ --- Marks a track whose file the scanner could no longer find. --- --- NULL means present. A timestamp means the file was absent as of that scan, --- and is the point from which "how long has this been gone" is measured — which --- is what a later cleanup pass needs in order to require a grace period rather --- than deleting on a single missed stat. --- --- Deliberately a nullable timestamp rather than a boolean: "missing" is not a --- state we want to act on immediately, and the age is the only thing that makes --- an automated deletion safe to reason about. --- --- No default and no backfill. Existing rows start NULL (present) and the next --- full scan sets the mark where it belongs — a migration cannot check the --- filesystem, and guessing here would mark the whole library on a server whose --- media volume happens to be detached at upgrade time. -ALTER TABLE tracks - ADD COLUMN missing_since timestamptz; - --- Partial index: the only query that filters on this column positively is the --- admin "what's missing" list, which is a small set. Playback and browse --- queries filter `missing_since IS NULL`, which matches nearly every row and is --- better served by a sequential scan than an index lookup. -CREATE INDEX tracks_missing_since_idx - ON tracks (missing_since) - WHERE missing_since IS NOT NULL; diff --git a/internal/db/migrations/0056_missing_reacquisition.down.sql b/internal/db/migrations/0056_missing_reacquisition.down.sql deleted file mode 100644 index 5acbc0ba..00000000 --- a/internal/db/migrations/0056_missing_reacquisition.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS reacquisition_settings; -DROP TABLE IF EXISTS missing_reacquisitions; diff --git a/internal/db/migrations/0056_missing_reacquisition.up.sql b/internal/db/migrations/0056_missing_reacquisition.up.sql deleted file mode 100644 index 175b576f..00000000 --- a/internal/db/migrations/0056_missing_reacquisition.up.sql +++ /dev/null @@ -1,97 +0,0 @@ --- Auto re-acquisition of missing files via Lidarr. Before this a missing --- file was a dead end: reconcile marks it, every selection path skips it, --- the admin surface lists it, and there it sits. --- --- The unit here is the ALBUM, not the track, and that is the design decision --- carrying most of the safety. Lidarr acquires releases; there is no --- meaningful "fetch me one track" operation, and a track-kind request needs a --- recording MBID plenty of files simply don't have. Grouping by album means --- a reorganised album with dozens of missing files becomes one request. - -CREATE TABLE missing_reacquisitions ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - attempts int NOT NULL DEFAULT 0, - last_attempt_at timestamptz, - -- The request this album's most recent attempt produced. SET NULL rather - -- than CASCADE: a purged request row must not erase the attempt history - -- that stops us asking again in a loop. - last_request_id uuid REFERENCES lidarr_requests (id) ON DELETE SET NULL, - -- Set when the attempt budget is spent. Distinct from "attempts = max" - -- so the reason survives a later change to the configured maximum, and so - -- the admin surface can say "gave up on the 3rd of August" rather than - -- inferring it. - gave_up_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT missing_reacquisitions_attempts_nonneg CHECK (attempts >= 0) -); - --- The sweeper's own read: albums due another attempt, oldest attempt first. --- Partial on the not-given-up rows because a spent album is never selected --- again and would otherwise grow the index forever. -CREATE INDEX missing_reacquisitions_due_idx - ON missing_reacquisitions (last_attempt_at NULLS FIRST) - WHERE gave_up_at IS NULL; - --- Settings, singleton in the style of network_settings (0053). Every value an --- admin might want to tune lives here rather than in YAML, changed without a --- restart. -CREATE TABLE reacquisition_settings ( - id boolean PRIMARY KEY DEFAULT true, - - -- Master switch. Default true: this is meant to happen by itself, and a - -- feature that ships switched off is a feature nobody finds. - enabled boolean NOT NULL DEFAULT true, - - -- How long a file must have been missing before the FIRST attempt. This - -- is what separates "automatic" from "trigger-happy": a filesystem lies - -- transiently -- an unmounted volume, a container that started before its - -- media mount attached, a NAS mid-reboot -- and every one of those - -- resolves itself well inside a day at no cost. tracks.missing_since is - -- never re-stamped, so it is a true "gone since" clock to measure - -- against. - grace_hours int NOT NULL DEFAULT 24, - - -- Exponential spacing between attempts: base * 2^(attempts-1), clamped to - -- backoff_max_hours. 6h -> 12h -> 24h -> 48h by default. An album Lidarr - -- genuinely cannot find must get quieter, not keep pace. - backoff_base_hours int NOT NULL DEFAULT 6, - backoff_max_hours int NOT NULL DEFAULT 168, -- one week - - -- Attempts before giving up. Three real tries spread over days is enough - -- to ride out a transient Lidarr/indexer outage; past that the answer is - -- "this release is not obtainable" and asking again is noise. - max_attempts int NOT NULL DEFAULT 3, - - -- Ceiling on requests created per sweep. Album grouping already collapses - -- the common case, but a genuinely large loss (a whole drive slipping - -- under reconcile's 25% mark cap) should still trickle rather than dump - -- hundreds of requests into the queue at once. - max_per_pass int NOT NULL DEFAULT 20, - - -- Whether the sweeper approves what it creates. Requests are created - -- pending and nothing reaches Lidarr until approval, so with this off the - -- feature is a notification rather than an attempt -- which is why the - -- default is on. Off is the review-first posture: rows appear in the - -- admin Requests queue for a human to release. - auto_approve boolean NOT NULL DEFAULT true, - - CONSTRAINT reacquisition_settings_singleton CHECK (id = true), - -- Ranges exist to stop a typo becoming a behaviour change: a 0-hour grace - -- would fire on every transient unmount, and a 10000-per-pass cap would - -- defeat the point of having one. - CONSTRAINT reacquisition_settings_grace_range - CHECK (grace_hours >= 1 AND grace_hours <= 720), - CONSTRAINT reacquisition_settings_backoff_base_range - CHECK (backoff_base_hours >= 1 AND backoff_base_hours <= 168), - CONSTRAINT reacquisition_settings_backoff_max_range - CHECK (backoff_max_hours >= 1 AND backoff_max_hours <= 720), - CONSTRAINT reacquisition_settings_backoff_ordered - CHECK (backoff_max_hours >= backoff_base_hours), - CONSTRAINT reacquisition_settings_attempts_range - CHECK (max_attempts >= 1 AND max_attempts <= 10), - CONSTRAINT reacquisition_settings_per_pass_range - CHECK (max_per_pass >= 1 AND max_per_pass <= 200) -); - -INSERT INTO reacquisition_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0057_songs_like_tuning.down.sql b/internal/db/migrations/0057_songs_like_tuning.down.sql deleted file mode 100644 index 96070ff5..00000000 --- a/internal/db/migrations/0057_songs_like_tuning.down.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Drop the rows the narrower constraints are about to forbid, or re-adding --- them fails against existing data (the 0051 down-migration pattern). -DELETE FROM recommendation_weight_profiles WHERE profile = 'songs_like'; -DELETE FROM recommendation_tuning_audit WHERE scope = 'songs_like'; - -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover')); - -ALTER TABLE recommendation_weight_profiles - DROP CONSTRAINT recommendation_weight_profiles_profile_check; -ALTER TABLE recommendation_weight_profiles - ADD CONSTRAINT recommendation_weight_profiles_profile_check - CHECK (profile IN ('radio', 'daily_mix')); diff --git a/internal/db/migrations/0057_songs_like_tuning.up.sql b/internal/db/migrations/0057_songs_like_tuning.up.sql deleted file mode 100644 index c8071e66..00000000 --- a/internal/db/migrations/0057_songs_like_tuning.up.sql +++ /dev/null @@ -1,33 +0,0 @@ --- 0057_songs_like_tuning.up.sql — a THIRD weight profile, for Songs-like. --- --- Before: Songs-like shared the `daily_mix` profile with For-You. The two --- surfaces want opposite things: For-You is a broad "what will they enjoy --- today", Songs-like answers "what sounds like THIS" and should stay in one --- neighbourhood of sound, and under one set of weights the broad answer wins. --- --- Under the shared daily_mix weights, an UNRELATED track the user had liked --- and not played recently scored 1.0 + 2.0 + 1.0 = 4.0 before taste, while a --- PERFECT similarity match they had not liked scored 1.0 + 1.5 = 2.5. Liking --- something outranked sounding like the seed. Splitting the profile is what --- lets similarity dominate here without making For-You narrow. --- --- Rows are seeded by the recsettings boot reconcile, not here, so shipped --- defaults live in exactly one place (Go) — same as 0040. - --- Rule #36: a new value for a CHECK-gated column needs the constraint --- rewritten in the SAME change, or the first row written under the new --- profile fails at runtime rather than at migrate time. -ALTER TABLE recommendation_weight_profiles - DROP CONSTRAINT recommendation_weight_profiles_profile_check; -ALTER TABLE recommendation_weight_profiles - ADD CONSTRAINT recommendation_weight_profiles_profile_check - CHECK (profile IN ('radio', 'daily_mix', 'songs_like')); - --- The audit table gates the same name on a separate constraint. Missing this --- one would let the profile be seeded and then fail on the first knob turn — --- green at boot, 500 on first use. -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover', 'songs_like')); diff --git a/internal/db/migrations/0058_track_fingerprints.down.sql b/internal/db/migrations/0058_track_fingerprints.down.sql deleted file mode 100644 index c04a359c..00000000 --- a/internal/db/migrations/0058_track_fingerprints.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE track_fingerprints; diff --git a/internal/db/migrations/0058_track_fingerprints.up.sql b/internal/db/migrations/0058_track_fingerprints.up.sql deleted file mode 100644 index a42e6151..00000000 --- a/internal/db/migrations/0058_track_fingerprints.up.sql +++ /dev/null @@ -1,37 +0,0 @@ --- 0058_track_fingerprints.up.sql — an acoustic identity per track. --- --- A table of its own rather than columns on tracks, for the hot path's sake: --- tracks is read with SELECT * by eight queries, among them ListTracksByAlbum, --- SearchTracks and GetTracksByIDs — album pages, search, the Subsonic surface. --- A ~4 KB chromaprint column on tracks would be de-TOASTed on every one of --- those reads to carry a value only the duplicate sweep ever looks at. --- --- What a row means, which the backfill depends on: --- no row never fingerprinted --- fingerprint_version < current derived by an older method; re-derive it --- fingerprint_version = current attempted; a NULL value means that tool --- failed on this file, and it is not retried --- until the file changes --- A failure that says nothing about the file — a timeout, a cancelled scan, a --- missing binary — writes no row at all, so the backfill tries again. -CREATE TABLE track_fingerprints ( - -- CASCADE is right here, unlike for the likes and play history the - -- duplicate merge has to carry across: a fingerprint describes one file's - -- bytes and means nothing once that file's row is gone. - track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE, - -- SHA-256 of the ENCODED audio packets (ffmpeg -c:a copy -f hash), not of - -- decoded samples. internal/library/fingerprint.go says why. - audio_stream_sha256 bytea - CHECK (audio_stream_sha256 IS NULL OR octet_length(audio_stream_sha256) = 32), - -- fpcalc -raw -signed: the same 32 bits per item, stored signed because - -- integer is. - chromaprint integer[], - fingerprint_version smallint NOT NULL, - computed_at timestamptz NOT NULL DEFAULT now() -); - --- The exact duplicate tier is an equality match on this column. Partial --- because a NULL is never looked up — it only means the hash was not taken. -CREATE INDEX track_fingerprints_audio_stream_sha256 - ON track_fingerprints (audio_stream_sha256) - WHERE audio_stream_sha256 IS NOT NULL; diff --git a/internal/db/migrations/0059_duplicate_groups.down.sql b/internal/db/migrations/0059_duplicate_groups.down.sql deleted file mode 100644 index 1d37bf4c..00000000 --- a/internal/db/migrations/0059_duplicate_groups.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DROP INDEX IF EXISTS tracks_duration_id_idx; -DROP TABLE duplicate_group_members; -DROP TABLE duplicate_groups; -DROP TABLE duplicate_sweeps; diff --git a/internal/db/migrations/0059_duplicate_groups.up.sql b/internal/db/migrations/0059_duplicate_groups.up.sql deleted file mode 100644 index 67073cd6..00000000 --- a/internal/db/migrations/0059_duplicate_groups.up.sql +++ /dev/null @@ -1,54 +0,0 @@ --- 0059_duplicate_groups.up.sql — proposed duplicates and the sweeps that find --- them. --- --- The sweep compares fingerprints (track_fingerprints, 0058) and proposes --- groups of tracks that hold one recording. Nothing here merges anything: a --- group is a proposal an admin reviews, and the merge is a separate act. - --- One row per sweep. Lets the report tell "the sweep has never run" apart from --- "it ran and found nothing", and gives the in-flight guard something to check, --- the same way scan_runs does for the library scan. -CREATE TABLE duplicate_sweeps ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - started_at timestamptz NOT NULL DEFAULT now(), - finished_at timestamptz, - candidates integer, - groups_found integer, - oversize_clusters integer, - error_message text -); -CREATE INDEX duplicate_sweeps_started_at_idx ON duplicate_sweeps (started_at DESC); - -CREATE TABLE duplicate_groups ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - -- The group's identity: its member track ids, sorted and joined. A sweep - -- that finds the same tracks again updates this row rather than proposing - -- them twice, and a dismissal stays attached to the set it was made about. - member_key text NOT NULL UNIQUE, - -- Rule 36: a new value for either CHECK swaps the constraint in the same - -- migration. - tier text NOT NULL CHECK (tier IN ('exact', 'acoustic')), - -- Largest disagreement between any two members; NULL for exact groups, - -- which have no score. - worst_bit_error_rate real, - status text NOT NULL DEFAULT 'pending' - CHECK (status IN ('pending', 'dismissed', 'merged')), - detected_at timestamptz NOT NULL DEFAULT now(), - last_seen_sweep_id uuid REFERENCES duplicate_sweeps (id) ON DELETE SET NULL, - resolved_at timestamptz -); -CREATE INDEX duplicate_groups_status_idx ON duplicate_groups (status); - -CREATE TABLE duplicate_group_members ( - group_id uuid NOT NULL REFERENCES duplicate_groups (id) ON DELETE CASCADE, - -- CASCADE is right here: a track that genuinely leaves the library has no - -- place in a proposal about its duplicates. - track_id uuid NOT NULL REFERENCES tracks (id) ON DELETE CASCADE, - PRIMARY KEY (group_id, track_id) -); -CREATE INDEX duplicate_group_members_track_idx ON duplicate_group_members (track_id); - --- The sweep streams candidates in (duration_ms, id) order, keyset-paged, so it --- only ever holds a few seconds' worth of durations in memory. Without this --- each page would sort the whole library again. -CREATE INDEX tracks_duration_id_idx ON tracks (duration_ms, id); diff --git a/internal/db/migrations/0060_play_events_track_index.down.sql b/internal/db/migrations/0060_play_events_track_index.down.sql deleted file mode 100644 index af749a3f..00000000 --- a/internal/db/migrations/0060_play_events_track_index.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP INDEX IF EXISTS play_events_track_idx; diff --git a/internal/db/migrations/0060_play_events_track_index.up.sql b/internal/db/migrations/0060_play_events_track_index.up.sql deleted file mode 100644 index 2c19bd36..00000000 --- a/internal/db/migrations/0060_play_events_track_index.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- 0060_play_events_track_index.up.sql — play_events by track. --- --- play_events is indexed by (user_id, started_at) and (user_id, track_id), both --- led by user. Nothing reached it by track alone until the duplicates report, --- which shows each copy's play count — a scan of the whole table per copy — and --- the duplicate merge, which repoints a duplicate's play history onto the copy --- being kept. Both ask "every play of this track", whoever played it. -CREATE INDEX play_events_track_idx ON play_events (track_id); diff --git a/internal/db/migrations/0061_fingerprint_settings.down.sql b/internal/db/migrations/0061_fingerprint_settings.down.sql deleted file mode 100644 index 31d6d9cc..00000000 --- a/internal/db/migrations/0061_fingerprint_settings.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE track_fingerprints DROP COLUMN chromaprint_length_sec; -DROP TABLE fingerprint_settings; diff --git a/internal/db/migrations/0061_fingerprint_settings.up.sql b/internal/db/migrations/0061_fingerprint_settings.up.sql deleted file mode 100644 index 89911d69..00000000 --- a/internal/db/migrations/0061_fingerprint_settings.up.sql +++ /dev/null @@ -1,48 +0,0 @@ --- 0061_fingerprint_settings.up.sql — fingerprinting's knobs, in admin --- Settings: anything an admin might tune is a database row, changed without a --- restart. Singleton in the style of reacquisition_settings (0056). -CREATE TABLE fingerprint_settings ( - id boolean PRIMARY KEY DEFAULT true, - - -- Fingerprinting new files, the backfill, and the duplicate sweep. Off - -- stops the decode work entirely — the reason to turn it off is a slow NAS. - -- On by default: without it the library cannot tell its duplicates apart. - enabled boolean NOT NULL DEFAULT true, - - -- Seconds of audio fpcalc fingerprints. Chromaprints taken at different - -- lengths cannot be compared, which is why track_fingerprints records the - -- length each row was taken at (below): change this and every chromaprint - -- is re-derived, and until then only rows at the new length are compared. - chromaprint_length_sec integer NOT NULL DEFAULT 120, - - -- The most disagreement two aligned fingerprints may show and still be - -- proposed as one recording. Unrelated audio sits near 0.5, so the ceiling - -- stays well clear of it. - acoustic_max_bit_error_rate double precision NOT NULL DEFAULT 0.15, - - -- Files the backfill decodes at once. Decoding competes with playback - -- transcoding for CPU and with streaming for the mount. - backfill_concurrency integer NOT NULL DEFAULT 2, - - -- The least time between duplicate sweeps. A sweep still runs only when - -- fingerprints have changed since the last one. - sweep_interval_hours integer NOT NULL DEFAULT 1, - - -- When the settings were last saved. A new threshold or length can change - -- what a sweep finds, so a save makes a sweep due. - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT fingerprint_settings_singleton CHECK (id = true), - CONSTRAINT fingerprint_settings_length_range - CHECK (chromaprint_length_sec >= 30 AND chromaprint_length_sec <= 600), - CONSTRAINT fingerprint_settings_threshold_range - CHECK (acoustic_max_bit_error_rate >= 0.01 AND acoustic_max_bit_error_rate <= 0.35), - CONSTRAINT fingerprint_settings_concurrency_range - CHECK (backfill_concurrency >= 1 AND backfill_concurrency <= 8), - CONSTRAINT fingerprint_settings_sweep_interval_range - CHECK (sweep_interval_hours >= 1 AND sweep_interval_hours <= 168) -); -INSERT INTO fingerprint_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; - --- Every row written so far was taken at fpcalc's default length. -ALTER TABLE track_fingerprints ADD COLUMN chromaprint_length_sec integer NOT NULL DEFAULT 120; diff --git a/internal/db/migrations/0062_network_public_url.down.sql b/internal/db/migrations/0062_network_public_url.down.sql deleted file mode 100644 index 418a7cd6..00000000 --- a/internal/db/migrations/0062_network_public_url.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE network_settings DROP COLUMN IF EXISTS public_url; diff --git a/internal/db/migrations/0062_network_public_url.up.sql b/internal/db/migrations/0062_network_public_url.up.sql deleted file mode 100644 index 4eb7dee8..00000000 --- a/internal/db/migrations/0062_network_public_url.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- The address users reach Minstrel at, e.g. https://music.example.com. --- --- Before: password-reset links were built from the request's Host header, --- which the requester controls, so a forgot-password call with a forged Host --- would email the victim a real reset token on a link to the attacker's --- server. After: links are built only from this admin-set value, and none --- are sent while it is empty. -ALTER TABLE network_settings ADD COLUMN public_url text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0063_api_token_hash.down.sql b/internal/db/migrations/0063_api_token_hash.down.sql deleted file mode 100644 index 8b80a9f4..00000000 --- a/internal/db/migrations/0063_api_token_hash.down.sql +++ /dev/null @@ -1,7 +0,0 @@ --- The keys cannot be recovered from their hashes. Rolling back gives every --- user a new random key; Subsonic clients using apiKey need the new one. -ALTER TABLE users ADD COLUMN api_token text; -UPDATE users SET api_token = md5(random()::text || id::text || clock_timestamp()::text); -ALTER TABLE users ALTER COLUMN api_token SET NOT NULL; -ALTER TABLE users ADD CONSTRAINT users_api_token_key UNIQUE (api_token); -ALTER TABLE users DROP COLUMN api_token_hash; diff --git a/internal/db/migrations/0063_api_token_hash.up.sql b/internal/db/migrations/0063_api_token_hash.up.sql deleted file mode 100644 index 646d6b18..00000000 --- a/internal/db/migrations/0063_api_token_hash.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- API keys (the OpenSubsonic apiKey) are stored as their sha256, hex, the --- same way session tokens are. A leaked database row or backup no longer --- hands out working keys. Existing keys are hashed in place, so every --- Subsonic client keeps working; the key itself can no longer be shown --- again, only replaced. -ALTER TABLE users ADD COLUMN api_token_hash text; -UPDATE users SET api_token_hash = encode(sha256(convert_to(api_token, 'UTF8')), 'hex'); -ALTER TABLE users ALTER COLUMN api_token_hash SET NOT NULL; -ALTER TABLE users ADD CONSTRAINT users_api_token_hash_key UNIQUE (api_token_hash); -ALTER TABLE users DROP COLUMN api_token; diff --git a/internal/db/migrations/0064_clear_subsonic_password.down.sql b/internal/db/migrations/0064_clear_subsonic_password.down.sql deleted file mode 100644 index 98a094aa..00000000 --- a/internal/db/migrations/0064_clear_subsonic_password.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- The cleared values are gone and were never meant to be kept; nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0064_clear_subsonic_password.up.sql b/internal/db/migrations/0064_clear_subsonic_password.up.sql deleted file mode 100644 index bcb885bc..00000000 --- a/internal/db/migrations/0064_clear_subsonic_password.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Before: `minstrel admin reset-password` copied the new login password into --- subsonic_password, so every account recovered through the CLI had its login --- password stored in plain text, and a later password change in Settings left --- that copy behind. After: the CLI does not write this column; a Subsonic --- password is generated separately in Settings and is never the login --- password. Clearing every value here removes the copies already made. --- --- Accounts whose Subsonic client signs in with t/s stop working until the user --- generates a Subsonic password (or switches the client to an API key). -UPDATE users SET subsonic_password = NULL WHERE subsonic_password IS NOT NULL; diff --git a/internal/db/migrations/0065_track_loudness.down.sql b/internal/db/migrations/0065_track_loudness.down.sql deleted file mode 100644 index 0bb9eced..00000000 --- a/internal/db/migrations/0065_track_loudness.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS loudness_settings; -DROP TABLE IF EXISTS track_loudness; diff --git a/internal/db/migrations/0065_track_loudness.up.sql b/internal/db/migrations/0065_track_loudness.up.sql deleted file mode 100644 index 17b46ace..00000000 --- a/internal/db/migrations/0065_track_loudness.up.sql +++ /dev/null @@ -1,65 +0,0 @@ --- 0065_track_loudness.up.sql — measured loudness per track, for loudness --- normalization. --- --- Measured with ffmpeg's EBU R128 filter rather than read from ReplayGain tags: --- tags in the wild are written against four different reference levels, and --- most files have none. internal/library/loudness.go says how it is measured. --- --- A table of its own rather than columns on tracks, for the reason --- track_fingerprints is (0058): tracks is read with SELECT * on the hot path, --- and the block histogram is a few hundred integers only album loudness reads. --- --- What a row means, which the backfill depends on: --- no row never analyzed, or the file changed since --- analysis_version < current measured by an older method; measure again --- analysis_version = current settled until the file changes: --- integrated_lufs NOT NULL measured --- integrated_lufs NULL, unreadable false --- read fine, but no 400 ms block was above --- the -70 LUFS gate: silence, or too short --- unreadable true ffmpeg could not decode the file --- A failure that says nothing about the file (a timeout, a cancelled pass, a --- missing ffmpeg) writes no row, so the backfill tries again. -CREATE TABLE track_loudness ( - track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE, - -- Gated integrated loudness (ITU-R BS.1770), mono measured as dual mono. - integrated_lufs real, - -- Highest inter-sample peak, from 4x oversampling, in dB relative to full - -- scale. NULL for digital silence, whose peak is -inf. - true_peak_dbtp real, - -- Loudness range (EBU Tech 3342): how much the loudness moves within the - -- track. Not used for gain; kept because it costs nothing here. - loudness_range_lu real, - -- How many 400 ms gating blocks fell in each 0.1 LU bin. Bin i holds blocks - -- measuring -70.0 + (block_hist_start + i) / 10 LUFS; the array is trimmed - -- to the first and last non-empty bins. Album loudness is the gated - -- loudness of every block on the album, so it is computed from these - -- exactly, with no second decode. - block_hist_start smallint, - block_hist integer[], - unreadable boolean NOT NULL DEFAULT false, - analysis_version smallint NOT NULL, - analyzed_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT track_loudness_hist_pair - CHECK ((block_hist IS NULL) = (block_hist_start IS NULL)) -); - --- Loudness analysis's knobs, in admin Settings. Rule 25: an operator setting is --- a database row, changed without a restart. Singleton in the style of --- fingerprint_settings (0061). -CREATE TABLE loudness_settings ( - id boolean PRIMARY KEY DEFAULT true, - -- Off stops the background analysis. Tracks already measured keep their - -- values, so normalization keeps working for them. - enabled boolean NOT NULL DEFAULT true, - -- Files analyzed at once. Each is a full decode, competing with playback - -- transcoding for CPU and with streaming for the mount. - backfill_concurrency integer NOT NULL DEFAULT 2, - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT loudness_settings_singleton CHECK (id = true), - CONSTRAINT loudness_settings_concurrency_range - CHECK (backfill_concurrency >= 1 AND backfill_concurrency <= 8) -); -INSERT INTO loudness_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0066_album_loudness.down.sql b/internal/db/migrations/0066_album_loudness.down.sql deleted file mode 100644 index 7e0a1306..00000000 --- a/internal/db/migrations/0066_album_loudness.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS album_loudness; diff --git a/internal/db/migrations/0066_album_loudness.up.sql b/internal/db/migrations/0066_album_loudness.up.sql deleted file mode 100644 index 0e04820f..00000000 --- a/internal/db/migrations/0066_album_loudness.up.sql +++ /dev/null @@ -1,30 +0,0 @@ --- 0066_album_loudness.up.sql — album loudness for album-mode normalization. --- --- An album's loudness is the gated loudness of every 400 ms block on the album, --- not an average of its tracks' values: a quiet interlude and a loud single --- should keep their difference when the album plays in order. It is computed --- from the per-track block histograms in track_loudness (0065), summed, so no --- audio is decoded again. --- --- A derived value, recomputed by the loudness worker whenever its inputs --- change. inputs_digest is an md5 over the album's present tracks and the --- measurement each holds; the worker recomputes every album whose stored digest --- no longer matches. That one comparison covers every way membership changes --- (a scan moving a track between albums, a duplicate merge, a delete, a file --- going missing or coming back) without hooking each of them. -CREATE TABLE album_loudness ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - -- NULL until every present track has a settled measurement: an album - -- leveled from half its tracks would jump when the rest arrived. Also NULL - -- for an album with no block above the gate. Clients fall back to track - -- gain while it is NULL. - integrated_lufs real, - -- The loudest true peak of any track on the album, so album gain is held - -- to the headroom of its loudest track. - true_peak_dbtp real, - tracks_total integer NOT NULL, - -- Tracks with a settled measurement (measured, silent or unreadable). - tracks_settled integer NOT NULL, - inputs_digest text NOT NULL, - computed_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0067_user_normalization_prefs.down.sql b/internal/db/migrations/0067_user_normalization_prefs.down.sql deleted file mode 100644 index 650e65d7..00000000 --- a/internal/db/migrations/0067_user_normalization_prefs.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS user_normalization_prefs; diff --git a/internal/db/migrations/0067_user_normalization_prefs.up.sql b/internal/db/migrations/0067_user_normalization_prefs.up.sql deleted file mode 100644 index 4f767df7..00000000 --- a/internal/db/migrations/0067_user_normalization_prefs.up.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Each user's loudness-normalization preference. It is kept on --- the server, not per device, so the web player, the Android app and the --- leveled stream for UPnP/Sonos all apply the same one. --- --- mode: off, auto (album gain while an album plays in order, otherwise --- track gain), track or album. --- target: the loudness tracks are leveled to, in LUFS. --- boost: headroom raises quiet tracks only as far as their true peak --- allows; limiter raises them all the way and limits the peaks. --- --- No row means the defaults, which are the column defaults here and --- library.DefaultNormalizationPrefs in Go (a test holds them equal). -CREATE TABLE user_normalization_prefs ( - user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - mode text NOT NULL DEFAULT 'auto' - CHECK (mode IN ('off', 'auto', 'track', 'album')), - target_lufs smallint NOT NULL DEFAULT -18 - CHECK (target_lufs IN (-18, -16, -14)), - boost text NOT NULL DEFAULT 'headroom' - CHECK (boost IN ('headroom', 'limiter')), - updated_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0068_leveled_stream_cache.down.sql b/internal/db/migrations/0068_leveled_stream_cache.down.sql deleted file mode 100644 index 59ab4d17..00000000 --- a/internal/db/migrations/0068_leveled_stream_cache.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE loudness_settings - DROP CONSTRAINT loudness_settings_leveled_cache_range, - DROP COLUMN leveled_cache_mb; diff --git a/internal/db/migrations/0068_leveled_stream_cache.up.sql b/internal/db/migrations/0068_leveled_stream_cache.up.sql deleted file mode 100644 index 84293517..00000000 --- a/internal/db/migrations/0068_leveled_stream_cache.up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- 0068_leveled_stream_cache.up.sql — the size cap of the leveled-stream render --- cache. --- --- Sonos and other UPnP renderers fetch a track's URL themselves, so the phone --- cannot level what they play. The server renders a gain-applied FLAC for them --- instead and keeps it on disk, oldest-used first out once the cache is over --- this size. An admin setting, on the loudness settings row it belongs with. -ALTER TABLE loudness_settings - ADD COLUMN leveled_cache_mb integer NOT NULL DEFAULT 2048, - ADD CONSTRAINT loudness_settings_leveled_cache_range - CHECK (leveled_cache_mb >= 256 AND leveled_cache_mb <= 65536); diff --git a/internal/db/migrations/0069_acoustid_lookup.down.sql b/internal/db/migrations/0069_acoustid_lookup.down.sql deleted file mode 100644 index 3dae17cb..00000000 --- a/internal/db/migrations/0069_acoustid_lookup.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -DROP TABLE IF EXISTS acoustid_settings; -DROP TABLE IF EXISTS track_acoustid_lookups; --- Looked-up ids go with the lookups; a tag id stays. -UPDATE tracks SET mbid = NULL WHERE mbid_source = 'acoustid'; -ALTER TABLE tracks DROP CONSTRAINT IF EXISTS tracks_mbid_source_pair; -ALTER TABLE tracks DROP CONSTRAINT IF EXISTS tracks_mbid_source_check; -ALTER TABLE tracks DROP COLUMN IF EXISTS mbid_source; diff --git a/internal/db/migrations/0069_acoustid_lookup.up.sql b/internal/db/migrations/0069_acoustid_lookup.up.sql deleted file mode 100644 index ecd56c99..00000000 --- a/internal/db/migrations/0069_acoustid_lookup.up.sql +++ /dev/null @@ -1,69 +0,0 @@ --- 0069_acoustid_lookup.up.sql — recording MBIDs looked up through AcoustID --- for tracks whose tags carry none. --- --- A track with no recording MBID is invisible to the ListenBrainz similarity --- arm in both directions, so this fills the ids the tags leave empty. - --- Where tracks.mbid came from. The file's own tag always outranks a lookup: --- the scan's upsert keeps a looked-up id while the tag carries --- none, and replaces it the moment the tag carries one. -ALTER TABLE tracks ADD COLUMN mbid_source text; --- Every id stored so far was read from a tag (the scan or the tag backfill), --- or inherited from a merged duplicate's tag. -UPDATE tracks SET mbid_source = 'tag' WHERE mbid IS NOT NULL; -ALTER TABLE tracks - ADD CONSTRAINT tracks_mbid_source_check CHECK (mbid_source IN ('tag', 'acoustid')), - ADD CONSTRAINT tracks_mbid_source_pair CHECK ((mbid IS NULL) = (mbid_source IS NULL)); - --- What happened the last time a track was looked up. A table of its own, as --- track_loudness is (0065): tracks is read with SELECT * on the hot path. --- --- What a row means, which the lookup worker depends on: --- no row never looked up, or the file changed since (the scan deletes --- the row): look it up --- matched one recording cleared the score threshold, or one was left --- after disambiguating by title and length; recording_mbid is it --- ambiguous several recordings cleared it and nothing told them apart. --- Nothing is written: a wrong MBID would feed similarity the --- wrong neighbours, which is worse than none --- no_match AcoustID linked nothing at or above the threshold --- failed fpcalc rejected the file, or AcoustID rejected its print --- Every state is settled until the file changes. A failure that says nothing --- about the file (AcoustID unreachable, a timeout, a cancelled pass) writes no --- row, so the worker tries again. -CREATE TABLE track_acoustid_lookups ( - track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE, - state text NOT NULL, - -- The best score any linked recording had; NULL when none was linked. - best_score real, - -- How many distinct recordings were linked, at any score. - candidates integer NOT NULL DEFAULT 0, - recording_mbid text, - -- Why a lookup failed, for the admin list. - detail text, - looked_up_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT track_acoustid_lookups_state_check - CHECK (state IN ('matched', 'ambiguous', 'no_match', 'failed')), - CONSTRAINT track_acoustid_lookups_matched_has_mbid - CHECK ((state = 'matched') = (recording_mbid IS NOT NULL)) -); -CREATE INDEX track_acoustid_lookups_state ON track_acoustid_lookups (state); - --- AcoustID's knobs, in admin Settings. Singleton in the style of --- loudness_settings (0065). -CREATE TABLE acoustid_settings ( - id boolean PRIMARY KEY DEFAULT true, - -- Off by default: AcoustID needs a key an admin registers, and the lookup - -- sends fingerprints to a third party. - enabled boolean NOT NULL DEFAULT false, - api_key text, - -- The score a recording needs before it is considered at all. AcoustID - -- scores a true match close to 1; 0.85 leaves room for a lossy encode. - min_score real NOT NULL DEFAULT 0.85, - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT acoustid_settings_singleton CHECK (id = true), - CONSTRAINT acoustid_settings_min_score_range CHECK (min_score >= 0.5 AND min_score <= 1) -); -INSERT INTO acoustid_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0070_album_release_group_mbid.down.sql b/internal/db/migrations/0070_album_release_group_mbid.down.sql deleted file mode 100644 index 1deb2957..00000000 --- a/internal/db/migrations/0070_album_release_group_mbid.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS albums_release_group_mbid_idx; -ALTER TABLE albums DROP COLUMN IF EXISTS release_group_mbid; diff --git a/internal/db/migrations/0070_album_release_group_mbid.up.sql b/internal/db/migrations/0070_album_release_group_mbid.up.sql deleted file mode 100644 index e6068030..00000000 --- a/internal/db/migrations/0070_album_release_group_mbid.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- MusicBrainz release-group id for an album. albums.mbid holds the --- *release* id (Picard's musicbrainz_albumid: one edition), but Lidarr names --- albums by release group, so re-acquisition and request completion need --- this one. Not unique: several releases of one group can each be an album --- row. Filled by the scanner from musicbrainz_releasegroupid, or by the --- re-acquisition sweeper resolving the release through MusicBrainz. -ALTER TABLE albums ADD COLUMN release_group_mbid text; - -CREATE INDEX albums_release_group_mbid_idx ON albums (release_group_mbid) - WHERE release_group_mbid IS NOT NULL; diff --git a/internal/db/migrations/0071_reopen_false_reacquisition_completions.down.sql b/internal/db/migrations/0071_reopen_false_reacquisition_completions.down.sql deleted file mode 100644 index 03bb6852..00000000 --- a/internal/db/migrations/0071_reopen_false_reacquisition_completions.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- The reopened requests were never complete; the reconciler completes them --- again once their albums come back. Nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0071_reopen_false_reacquisition_completions.up.sql b/internal/db/migrations/0071_reopen_false_reacquisition_completions.up.sql deleted file mode 100644 index e7e18c49..00000000 --- a/internal/db/migrations/0071_reopen_false_reacquisition_completions.up.sql +++ /dev/null @@ -1,30 +0,0 @@ --- Before: the reconciler completed album and track requests as soon as the --- album had any track on disk. Re-acquisition targets albums with only SOME --- tracks missing, so those requests completed the moment Lidarr accepted the --- add, with nothing downloaded. --- --- Reopen every completed album/track request whose matched album does not meet --- the corrected test: a track --- that arrived after the request, or no track that was already missing at the --- request still missing. The reconciler then judges them again; the Lidarr add --- stays confirmed, so nothing is re-sent. Requests that genuinely completed --- meet the test and are left alone. -UPDATE lidarr_requests lr - SET status = 'approved', - completed_at = NULL, - matched_album_id = NULL, - matched_track_id = NULL, - updated_at = now() - WHERE lr.status = 'completed' - AND lr.kind IN ('album', 'track') - AND lr.matched_album_id IS NOT NULL - AND NOT EXISTS ( - SELECT 1 FROM tracks t - WHERE t.album_id = lr.matched_album_id - AND t.missing_since IS NULL - AND t.added_at > lr.requested_at) - AND EXISTS ( - SELECT 1 FROM tracks t - WHERE t.album_id = lr.matched_album_id - AND t.missing_since IS NOT NULL - AND t.missing_since < lr.requested_at); diff --git a/internal/db/migrations/0072_similarity_cache.down.sql b/internal/db/migrations/0072_similarity_cache.down.sql deleted file mode 100644 index fb3b01a0..00000000 --- a/internal/db/migrations/0072_similarity_cache.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS artist_similarity_fetches; -DROP TABLE IF EXISTS track_similarity_fetches; -DROP TABLE IF EXISTS listenbrainz_similar_recordings; diff --git a/internal/db/migrations/0072_similarity_cache.up.sql b/internal/db/migrations/0072_similarity_cache.up.sql deleted file mode 100644 index f11866f0..00000000 --- a/internal/db/migrations/0072_similarity_cache.up.sql +++ /dev/null @@ -1,43 +0,0 @@ --- Keep ListenBrainz's whole similar-recordings answer, and record every --- fetch, so the library match is made locally and can be made again. --- --- Before: the worker kept only the recordings already in the library (at most --- 20 of LB's 50) and threw the rest away. Two things followed: --- --- * A recording that reached the library later — a Lidarr import, or an MBID --- filled in by the AcoustID lookup — was not linked until its seed was --- fetched again. --- * A seed with no in-library match wrote nothing at all, and freshness was --- read from track_similarity, so that seed was never fresh. With the queue --- ordered by id, such seeds held its head and were re-asked every hour --- while the rest waited. --- --- The listenbrainz rows in track_similarity are now derived from this cache by --- ResolveListenBrainzTrackEdges. - -CREATE TABLE listenbrainz_similar_recordings ( - seed_track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - recording_mbid text NOT NULL, - score DOUBLE PRECISION NOT NULL, - PRIMARY KEY (seed_track_id, recording_mbid) -); - --- The resolve joins the cache to tracks by recording MBID. -CREATE INDEX listenbrainz_similar_recordings_mbid_idx - ON listenbrainz_similar_recordings (recording_mbid); - --- One row per seed that ListenBrainz has answered for, an empty answer --- included. The worker's queue reads this, not the edges. -CREATE TABLE track_similarity_fetches ( - track_id uuid PRIMARY KEY REFERENCES tracks(id) ON DELETE CASCADE, - fetched_at timestamptz NOT NULL DEFAULT now(), - returned integer NOT NULL -); - --- The same for artists. Their answer is already kept, in artist_similarity and --- artist_similarity_unmatched; this only stops an empty answer being re-asked. -CREATE TABLE artist_similarity_fetches ( - artist_id uuid PRIMARY KEY REFERENCES artists(id) ON DELETE CASCADE, - fetched_at timestamptz NOT NULL DEFAULT now(), - returned integer NOT NULL -); diff --git a/internal/db/migrations/0073_user_notifications.down.sql b/internal/db/migrations/0073_user_notifications.down.sql deleted file mode 100644 index df94a29d..00000000 --- a/internal/db/migrations/0073_user_notifications.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS user_notification_prefs; -DROP TABLE IF EXISTS user_notifications; diff --git a/internal/db/migrations/0073_user_notifications.up.sql b/internal/db/migrations/0073_user_notifications.up.sql deleted file mode 100644 index ea6fdf9e..00000000 --- a/internal/db/migrations/0073_user_notifications.up.sql +++ /dev/null @@ -1,74 +0,0 @@ --- A persistent, per-user notifications inbox. --- --- The event bus is fire-and-forget: a client that is not connected when a --- request completes, or when the scanner marks tracks missing, never hears of --- it. A row here is the durable record; the bus only nudges open clients to --- come and read it. --- --- `kind` is CHECK-gated. A new kind adds its value here, in the --- same migration as the code that produces it. The list is mirrored in --- internal/notifications/kinds.go, and both CHECKs below must agree with it. - -CREATE TABLE user_notifications ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - kind text NOT NULL CHECK (kind IN ( - 'request_approved', - 'request_rejected', - 'request_completed', - 'request_pending', - 'quarantine_flagged', - 'scan_failed', - 'tracks_missing', - 'duplicates_found', - 'playback_errors' - )), - payload jsonb NOT NULL DEFAULT '{}'::jsonb, - created_at timestamptz NOT NULL DEFAULT now(), - read_at timestamptz, - -- Burst-prone kinds share one key per user. While a row with that key is - -- unread, a new event updates it in place rather than adding another, so - -- fourteen missing tracks are one notification with a count. - coalesce_key text, - -- Stamped once the row has gone out in an email (or been judged not to - -- need one), so the digest never sends the same item twice. - emailed_at timestamptz -); - --- The inbox list, newest first. -CREATE INDEX user_notifications_user_created_idx - ON user_notifications (user_id, created_at DESC); - --- The unread badge, and the digest's selection of unread rows. -CREATE INDEX user_notifications_unread_idx - ON user_notifications (user_id, created_at DESC) - WHERE read_at IS NULL; - --- At most one unread row per coalesce key per user. The upsert in --- notifications.sql targets this index. -CREATE UNIQUE INDEX user_notifications_coalesce_idx - ON user_notifications (user_id, coalesce_key) - WHERE read_at IS NULL AND coalesce_key IS NOT NULL; - --- Per user, per kind: which channels a kind reaches. A missing row means the --- kind's defaults (internal/notifications/kinds.go), so nothing is seeded and --- a new kind needs no backfill. -CREATE TABLE user_notification_prefs ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - kind text NOT NULL CHECK (kind IN ( - 'request_approved', - 'request_rejected', - 'request_completed', - 'request_pending', - 'quarantine_flagged', - 'scan_failed', - 'tracks_missing', - 'duplicates_found', - 'playback_errors' - )), - inbox boolean NOT NULL, - phone boolean NOT NULL, - email boolean NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, kind) -); diff --git a/internal/db/migrations/0074_notification_email.down.sql b/internal/db/migrations/0074_notification_email.down.sql deleted file mode 100644 index e8c2d908..00000000 --- a/internal/db/migrations/0074_notification_email.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS user_notifications_email_pending_idx; -DROP TABLE IF EXISTS user_notification_email_state; -DROP TABLE IF EXISTS notification_email_settings; diff --git a/internal/db/migrations/0074_notification_email.up.sql b/internal/db/migrations/0074_notification_email.up.sql deleted file mode 100644 index 917fd02a..00000000 --- a/internal/db/migrations/0074_notification_email.up.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Notifications by email, grouped. Nothing is emailed per event. --- --- New music (request_completed) goes out as at most one summary a day, at a set --- hour in each user's own timezone. Everything else is batched: a batch opens --- at the first un-emailed item and one email goes out a window later, holding --- whatever accumulated. internal/notifications/digest.go is the one sender. - --- The two knobs, in admin Settings. Singleton in the style of --- fingerprint_settings (0061). -CREATE TABLE notification_email_settings ( - id boolean PRIMARY KEY DEFAULT true, - -- The local hour (0-23, in each user's timezone) the daily new-music - -- summary goes out. - summary_hour integer NOT NULL DEFAULT 9, - -- How long a batch stays open after its first item before it is sent. - batch_window_minutes integer NOT NULL DEFAULT 60, - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT notification_email_settings_singleton CHECK (id = true), - CONSTRAINT notification_email_settings_hour_range - CHECK (summary_hour >= 0 AND summary_hour <= 23), - CONSTRAINT notification_email_settings_window_range - CHECK (batch_window_minutes >= 15 AND batch_window_minutes <= 1440) -); -INSERT INTO notification_email_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; - --- Per user, per email group: where the digest stands. A missing row is a user --- who has never had a batch open or a summary sent. -CREATE TABLE user_notification_email_state ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - email_group text NOT NULL CHECK (email_group IN ('batch', 'summary')), - -- When the open batch started. Held here rather than read off the items, - -- because a coalesced item moves its created_at forward on every update - -- and would otherwise keep a batch from ever coming due. - batch_opened_at timestamptz, - -- The last email of this group the mailer accepted. A summary is due once - -- per local day, after the summary hour, if this is before it. - last_sent_at timestamptz, - -- A failed send backs off: nothing is tried for this group before - -- retry_after, and the gap doubles with each failure in a row. - failures integer NOT NULL DEFAULT 0, - retry_after timestamptz, - PRIMARY KEY (user_id, email_group) -); - --- The digest's selection: unread rows not yet emailed. -CREATE INDEX user_notifications_email_pending_idx - ON user_notifications (user_id, created_at) - WHERE read_at IS NULL AND emailed_at IS NULL; - --- Rows written before this migration were never judged for email. Treat them --- as already handled, so the first digest after the upgrade doesn't send a --- backlog nobody asked for. -UPDATE user_notifications SET emailed_at = now() WHERE emailed_at IS NULL; diff --git a/internal/db/migrations/0075_duplicate_resolve.down.sql b/internal/db/migrations/0075_duplicate_resolve.down.sql deleted file mode 100644 index 60372195..00000000 --- a/internal/db/migrations/0075_duplicate_resolve.down.sql +++ /dev/null @@ -1,17 +0,0 @@ -DELETE FROM user_notifications WHERE kind = 'duplicates_resolved'; -DELETE FROM user_notification_prefs WHERE kind = 'duplicates_resolved'; -ALTER TABLE user_notification_prefs DROP CONSTRAINT user_notification_prefs_kind_check; -ALTER TABLE user_notification_prefs ADD CONSTRAINT user_notification_prefs_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'playback_errors')); -ALTER TABLE user_notifications DROP CONSTRAINT user_notifications_kind_check; -ALTER TABLE user_notifications ADD CONSTRAINT user_notifications_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'playback_errors')); -ALTER TABLE fingerprint_settings DROP COLUMN IF EXISTS auto_resolve; -ALTER TABLE duplicate_group_members DROP COLUMN IF EXISTS lidarr_state; -ALTER TABLE duplicate_groups DROP COLUMN IF EXISTS resolved_automatically; -ALTER TABLE duplicate_groups DROP COLUMN IF EXISTS resolve_note; -ALTER TABLE duplicate_groups DROP COLUMN IF EXISTS class; diff --git a/internal/db/migrations/0075_duplicate_resolve.up.sql b/internal/db/migrations/0075_duplicate_resolve.up.sql deleted file mode 100644 index 95b958da..00000000 --- a/internal/db/migrations/0075_duplicate_resolve.up.sql +++ /dev/null @@ -1,56 +0,0 @@ --- 0075_duplicate_resolve.up.sql — duplicates resolve themselves. --- --- Before: the sweep (0059) proposed groups and every proposal waited for an --- admin. After: the resolver classifies each pending group and acts on the --- classes that are safe. What makes deletion safe is Lidarr's view of the file: --- Lidarr maps one file to each track of the release it monitors, so deleting a --- mapped file opens a hole it fills by downloading again. Only a copy Lidarr --- does not map may go. - --- What kind of duplicate a group is. NULL until the resolver has classified it. --- same_release every copy is on one album --- cross_release the same song on different releases (a single and its album) --- mismatch identical audio under different titles on different albums: --- a file imported as the wrong song --- review anything else: an admin decides --- A new value swaps this constraint in the same migration. -ALTER TABLE duplicate_groups ADD COLUMN class text; -ALTER TABLE duplicate_groups ADD CONSTRAINT duplicate_groups_class_check - CHECK (class IN ('same_release', 'cross_release', 'mismatch', 'review')); - --- Why the resolver left a group for an admin, in words the report shows --- ("Lidarr tracks every copy as its own track"). NULL when it had nothing to --- say. -ALTER TABLE duplicate_groups ADD COLUMN resolve_note text; - --- True when the resolver merged the group itself, so the report can tell its --- merges from an admin's. -ALTER TABLE duplicate_groups ADD COLUMN resolved_automatically boolean NOT NULL DEFAULT false; - --- Lidarr's view of each copy, as of the resolver's last pass: --- tracked Lidarr holds the file and it is not among its unmapped files --- unmapped Lidarr holds the file but maps it to no track: removing it opens --- no hole --- NULL when Lidarr was not consulted (disabled, or unreachable that pass). -ALTER TABLE duplicate_group_members ADD COLUMN lidarr_state text; -ALTER TABLE duplicate_group_members ADD CONSTRAINT duplicate_group_members_lidarr_state_check - CHECK (lidarr_state IN ('tracked', 'unmapped')); - --- An admin can turn the resolver off. On by default: duplicates are meant to --- resolve themselves. -ALTER TABLE fingerprint_settings ADD COLUMN auto_resolve boolean NOT NULL DEFAULT true; - --- The resolver tells admins what it did (the kind CHECKs of 0073 are swapped --- to carry the new value). Postgres named both from their columns. -ALTER TABLE user_notifications DROP CONSTRAINT user_notifications_kind_check; -ALTER TABLE user_notifications ADD CONSTRAINT user_notifications_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); -ALTER TABLE user_notification_prefs DROP CONSTRAINT user_notification_prefs_kind_check; -ALTER TABLE user_notification_prefs ADD CONSTRAINT user_notification_prefs_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); diff --git a/internal/db/migrations/0076_track_song_link.down.sql b/internal/db/migrations/0076_track_song_link.down.sql deleted file mode 100644 index f81c06f2..00000000 --- a/internal/db/migrations/0076_track_song_link.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS tracks_song_key_idx; -ALTER TABLE tracks DROP COLUMN IF EXISTS song_key; -ALTER TABLE tracks DROP COLUMN IF EXISTS song_id; diff --git a/internal/db/migrations/0076_track_song_link.up.sql b/internal/db/migrations/0076_track_song_link.up.sql deleted file mode 100644 index 94789e09..00000000 --- a/internal/db/migrations/0076_track_song_link.up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- 0076_track_song_link.up.sql — the same song on several releases counts as --- one song. --- --- A single and the album it came from each hold the song, and Lidarr keeps --- both: each fulfils its own release. Minstrel keeps both files and links --- them, so a like on one is a like on the song, and a mix or radio picks the --- song once rather than once per release. --- --- song_id is set only on a linked track, to the song_key the link chose. --- song_key is what everything reads: the track's own id until it is linked. --- No foreign key: the track whose id names a song may itself be merged away --- later, and the key still groups the copies left. -ALTER TABLE tracks ADD COLUMN song_id uuid; -ALTER TABLE tracks ADD COLUMN song_key uuid GENERATED ALWAYS AS (COALESCE(song_id, id)) STORED; -CREATE INDEX tracks_song_key_idx ON tracks (song_key); diff --git a/internal/db/migrations/0077_track_source_verdict.down.sql b/internal/db/migrations/0077_track_source_verdict.down.sql deleted file mode 100644 index 17b626c6..00000000 --- a/internal/db/migrations/0077_track_source_verdict.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS tracks_source_suspect_idx; -ALTER TABLE tracks DROP COLUMN IF EXISTS source_verdict_at; -ALTER TABLE tracks DROP COLUMN IF EXISTS source_verdict; diff --git a/internal/db/migrations/0077_track_source_verdict.up.sql b/internal/db/migrations/0077_track_source_verdict.up.sql deleted file mode 100644 index 529b5d3e..00000000 --- a/internal/db/migrations/0077_track_source_verdict.up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- 0077_track_source_verdict.up.sql — video rips are held back from mixes and --- radio until an admin says otherwise. --- --- A file whose name carries a video-rip marker ("(Official Video)", "[HD]") --- holds the audio of an upload, which can carry intros, skits or a --- different take. The duplicate resolver sets 'suspect' on such a present --- track each pass, and clears it when the name no longer matches. 'suspect' --- keeps the track out of radio and the system mixes; it still plays when --- chosen. 'fine' is an admin's "this one is fine" and is never --- overwritten by the resolver. -ALTER TABLE tracks ADD COLUMN source_verdict text - CONSTRAINT tracks_source_verdict_check CHECK (source_verdict IN ('suspect', 'fine')); -ALTER TABLE tracks ADD COLUMN source_verdict_at timestamptz; -CREATE INDEX tracks_source_suspect_idx ON tracks (id) WHERE source_verdict = 'suspect'; diff --git a/internal/db/migrations/0078_drop_duplicate_lidarr_state.down.sql b/internal/db/migrations/0078_drop_duplicate_lidarr_state.down.sql deleted file mode 100644 index b325605d..00000000 --- a/internal/db/migrations/0078_drop_duplicate_lidarr_state.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE duplicate_group_members ADD COLUMN lidarr_state text; -ALTER TABLE duplicate_group_members ADD CONSTRAINT duplicate_group_members_lidarr_state_check - CHECK (lidarr_state IN ('tracked', 'unmapped')); diff --git a/internal/db/migrations/0078_drop_duplicate_lidarr_state.up.sql b/internal/db/migrations/0078_drop_duplicate_lidarr_state.up.sql deleted file mode 100644 index 943423a1..00000000 --- a/internal/db/migrations/0078_drop_duplicate_lidarr_state.up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- 0078_drop_duplicate_lidarr_state.up.sql — the duplicate resolver works --- without Lidarr. --- --- 0075 recorded Lidarr's view of each duplicate copy (tracked or unmapped) --- because a copy Lidarr mapped could not be removed without Lidarr downloading --- it again. Lidarr is gone: Minstrel is the only program writing the library, --- so no copy is anyone else's to keep, and the column has nothing to say. -ALTER TABLE duplicate_group_members DROP CONSTRAINT IF EXISTS duplicate_group_members_lidarr_state_check; -ALTER TABLE duplicate_group_members DROP COLUMN IF EXISTS lidarr_state; diff --git a/internal/db/migrations/0079_acquisition_services.down.sql b/internal/db/migrations/0079_acquisition_services.down.sql deleted file mode 100644 index 49d5d65c..00000000 --- a/internal/db/migrations/0079_acquisition_services.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS acquisition_services; diff --git a/internal/db/migrations/0079_acquisition_services.up.sql b/internal/db/migrations/0079_acquisition_services.up.sql deleted file mode 100644 index b4487dac..00000000 --- a/internal/db/migrations/0079_acquisition_services.up.sql +++ /dev/null @@ -1,61 +0,0 @@ --- 0079_acquisition_services.up.sql — the indexers and download clients the --- admin adds in Admin → Integrations. --- --- Minstrel replaces Lidarr, so it searches and downloads itself. Nothing is --- seeded and nothing is copied from Lidarr: a connection is a row an admin --- adds, from a list of what Minstrel can speak: --- --- kind which list the row appears in: search (Indexers) or download --- (Download clients). --- protocol which client is built: prowlarr (its native /api/v1/search, --- because Prowlarr has no aggregate Torznab feed), torznab (any --- single feed), qbittorrent (the WebUI v2), exchange. --- --- FabledExchange is ONE row under Download clients with a switch per job: --- downloading, searching its DHT index, and describing a torrent's files and --- swarm before a grab. The serves_* switches mean something on an exchange --- row only; every other row does the one job its kind names. --- --- Secrets (api_key, password) are write-only: no query the API answers with --- returns them, only whether one is set. -CREATE TABLE acquisition_services ( - -- code is the stable identity: the protocol for the first of its kind, - -- then protocol-2, protocol-3. Legible in a log, never typed. - code text PRIMARY KEY, - kind text NOT NULL - CONSTRAINT acquisition_services_kind_check CHECK (kind IN ('search', 'download')), - protocol text NOT NULL - CONSTRAINT acquisition_services_protocol_check - CHECK (protocol IN ('prowlarr', 'torznab', 'qbittorrent', 'exchange')), - label text NOT NULL, - -- A new row is off: it has no address yet. - enabled boolean NOT NULL DEFAULT false, - -- The address as an admin's browser opens it. For a Torznab feed it - -- is the whole feed URL up to and including /api. - base_url text NOT NULL DEFAULT '', - api_key text NOT NULL DEFAULT '', - -- qBittorrent only. Both may be empty: a WebUI with auth bypassed for - -- local addresses takes neither. - username text NOT NULL DEFAULT '', - password text NOT NULL DEFAULT '', - -- Download clients: everything Minstrel adds is filed under it. - category text NOT NULL DEFAULT '', - timeout_ms integer NOT NULL DEFAULT 30000 - CONSTRAINT acquisition_services_timeout_check CHECK (timeout_ms BETWEEN 1000 AND 300000), - serves_search boolean NOT NULL DEFAULT true, - serves_downloads boolean NOT NULL DEFAULT true, - serves_enrichment boolean NOT NULL DEFAULT true, - -- One downloads folder, two names: where Minstrel has it mounted, and - -- where the client sees it (empty = the same path, nothing translated). - local_path text NOT NULL DEFAULT '/downloads' - CONSTRAINT acquisition_services_local_path_check CHECK (local_path LIKE '/%'), - remote_path text NOT NULL DEFAULT '' - CONSTRAINT acquisition_services_remote_path_check CHECK (remote_path = '' OR remote_path LIKE '/%'), - -- The most searches the schedule sends this source an hour; 0 = unpaced. - -- Prowlarr's indexers answer 429 when asked too often; an Exchange - -- searches its own database and starts unpaced. - searches_per_hour integer NOT NULL DEFAULT 120 - CONSTRAINT acquisition_services_searches_per_hour_check CHECK (searches_per_hour BETWEEN 0 AND 3600), - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0080_release_catalogue.down.sql b/internal/db/migrations/0080_release_catalogue.down.sql deleted file mode 100644 index bb9e6ac3..00000000 --- a/internal/db/migrations/0080_release_catalogue.down.sql +++ /dev/null @@ -1,5 +0,0 @@ -DROP TABLE IF EXISTS mb_release_tracks; -DROP TABLE IF EXISTS mb_releases; -DROP TABLE IF EXISTS mb_artist_release_groups; -DROP TABLE IF EXISTS mb_release_groups; -DROP TABLE IF EXISTS mb_artists; diff --git a/internal/db/migrations/0080_release_catalogue.up.sql b/internal/db/migrations/0080_release_catalogue.up.sql deleted file mode 100644 index 88e3086c..00000000 --- a/internal/db/migrations/0080_release_catalogue.up.sql +++ /dev/null @@ -1,86 +0,0 @@ --- 0080_release_catalogue.up.sql — Minstrel's own copy of what artists have --- released, read from MusicBrainz. --- --- With Lidarr gone, the wanted list, search and import need to know an --- artist's discography and each release's track list. MusicBrainz allows one --- request a second, so what has been read is kept here and refreshed on a --- schedule rather than asked again for every page. --- --- mb_artists artists the catalogue has been asked about. --- mb_release_groups what a person calls an album (Lidarr's albums --- were release groups too), with MusicBrainz's --- primary and secondary types. --- mb_artist_release_groups who is credited on each group: a collaboration --- belongs to every credited artist's discography. --- mb_releases the editions of a group, read when something --- needs a track list. --- mb_release_tracks each release's track list. --- --- Dates stay as MusicBrainz's partial-date text ("1997", "1997-05", --- "1997-05-21"): most early releases have only a year. - -CREATE TABLE mb_artists ( - mbid text PRIMARY KEY, - name text NOT NULL, - sort_name text NOT NULL DEFAULT '', - disambiguation text NOT NULL DEFAULT '', - artist_type text NOT NULL DEFAULT '', - country text NOT NULL DEFAULT '', - -- When the discography was last read in full; NULL means never. - discography_refreshed_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX mb_artists_refresh_idx ON mb_artists (discography_refreshed_at NULLS FIRST); - -CREATE TABLE mb_release_groups ( - mbid text PRIMARY KEY, - title text NOT NULL, - primary_type text NOT NULL DEFAULT '', - secondary_types text[] NOT NULL DEFAULT '{}', - first_release_date text NOT NULL DEFAULT '', - artist_credit text NOT NULL DEFAULT '', - -- When the releases and their track lists were last read; NULL means never. - releases_refreshed_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE TABLE mb_artist_release_groups ( - artist_mbid text NOT NULL REFERENCES mb_artists (mbid) ON DELETE CASCADE, - release_group_mbid text NOT NULL REFERENCES mb_release_groups (mbid) ON DELETE CASCADE, - PRIMARY KEY (artist_mbid, release_group_mbid) -); - -CREATE INDEX mb_artist_release_groups_group_idx ON mb_artist_release_groups (release_group_mbid); - -CREATE TABLE mb_releases ( - mbid text PRIMARY KEY, - release_group_mbid text NOT NULL REFERENCES mb_release_groups (mbid) ON DELETE CASCADE, - title text NOT NULL, - status text NOT NULL DEFAULT '', - release_date text NOT NULL DEFAULT '', - country text NOT NULL DEFAULT '', - disambiguation text NOT NULL DEFAULT '', - formats text NOT NULL DEFAULT '', - track_count integer NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX mb_releases_group_idx ON mb_releases (release_group_mbid); - -CREATE TABLE mb_release_tracks ( - release_mbid text NOT NULL REFERENCES mb_releases (mbid) ON DELETE CASCADE, - medium_position integer NOT NULL, - position integer NOT NULL, - medium_format text NOT NULL DEFAULT '', - number text NOT NULL DEFAULT '', - title text NOT NULL, - length_ms integer NOT NULL DEFAULT 0, - recording_mbid text NOT NULL DEFAULT '', - PRIMARY KEY (release_mbid, medium_position, position) -); - -CREATE INDEX mb_release_tracks_recording_idx ON mb_release_tracks (recording_mbid) - WHERE recording_mbid <> ''; diff --git a/internal/db/migrations/0081_wanted.down.sql b/internal/db/migrations/0081_wanted.down.sql deleted file mode 100644 index 4087ae4d..00000000 --- a/internal/db/migrations/0081_wanted.down.sql +++ /dev/null @@ -1,38 +0,0 @@ -ALTER TABLE reacquisition_settings - ADD COLUMN backoff_base_hours int NOT NULL DEFAULT 6, - ADD COLUMN backoff_max_hours int NOT NULL DEFAULT 168, - ADD COLUMN max_attempts int NOT NULL DEFAULT 3, - ADD COLUMN auto_approve boolean NOT NULL DEFAULT true; - -ALTER INDEX requests_user_id_idx RENAME TO lidarr_requests_user_id_idx; -ALTER INDEX requests_status_idx RENAME TO lidarr_requests_status_idx; -ALTER INDEX requests_artist_mbid_idx RENAME TO lidarr_requests_artist_mbid_idx; -ALTER INDEX requests_album_mbid_idx RENAME TO lidarr_requests_album_mbid_idx; -ALTER TABLE requests ADD COLUMN lidarr_add_confirmed_at timestamptz; -ALTER TABLE requests ADD COLUMN root_folder_path text; -ALTER TABLE requests ADD COLUMN quality_profile_id int; -ALTER TABLE requests RENAME COLUMN track_mbid TO lidarr_track_mbid; -ALTER TABLE requests RENAME COLUMN album_mbid TO lidarr_album_mbid; -ALTER TABLE requests RENAME COLUMN artist_mbid TO lidarr_artist_mbid; -ALTER TYPE request_kind RENAME TO lidarr_request_kind; -ALTER TYPE request_status RENAME TO lidarr_request_status; -ALTER TABLE requests RENAME TO lidarr_requests; - -CREATE TABLE missing_reacquisitions ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - attempts int NOT NULL DEFAULT 0, - last_attempt_at timestamptz, - last_request_id uuid REFERENCES lidarr_requests (id) ON DELETE SET NULL, - gave_up_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT missing_reacquisitions_attempts_nonneg CHECK (attempts >= 0) -); -CREATE INDEX missing_reacquisitions_due_idx - ON missing_reacquisitions (last_attempt_at NULLS FIRST) - WHERE gave_up_at IS NULL; - -DROP TABLE wants; -DROP TABLE follow_seen_groups; -DROP TABLE follows; -DROP TABLE release_type_profiles; diff --git a/internal/db/migrations/0081_wanted.up.sql b/internal/db/migrations/0081_wanted.up.sql deleted file mode 100644 index d358ab3d..00000000 --- a/internal/db/migrations/0081_wanted.up.sql +++ /dev/null @@ -1,165 +0,0 @@ --- 0081_wanted.up.sql — the wanted list. --- --- With Lidarr gone, Minstrel keeps its own record of what it is looking for: --- --- release_type_profiles which kinds of release a follow wants: primary --- types (Album, EP, Single…) and the secondary types --- allowed (Live, Compilation, Remix…). An empty --- secondary list means studio releases only, which --- is how live recordings are left out. --- follows artists whose new releases are wanted, each on a --- profile. --- follow_seen_groups release groups a follow has already judged, so --- each is judged once. --- wants release groups wanted: a request, a followed --- artist's new release, or an album whose files went --- missing. A want is held once the library has a --- full copy (internal/wanted). --- --- lidarr_requests becomes requests with no Lidarr columns: approving a request --- now records a want or a follow instead of sending an add to Lidarr. The --- missing-file sweeper's attempt bookkeeping goes too; retrying belongs to the --- search schedule, which works per want. - -CREATE TABLE release_type_profiles ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - name text NOT NULL UNIQUE, - primary_types text[] NOT NULL, - secondary_types text[] NOT NULL DEFAULT '{}', - is_default boolean NOT NULL DEFAULT false, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT release_type_profiles_primary_nonempty CHECK (cardinality(primary_types) > 0) -); - --- At most one default; the service keeps exactly one by moving it. -CREATE UNIQUE INDEX release_type_profiles_one_default - ON release_type_profiles (is_default) WHERE is_default; - --- Lidarr's "Standard" metadata profile, which followed artists used: albums, --- EPs and singles, studio releases only. -INSERT INTO release_type_profiles (name, primary_types, secondary_types, is_default) -VALUES ('Standard', ARRAY['Album', 'EP', 'Single'], '{}', true); - -CREATE TABLE follows ( - artist_mbid text PRIMARY KEY, - artist_name text NOT NULL, - -- RESTRICT: a profile in use cannot be deleted out from under a follow. - profile_id uuid NOT NULL REFERENCES release_type_profiles (id) ON DELETE RESTRICT, - followed_by uuid REFERENCES users (id) ON DELETE SET NULL, - followed_at timestamptz NOT NULL DEFAULT now(), - -- When the first discography read marked everything then listed as seen. - -- NULL until then: a follow wants only what appears after it. - baseline_at timestamptz, - -- Whether the baseline also wants what the artist had already released - -- that the profile passes and the library lacks: an approved artist - -- request, or an admin ticking "also want…". Cleared once applied. - want_existing boolean NOT NULL DEFAULT false, - -- The discography read this follow last applied. - checked_at timestamptz, - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX follows_profile_idx ON follows (profile_id); - -CREATE TABLE follow_seen_groups ( - artist_mbid text NOT NULL REFERENCES follows (artist_mbid) ON DELETE CASCADE, - release_group_mbid text NOT NULL, - seen_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (artist_mbid, release_group_mbid) -); - -CREATE TABLE wants ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - release_group_mbid text NOT NULL UNIQUE, - artist_mbid text NOT NULL, - artist_name text NOT NULL, - title text NOT NULL, - primary_type text NOT NULL DEFAULT '', - first_release_date text NOT NULL DEFAULT '', - reason text NOT NULL - CONSTRAINT wants_reason_check CHECK (reason IN ('request', 'follow', 'missing')), - -- The library album this want is about (a missing want), or the one that - -- answered it. - album_id uuid REFERENCES albums (id) ON DELETE SET NULL, - created_by uuid REFERENCES users (id) ON DELETE SET NULL, - -- When it was last wanted: set again when a held want is reopened, so - -- "arrived since it was wanted" measures from the reopening. - wanted_at timestamptz NOT NULL DEFAULT now(), - fulfilled_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX wants_open_idx ON wants (wanted_at) WHERE fulfilled_at IS NULL; -CREATE INDEX wants_artist_idx ON wants (artist_mbid); - --- Requests lose Lidarr. -DROP TABLE missing_reacquisitions; - -ALTER TABLE lidarr_requests RENAME TO requests; -ALTER TYPE lidarr_request_status RENAME TO request_status; -ALTER TYPE lidarr_request_kind RENAME TO request_kind; -ALTER TABLE requests RENAME COLUMN lidarr_artist_mbid TO artist_mbid; -ALTER TABLE requests RENAME COLUMN lidarr_album_mbid TO album_mbid; -ALTER TABLE requests RENAME COLUMN lidarr_track_mbid TO track_mbid; -ALTER TABLE requests DROP COLUMN quality_profile_id; -ALTER TABLE requests DROP COLUMN root_folder_path; -ALTER TABLE requests DROP COLUMN lidarr_add_confirmed_at; -ALTER INDEX lidarr_requests_user_id_idx RENAME TO requests_user_id_idx; -ALTER INDEX lidarr_requests_status_idx RENAME TO requests_status_idx; -ALTER INDEX lidarr_requests_artist_mbid_idx RENAME TO requests_artist_mbid_idx; -ALTER INDEX lidarr_requests_album_mbid_idx RENAME TO requests_album_mbid_idx; - --- Older requests may name albums by release id. A want is keyed by --- release group, so repoint every request the library can translate. -UPDATE requests r - SET album_mbid = a.release_group_mbid, - updated_at = now() - FROM albums a - WHERE a.mbid = r.album_mbid - AND a.release_group_mbid IS NOT NULL - AND a.release_group_mbid <> r.album_mbid; - --- Approved album and track requests still waiting become wants, judged by --- the same test as any other (internal/wanted). -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, created_by, wanted_at) -SELECT DISTINCT ON (r.album_mbid) - r.album_mbid, r.artist_mbid, r.artist_name, COALESCE(r.album_title, ''), 'request', r.user_id, r.requested_at - FROM requests r - WHERE r.status = 'approved' - AND r.kind IN ('album', 'track') - AND r.album_mbid IS NOT NULL - ORDER BY r.album_mbid, r.requested_at -ON CONFLICT (release_group_mbid) DO NOTHING; - --- The library's album artists start out followed on the default profile: the --- artists already in the library are the wanted artists. Various Artists and --- MusicBrainz's bracketed placeholders ([unknown], [anonymous]…) are not --- artists anyone follows. -INSERT INTO follows (artist_mbid, artist_name, profile_id) -SELECT ar.mbid, ar.name, p.id - FROM artists ar - CROSS JOIN (SELECT id FROM release_type_profiles WHERE is_default) p - WHERE ar.mbid IS NOT NULL AND ar.mbid <> '' - AND ar.mbid <> '89ad4ac3-39f7-470e-963a-56509c546377' - AND ar.name NOT LIKE '[%]' - AND EXISTS (SELECT 1 FROM albums al WHERE al.artist_id = ar.id) -ON CONFLICT (artist_mbid) DO NOTHING; - --- An approved artist request was an artist added to Lidarr: it is followed. -INSERT INTO follows (artist_mbid, artist_name, profile_id, followed_by) -SELECT DISTINCT ON (r.artist_mbid) r.artist_mbid, r.artist_name, p.id, r.decided_by - FROM requests r - CROSS JOIN (SELECT id FROM release_type_profiles WHERE is_default) p - WHERE r.status = 'approved' AND r.kind = 'artist' - ORDER BY r.artist_mbid, r.requested_at -ON CONFLICT (artist_mbid) DO NOTHING; - --- The sweeper now only records a want; how often to look again is the --- search schedule's business. -ALTER TABLE reacquisition_settings - DROP COLUMN backoff_base_hours, - DROP COLUMN backoff_max_hours, - DROP COLUMN max_attempts, - DROP COLUMN auto_approve; diff --git a/internal/db/migrations/0082_search_and_grab.down.sql b/internal/db/migrations/0082_search_and_grab.down.sql deleted file mode 100644 index 630d58e6..00000000 --- a/internal/db/migrations/0082_search_and_grab.down.sql +++ /dev/null @@ -1,12 +0,0 @@ -DROP TABLE release_blocks; -DROP TABLE grabs; -DROP TABLE want_candidates; -DROP INDEX wants_search_due_idx; -ALTER TABLE wants - DROP COLUMN searched_at, - DROP COLUMN search_outcome, - DROP COLUMN search_considered, - DROP COLUMN best_release, - DROP COLUMN best_verdict, - DROP COLUMN search_error; -DROP TABLE acquisition_settings; diff --git a/internal/db/migrations/0082_search_and_grab.up.sql b/internal/db/migrations/0082_search_and_grab.up.sql deleted file mode 100644 index 962586a1..00000000 --- a/internal/db/migrations/0082_search_and_grab.up.sql +++ /dev/null @@ -1,101 +0,0 @@ --- 0082_search_and_grab.up.sql — searching for wants and grabbing releases. --- --- acquisition_settings one row: whether the schedule takes the best release --- by itself, how often a want is searched again, which --- quality tiers are taken, and the last pass's report. --- wants (columns) when each want was last searched and what came of it. --- want_candidates every release the last search found for a want, with --- its verdict and the reasons behind it. --- grabs downloads started for wants; at most one live per want. --- release_blocks releases never to take again, by infohash. - -CREATE TABLE acquisition_settings ( - id boolean PRIMARY KEY DEFAULT true CONSTRAINT acquisition_settings_one_row CHECK (id), - auto_grab boolean NOT NULL DEFAULT true, - -- 0 switches the schedule off. - search_interval_hours integer NOT NULL DEFAULT 24 - CONSTRAINT acquisition_settings_interval_check CHECK (search_interval_hours BETWEEN 0 AND 720), - -- As Lidarr's "Any" profile: trash lossy to lossless; unknown off. - allowed_qualities text[] NOT NULL DEFAULT ARRAY['lossless_hires', 'lossless', 'lossy_high', - 'lossy_standard', 'lossy_low', 'lossy_poor', 'lossy_trash'], - last_pass_at timestamptz, - last_pass jsonb NOT NULL DEFAULT '{}', - updated_at timestamptz NOT NULL DEFAULT now() -); - -INSERT INTO acquisition_settings DEFAULT VALUES; - -ALTER TABLE wants - ADD COLUMN searched_at timestamptz, - ADD COLUMN search_outcome text NOT NULL DEFAULT '' - CONSTRAINT wants_search_outcome_check CHECK (search_outcome IN ('', 'grabbed', 'waiting', 'nothing', 'error')), - ADD COLUMN search_considered integer NOT NULL DEFAULT 0, - ADD COLUMN best_release text NOT NULL DEFAULT '', - ADD COLUMN best_verdict text NOT NULL DEFAULT '', - ADD COLUMN search_error text NOT NULL DEFAULT ''; - -CREATE INDEX wants_search_due_idx ON wants (searched_at NULLS FIRST) WHERE fulfilled_at IS NULL; - -CREATE TABLE want_candidates ( - want_id uuid NOT NULL REFERENCES wants (id) ON DELETE CASCADE, - -- The infohash, or the name when the source gave none. - key text NOT NULL, - name text NOT NULL, - info_hash text NOT NULL DEFAULT '', - indexer text NOT NULL DEFAULT '', - source text NOT NULL DEFAULT '', - size_bytes bigint NOT NULL DEFAULT 0, - seeders integer NOT NULL DEFAULT 0, - files_count integer NOT NULL DEFAULT 0, - format text NOT NULL DEFAULT '', - quality text NOT NULL DEFAULT '', - year integer NOT NULL DEFAULT 0, - verdict text NOT NULL - CONSTRAINT want_candidates_verdict_check CHECK (verdict IN ('grab', 'review', 'refused', 'rejected', 'blocked')), - reason text NOT NULL DEFAULT '', - reasons jsonb NOT NULL DEFAULT '[]', - folded_from text[] NOT NULL DEFAULT '{}', - -- Position in the search's order, best first. - rank integer NOT NULL DEFAULT 0, - searched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (want_id, key) -); - -CREATE INDEX want_candidates_info_hash_idx ON want_candidates (info_hash) WHERE info_hash <> ''; - -CREATE TABLE grabs ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - want_id uuid REFERENCES wants (id) ON DELETE SET NULL, - info_hash text NOT NULL DEFAULT '', - name text NOT NULL, - key text NOT NULL, - indexer text NOT NULL DEFAULT '', - source text NOT NULL DEFAULT '', - -- The acquisition_services row of the download client it went to. - client text NOT NULL, - save_path text NOT NULL, - quality text NOT NULL DEFAULT '', - origin text NOT NULL CONSTRAINT grabs_origin_check CHECK (origin IN ('schedule', 'operator')), - forced boolean NOT NULL DEFAULT false, - grabbed_by uuid REFERENCES users (id) ON DELETE SET NULL, - grabbed_at timestamptz NOT NULL DEFAULT now(), - ended_at timestamptz, - end_reason text NOT NULL DEFAULT '' - CONSTRAINT grabs_end_reason_check CHECK (end_reason IN ('', 'superseded')), - end_detail text NOT NULL DEFAULT '' -); - --- One live grab per want; the service decides which, this is the backstop. -CREATE UNIQUE INDEX grabs_one_live_per_want ON grabs (want_id) WHERE ended_at IS NULL AND want_id IS NOT NULL; -CREATE INDEX grabs_info_hash_idx ON grabs (info_hash) WHERE info_hash <> ''; - -CREATE TABLE release_blocks ( - info_hash text PRIMARY KEY, - name text NOT NULL DEFAULT '', - -- operator: "never this one"; files: its .torrent held the wrong thing. - reason text NOT NULL CONSTRAINT release_blocks_reason_check CHECK (reason IN ('operator', 'files')), - detail text NOT NULL DEFAULT '', - want_id uuid REFERENCES wants (id) ON DELETE SET NULL, - blocked_by uuid REFERENCES users (id) ON DELETE SET NULL, - blocked_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0083_import.down.sql b/internal/db/migrations/0083_import.down.sql deleted file mode 100644 index a7677dcb..00000000 --- a/internal/db/migrations/0083_import.down.sql +++ /dev/null @@ -1,24 +0,0 @@ -ALTER TABLE acquisition_settings DROP COLUMN import_root; - -DELETE FROM release_blocks WHERE reason = 'import'; -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files')); - -DROP INDEX grabs_live_idx; - -UPDATE grabs SET end_reason = 'superseded' WHERE end_reason IN ('imported', 'refused', 'held'); -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check CHECK (end_reason IN ('', 'superseded')); - -ALTER TABLE grabs - DROP COLUMN progress, - DROP COLUMN import_state, - DROP COLUMN import_reason, - DROP COLUMN import_detail, - DROP COLUMN import_forced, - DROP COLUMN import_attempts, - DROP COLUMN import_updated_at, - DROP COLUMN imported_at, - DROP COLUMN imported_files, - DROP COLUMN destination; diff --git a/internal/db/migrations/0083_import.up.sql b/internal/db/migrations/0083_import.up.sql deleted file mode 100644 index 0cf4d5bb..00000000 --- a/internal/db/migrations/0083_import.up.sql +++ /dev/null @@ -1,37 +0,0 @@ --- Import with verification: a finished download is checked --- against the album it was grabbed for before anything reaches the library. --- --- grabs (columns) how far the download has got, and what the import --- made of it: the verdict, its reason and evidence, --- where the files went. --- grabs.end_reason a grab also ends by being imported, refused, or --- found to be an album already held. --- release_blocks.reason import: the files were not the album. --- acquisition_settings which library folder new music is filed into --- ('' = the first scan path). -ALTER TABLE grabs - ADD COLUMN progress real NOT NULL DEFAULT 0, - ADD COLUMN import_state text NOT NULL DEFAULT '' - CONSTRAINT grabs_import_state_check CHECK (import_state IN - ('', 'downloading', 'waiting', 'importing', 'imported', 'refused', 'review', 'held', 'failed')), - ADD COLUMN import_reason text NOT NULL DEFAULT '', - ADD COLUMN import_detail jsonb NOT NULL DEFAULT '{}', - -- A person said "import anyway" to a download the check held for them. - ADD COLUMN import_forced boolean NOT NULL DEFAULT false, - ADD COLUMN import_attempts integer NOT NULL DEFAULT 0, - ADD COLUMN import_updated_at timestamptz, - ADD COLUMN imported_at timestamptz, - ADD COLUMN imported_files integer NOT NULL DEFAULT 0, - ADD COLUMN destination text NOT NULL DEFAULT ''; - -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check - CHECK (end_reason IN ('', 'superseded', 'imported', 'refused', 'held')); - -CREATE INDEX grabs_live_idx ON grabs (grabbed_at) WHERE ended_at IS NULL; - -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import')); - -ALTER TABLE acquisition_settings ADD COLUMN import_root text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0084_download_lifecycle.down.sql b/internal/db/migrations/0084_download_lifecycle.down.sql deleted file mode 100644 index 9e00a4d5..00000000 --- a/internal/db/migrations/0084_download_lifecycle.down.sql +++ /dev/null @@ -1,23 +0,0 @@ -ALTER TABLE acquisition_settings - DROP COLUMN seed_ratio, - DROP COLUMN seed_days, - DROP COLUMN stall_hours; - -ALTER TABLE release_blocks DROP COLUMN expires_at; -DELETE FROM release_blocks WHERE reason = 'stalled'; -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import')); - -DROP INDEX grabs_seeding_idx; -ALTER TABLE grabs - DROP COLUMN seeding, - DROP COLUMN ratio, - DROP COLUMN seed_released_at; - -UPDATE grabs SET end_reason = 'superseded' WHERE end_reason IN ('stalled', 'failed', 'abandoned', 'gone'); -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check - CHECK (end_reason IN ('', 'superseded', 'imported', 'refused', 'held')); - -DROP TABLE download_interventions; diff --git a/internal/db/migrations/0084_download_lifecycle.up.sql b/internal/db/migrations/0084_download_lifecycle.up.sql deleted file mode 100644 index eedda40a..00000000 --- a/internal/db/migrations/0084_download_lifecycle.up.sql +++ /dev/null @@ -1,89 +0,0 @@ --- Download lifecycle: a download that stalls or fails is given up and its album --- searched again; an imported download seeds, then is removed. --- --- download_interventions what was seen wrong with a download or a client, --- what Minstrel did about it, and whether it --- cleared. One open row per (client, download, --- condition), updated in place. --- grabs (columns) a grab also ends by being given up (stalled, --- failed), set aside by a person, or leaving the --- client; an imported one records its seeding. --- release_blocks a release given up on is held back for a while, --- not for ever: expires_at. --- acquisition_settings how long to seed, and how long a download may sit --- with nobody sharing it. -CREATE TABLE download_interventions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - -- The acquisition_services code of the download client. - client text NOT NULL, - -- The torrent, or '' for a condition of the client itself. - info_hash text NOT NULL DEFAULT '', - grab_id uuid REFERENCES grabs (id) ON DELETE SET NULL, - name text NOT NULL DEFAULT '', - -- no_peers nobody is sharing an unfinished download. - -- no_metadata still fetching the torrent's file list. - -- client_error the client gave up on it, in its own words. - -- client_unreachable the client does not answer, or its engine is down. - -- gone the client no longer lists a running download. - -- not_removed given up on, and the client would not remove it. - trigger text NOT NULL CONSTRAINT download_interventions_trigger_check CHECK (trigger IN ( - 'no_peers', 'no_metadata', 'client_error', 'client_unreachable', 'gone', 'not_removed')), - -- escalated seen and shown; nothing done yet. - -- retried asked the trackers again and re-read the files. - -- given_up the download was removed and its album searched again. - -- removed a download left behind was removed. - action text NOT NULL DEFAULT 'escalated' - CONSTRAINT download_interventions_action_check CHECK (action IN ('escalated', 'retried', 'given_up', 'removed')), - outcome text NOT NULL DEFAULT 'open' - CONSTRAINT download_interventions_outcome_check CHECK (outcome IN ('open', 'resolved')), - detail text NOT NULL DEFAULT '', - -- How many passes have seen it, and how many times Minstrel acted on it. - -- The second is the retry ladder's rung, kept here so a restart does not - -- hand a stuck download fresh retries. - observations integer NOT NULL DEFAULT 1, - remediations integer NOT NULL DEFAULT 0, - first_seen timestamptz NOT NULL DEFAULT now(), - last_seen timestamptz NOT NULL DEFAULT now(), - settled_at timestamptz, - CONSTRAINT download_interventions_settled_together CHECK ((outcome = 'open') = (settled_at IS NULL)) -); - --- One open row per condition: a pass that sees it again lands on the same row. -CREATE UNIQUE INDEX download_interventions_one_open - ON download_interventions (client, info_hash, trigger) WHERE outcome = 'open'; -CREATE INDEX download_interventions_grab_idx ON download_interventions (grab_id) WHERE grab_id IS NOT NULL; - -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check - CHECK (end_reason IN ('', 'superseded', 'imported', 'refused', 'held', 'stalled', 'failed', 'abandoned', 'gone')); - --- An imported download goes on sharing (the files were copied) until its --- ratio reaches the setting or its time is up; seed_released_at is when it --- was removed, or found gone. -ALTER TABLE grabs - ADD COLUMN seeding boolean NOT NULL DEFAULT false, - ADD COLUMN ratio real NOT NULL DEFAULT 0, - ADD COLUMN seed_released_at timestamptz; - -CREATE INDEX grabs_seeding_idx ON grabs (imported_at) WHERE seeding AND seed_released_at IS NULL; - --- stalled: given up on because it would not finish; held back until --- expires_at. NULL is for good. -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import', 'stalled')); -ALTER TABLE release_blocks ADD COLUMN expires_at timestamptz; - --- FL's rulings: seed to ratio 2.0 or for 14 days at most; a download nobody --- has shared for 6 hours is retried, then given up. --- seed_ratio 0 the download is removed once imported. --- seed_days 0 no time limit: only the ratio ends it. --- stall_hours 0 never give up on a download for want of peers (a failed --- one is still given up). -ALTER TABLE acquisition_settings - ADD COLUMN seed_ratio real NOT NULL DEFAULT 2.0 - CONSTRAINT acquisition_settings_seed_ratio_check CHECK (seed_ratio BETWEEN 0 AND 100), - ADD COLUMN seed_days integer NOT NULL DEFAULT 14 - CONSTRAINT acquisition_settings_seed_days_check CHECK (seed_days BETWEEN 0 AND 365), - ADD COLUMN stall_hours integer NOT NULL DEFAULT 6 - CONSTRAINT acquisition_settings_stall_hours_check CHECK (stall_hours BETWEEN 0 AND 720); diff --git a/internal/db/migrations/0085_library_wants.down.sql b/internal/db/migrations/0085_library_wants.down.sql deleted file mode 100644 index 3fe34736..00000000 --- a/internal/db/migrations/0085_library_wants.down.sql +++ /dev/null @@ -1,8 +0,0 @@ -ALTER TABLE acquisition_settings - DROP COLUMN library_listing_started_at, - DROP COLUMN library_listed_at, - DROP COLUMN library_unlisted; - -DELETE FROM wants WHERE reason = 'library'; -ALTER TABLE wants DROP CONSTRAINT wants_reason_check; -ALTER TABLE wants ADD CONSTRAINT wants_reason_check CHECK (reason IN ('request', 'follow', 'missing')); diff --git a/internal/db/migrations/0085_library_wants.up.sql b/internal/db/migrations/0085_library_wants.up.sql deleted file mode 100644 index 9f7b87ce..00000000 --- a/internal/db/migrations/0085_library_wants.up.sql +++ /dev/null @@ -1,23 +0,0 @@ --- The library's albums go on the wanted list as held, once. After that the list --- is the truth: an album taken off it stays off, and one dropped into the --- library folder by hand is not added. Re-acquisition fetches back only albums --- on the list. --- --- wants.reason library: on the list because the library --- held it when the list began. --- acquisition_settings when the one-time listing began (its cutoff: --- albums added later are not listed), when it --- finished, and how many albums it could not --- list because nothing names them to --- MusicBrainz. --- --- The listing itself runs in the wanted worker after boot, not here: it may --- have to ask MusicBrainz for each album's release group. -ALTER TABLE wants DROP CONSTRAINT wants_reason_check; -ALTER TABLE wants ADD CONSTRAINT wants_reason_check - CHECK (reason IN ('request', 'follow', 'missing', 'library')); - -ALTER TABLE acquisition_settings - ADD COLUMN library_listing_started_at timestamptz, - ADD COLUMN library_listed_at timestamptz, - ADD COLUMN library_unlisted integer NOT NULL DEFAULT 0; diff --git a/internal/db/migrations/0086_library_album_matches.down.sql b/internal/db/migrations/0086_library_album_matches.down.sql deleted file mode 100644 index b61ff4fa..00000000 --- a/internal/db/migrations/0086_library_album_matches.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE library_album_matches; diff --git a/internal/db/migrations/0086_library_album_matches.up.sql b/internal/db/migrations/0086_library_album_matches.up.sql deleted file mode 100644 index fd7986da..00000000 --- a/internal/db/migrations/0086_library_album_matches.up.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Every library album is matched to MusicBrainz before it goes on the list, so --- its metadata comes from MusicBrainz. The listing in 0085 took only albums --- whose tags already named their release group and artist; the rest are now --- matched by the release their tags name, the artist's discography, or a --- search, and checked against their own tracks. --- --- library_album_matches one row per album the listing has decided: --- listed (with how it was matched) or unmatched --- (with why). It is the record that the listing --- saw the album, so an album taken off the list --- is never listed again. -CREATE TABLE library_album_matches ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - outcome text NOT NULL - CONSTRAINT library_album_matches_outcome_check CHECK (outcome IN ('listed', 'unmatched')), - -- tags its tags named the release group. - -- release its tags named a release; MusicBrainz named the group. - -- discography its title is one of the artist's release groups. - -- search MusicBrainz's search found it by artist and title. - method text NOT NULL DEFAULT '' - CONSTRAINT library_album_matches_method_check CHECK (method IN ('', 'tags', 'release', 'discography', 'search')), - release_group_mbid text NOT NULL DEFAULT '', - detail text NOT NULL DEFAULT '', - decided_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX library_album_matches_unmatched_idx ON library_album_matches (decided_at) WHERE outcome = 'unmatched'; - --- The albums 0085's listing already took, by its own test, are decided: --- one taken off the list since stays off. -INSERT INTO library_album_matches (album_id, outcome, method, release_group_mbid) -SELECT a.id, 'listed', 'tags', a.release_group_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - JOIN acquisition_settings s ON s.id = true - WHERE s.library_listing_started_at IS NOT NULL - AND a.created_at <= s.library_listing_started_at - AND a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> '' - AND ar.mbid IS NOT NULL AND ar.mbid <> '' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id); - --- The rest are matched by the wanted worker after boot: the listing resumes. -UPDATE acquisition_settings - SET library_listed_at = NULL, library_unlisted = 0 - WHERE library_listing_started_at IS NOT NULL; diff --git a/internal/db/migrations/0087_library_rematch.down.sql b/internal/db/migrations/0087_library_rematch.down.sql deleted file mode 100644 index 66b5e525..00000000 --- a/internal/db/migrations/0087_library_rematch.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Nothing to undo: the refused albums are matched again either way. -SELECT 1; diff --git a/internal/db/migrations/0087_library_rematch.up.sql b/internal/db/migrations/0087_library_rematch.up.sql deleted file mode 100644 index cc278ed9..00000000 --- a/internal/db/migrations/0087_library_rematch.up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- The first matching (0086) required every track's length to fit as well --- as its title, and refused singles and near-complete albums the library --- plainly holds. Matching now takes the titles alone under the album's own --- name: the albums it refused are matched again. -DELETE FROM library_album_matches WHERE outcome = 'unmatched'; - -UPDATE acquisition_settings - SET library_listed_at = NULL, library_unlisted = 0 - WHERE library_listing_started_at IS NOT NULL; diff --git a/internal/db/migrations/0088_library_matcher_version.down.sql b/internal/db/migrations/0088_library_matcher_version.down.sql deleted file mode 100644 index 1e22094a..00000000 --- a/internal/db/migrations/0088_library_matcher_version.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE library_album_matches DROP COLUMN matcher; diff --git a/internal/db/migrations/0088_library_matcher_version.up.sql b/internal/db/migrations/0088_library_matcher_version.up.sql deleted file mode 100644 index 568921f5..00000000 --- a/internal/db/migrations/0088_library_matcher_version.up.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Which version of the matching decided an album. A refusal by an --- older matcher is tried again by a newer one, so improving the matching --- reaches the albums it refused without a migration each time. -ALTER TABLE library_album_matches ADD COLUMN matcher integer NOT NULL DEFAULT 0; diff --git a/internal/db/migrations/0089_library_match_by_hand.down.sql b/internal/db/migrations/0089_library_match_by_hand.down.sql deleted file mode 100644 index 678f4eab..00000000 --- a/internal/db/migrations/0089_library_match_by_hand.down.sql +++ /dev/null @@ -1,8 +0,0 @@ -UPDATE library_album_matches SET outcome = 'unmatched' WHERE outcome = 'dismissed'; -UPDATE library_album_matches SET method = 'search' WHERE method = 'manual'; -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_outcome_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_outcome_check - CHECK (outcome IN ('listed', 'unmatched')); -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_method_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_method_check - CHECK (method IN ('', 'tags', 'release', 'discography', 'search')); diff --git a/internal/db/migrations/0089_library_match_by_hand.up.sql b/internal/db/migrations/0089_library_match_by_hand.up.sql deleted file mode 100644 index 8d8e47ca..00000000 --- a/internal/db/migrations/0089_library_match_by_hand.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- The Collection's Unmatched section: a person matches an album the --- listing could not, by a MusicBrainz link or a search (method 'manual'), --- or leaves it off the list for good (outcome 'dismissed': a local band's --- album MusicBrainz will never have, a mix that is no album). -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_outcome_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_outcome_check - CHECK (outcome IN ('listed', 'unmatched', 'dismissed')); -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_method_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_method_check - CHECK (method IN ('', 'tags', 'release', 'discography', 'search', 'manual')); diff --git a/internal/db/migrations/0090_upgrades.down.sql b/internal/db/migrations/0090_upgrades.down.sql deleted file mode 100644 index 8986bbc1..00000000 --- a/internal/db/migrations/0090_upgrades.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -DROP INDEX IF EXISTS wants_upgrade_idx; -ALTER TABLE wants - DROP COLUMN upgrade_checked_at, - DROP COLUMN held_quality, - DROP COLUMN held_tier, - DROP COLUMN upgrade; -ALTER TABLE acquisition_settings DROP COLUMN upgrade_until; diff --git a/internal/db/migrations/0090_upgrades.up.sql b/internal/db/migrations/0090_upgrades.up.sql deleted file mode 100644 index c64734d4..00000000 --- a/internal/db/migrations/0090_upgrades.up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- Upgrades: a held album whose copy is below the quality an admin settles --- for, or that holds a video rip, stays wanted for a better --- copy. The import replaces the old tracks with the new ones. --- --- acquisition_settings.upgrade_until the tier a held album is upgraded to; --- '' switches quality upgrades off. --- Lidarr's "Any" profile upgraded up to --- High Quality Lossy. --- wants.upgrade why a held album is wanted again: --- quality (below upgrade_until) or rip --- (a track is a video rip); '' not. --- wants.held_tier, held_quality the library copy's tier, estimated --- from format and size per second, and --- the same in words. --- wants.upgrade_checked_at when the wanted worker last judged it. --- want_candidates.verdict unchanged: a release no better than --- the copy held is "refused". -ALTER TABLE acquisition_settings - ADD COLUMN upgrade_until text NOT NULL DEFAULT 'lossy_high'; - -ALTER TABLE wants - ADD COLUMN upgrade text NOT NULL DEFAULT '' - CONSTRAINT wants_upgrade_check CHECK (upgrade IN ('', 'quality', 'rip')), - ADD COLUMN held_tier text NOT NULL DEFAULT '', - ADD COLUMN held_quality text NOT NULL DEFAULT '', - ADD COLUMN upgrade_checked_at timestamptz; - -CREATE INDEX wants_upgrade_idx ON wants (searched_at NULLS FIRST) - WHERE fulfilled_at IS NOT NULL AND upgrade <> ''; diff --git a/internal/db/migrations/0091_remove_lidarr.down.sql b/internal/db/migrations/0091_remove_lidarr.down.sql deleted file mode 100644 index dceb707f..00000000 --- a/internal/db/migrations/0091_remove_lidarr.down.sql +++ /dev/null @@ -1,29 +0,0 @@ -ALTER TABLE quarantine_actions RENAME CONSTRAINT quarantine_actions_admin_id_fkey TO lidarr_quarantine_actions_admin_id_fkey; -ALTER TABLE quarantine RENAME CONSTRAINT quarantine_track_id_fkey TO lidarr_quarantine_track_id_fkey; -ALTER TABLE quarantine RENAME CONSTRAINT quarantine_user_id_fkey TO lidarr_quarantine_user_id_fkey; - -ALTER INDEX quarantine_actions_created_idx RENAME TO lidarr_quarantine_actions_created_idx; -ALTER INDEX quarantine_actions_track_idx RENAME TO lidarr_quarantine_actions_track_idx; -ALTER INDEX quarantine_actions_pkey RENAME TO lidarr_quarantine_actions_pkey; -ALTER TABLE quarantine_actions RENAME COLUMN album_mbid TO lidarr_album_mbid; -ALTER TYPE quarantine_action_kind RENAME VALUE 'deleted_album' TO 'deleted_via_lidarr'; -ALTER TYPE quarantine_action_kind RENAME TO lidarr_quarantine_action_kind; -ALTER TABLE quarantine_actions RENAME TO lidarr_quarantine_actions; - -ALTER INDEX quarantine_pkey RENAME TO lidarr_quarantine_pkey; -ALTER INDEX quarantine_track_idx RENAME TO lidarr_quarantine_track_idx; -ALTER TYPE quarantine_reason RENAME TO lidarr_quarantine_reason; -ALTER TABLE quarantine RENAME TO lidarr_quarantine; - -CREATE TABLE lidarr_config ( - id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), - enabled boolean NOT NULL DEFAULT false, - base_url text, - api_key text, - default_quality_profile_id int, - default_root_folder_path text, - default_metadata_profile_id integer, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -INSERT INTO lidarr_config (id, enabled) VALUES (1, false); diff --git a/internal/db/migrations/0091_remove_lidarr.up.sql b/internal/db/migrations/0091_remove_lidarr.up.sql deleted file mode 100644 index b8e64723..00000000 --- a/internal/db/migrations/0091_remove_lidarr.up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- Minstrel does not talk to Lidarr: it finds, downloads, --- checks and files music itself. --- --- lidarr_config the connection's settings: dropped. --- lidarr_quarantine(_actions) the per-user track reports and the admin --- actions on them, which never needed Lidarr: --- renamed to quarantine(_actions), with their --- types and indexes. --- 'deleted_via_lidarr' the history of an album removed through --- Lidarr reads as what it did: 'deleted_album'. --- lidarr_album_mbid the album id that removal recorded: album_mbid. -DROP TABLE lidarr_config; - -ALTER TABLE lidarr_quarantine RENAME TO quarantine; -ALTER TYPE lidarr_quarantine_reason RENAME TO quarantine_reason; -ALTER INDEX lidarr_quarantine_track_idx RENAME TO quarantine_track_idx; -ALTER INDEX lidarr_quarantine_pkey RENAME TO quarantine_pkey; - -ALTER TABLE lidarr_quarantine_actions RENAME TO quarantine_actions; -ALTER TYPE lidarr_quarantine_action_kind RENAME TO quarantine_action_kind; -ALTER TYPE quarantine_action_kind RENAME VALUE 'deleted_via_lidarr' TO 'deleted_album'; -ALTER TABLE quarantine_actions RENAME COLUMN lidarr_album_mbid TO album_mbid; -ALTER INDEX lidarr_quarantine_actions_pkey RENAME TO quarantine_actions_pkey; -ALTER INDEX lidarr_quarantine_actions_track_idx RENAME TO quarantine_actions_track_idx; -ALTER INDEX lidarr_quarantine_actions_created_idx RENAME TO quarantine_actions_created_idx; - -ALTER TABLE quarantine RENAME CONSTRAINT lidarr_quarantine_user_id_fkey TO quarantine_user_id_fkey; -ALTER TABLE quarantine RENAME CONSTRAINT lidarr_quarantine_track_id_fkey TO quarantine_track_id_fkey; -ALTER TABLE quarantine_actions RENAME CONSTRAINT lidarr_quarantine_actions_admin_id_fkey TO quarantine_actions_admin_id_fkey; diff --git a/internal/db/migrations/0092_play_events_started_idx.down.sql b/internal/db/migrations/0092_play_events_started_idx.down.sql deleted file mode 100644 index 62eafa51..00000000 --- a/internal/db/migrations/0092_play_events_started_idx.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP INDEX IF EXISTS play_events_started_idx; diff --git a/internal/db/migrations/0092_play_events_started_idx.up.sql b/internal/db/migrations/0092_play_events_started_idx.up.sql deleted file mode 100644 index d5404011..00000000 --- a/internal/db/migrations/0092_play_events_started_idx.up.sql +++ /dev/null @@ -1,4 +0,0 @@ --- The admin Overview reads plays across every user by time: the ones --- in progress and the last day's count. The only index on play_events leads --- with user_id, so without this every Overview load scanned the table. -CREATE INDEX play_events_started_idx ON play_events (started_at); diff --git a/internal/db/migrations/0093_library_settings.down.sql b/internal/db/migrations/0093_library_settings.down.sql deleted file mode 100644 index 793e3ffb..00000000 --- a/internal/db/migrations/0093_library_settings.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS library_settings; diff --git a/internal/db/migrations/0093_library_settings.up.sql b/internal/db/migrations/0093_library_settings.up.sql deleted file mode 100644 index 4bf3473d..00000000 --- a/internal/db/migrations/0093_library_settings.up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- The library's folders, set in Settings. Until someone saves them --- there, scan_paths is NULL and MINSTREL_LIBRARY_SCAN_PATHS names the folders, --- as it always has; from the first save the row is what the server reads. -CREATE TABLE library_settings ( - id boolean PRIMARY KEY DEFAULT true, - scan_paths text[], - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT library_settings_singleton CHECK (id = true) -); -INSERT INTO library_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0094_duplicate_distinct.down.sql b/internal/db/migrations/0094_duplicate_distinct.down.sql deleted file mode 100644 index e5e44233..00000000 --- a/internal/db/migrations/0094_duplicate_distinct.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -UPDATE duplicate_groups SET class = 'review' WHERE class = 'distinct'; -ALTER TABLE duplicate_groups DROP CONSTRAINT duplicate_groups_class_check; -ALTER TABLE duplicate_groups ADD CONSTRAINT duplicate_groups_class_check - CHECK (class IN ('same_release', 'cross_release', 'mismatch', 'review')); diff --git a/internal/db/migrations/0094_duplicate_distinct.up.sql b/internal/db/migrations/0094_duplicate_distinct.up.sql deleted file mode 100644 index 856757e5..00000000 --- a/internal/db/migrations/0094_duplicate_distinct.up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- 0094_duplicate_distinct.up.sql — duplicates settle themselves, without --- waiting on an admin. --- --- distinct: one album holds two versions of a song that sound alike ("Lovesick" --- and "Lovesick (Instrumental)"). They are not duplicates, and the resolver --- dismisses them itself. mismatch now also covers one album holding the same --- audio in several track slots, the resolver's wrong-file case. --- The new value swaps the constraint in the same migration. -ALTER TABLE duplicate_groups DROP CONSTRAINT duplicate_groups_class_check; -ALTER TABLE duplicate_groups ADD CONSTRAINT duplicate_groups_class_check - CHECK (class IN ('same_release', 'cross_release', 'mismatch', 'distinct', 'review')); diff --git a/internal/db/migrations/0095_tracks_emptied_at.down.sql b/internal/db/migrations/0095_tracks_emptied_at.down.sql deleted file mode 100644 index f3feee97..00000000 --- a/internal/db/migrations/0095_tracks_emptied_at.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE tracks DROP COLUMN emptied_at; diff --git a/internal/db/migrations/0095_tracks_emptied_at.up.sql b/internal/db/migrations/0095_tracks_emptied_at.up.sql deleted file mode 100644 index 3ab7883a..00000000 --- a/internal/db/migrations/0095_tracks_emptied_at.up.sql +++ /dev/null @@ -1,13 +0,0 @@ --- 0095_tracks_emptied_at.up.sql — a slot the duplicate resolver emptied --- waits for a copy fetched again. --- --- When the resolver removes a file filed under another song's title and the --- album holds no copy of that song as long as the song is, the row is marked --- missing and stamped here with the same time. Missing-pair folding then pairs --- it by title only with a track added after that time, a copy fetched again, --- and not with one already on the album, which under that title holds --- another song. --- --- The stamp counts only while it equals missing_since: a row whose file came --- back and later went missing again is an ordinary missing row. -ALTER TABLE tracks ADD COLUMN emptied_at timestamptz; diff --git a/internal/db/migrations/0096_similarity_relative_scores.down.sql b/internal/db/migrations/0096_similarity_relative_scores.down.sql deleted file mode 100644 index 7c4e468f..00000000 --- a/internal/db/migrations/0096_similarity_relative_scores.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- The raw scores are not kept for artists; the worker rewrites every seed with --- relative scores on its next fetch either way. Nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0096_similarity_relative_scores.up.sql b/internal/db/migrations/0096_similarity_relative_scores.up.sql deleted file mode 100644 index 111e110e..00000000 --- a/internal/db/migrations/0096_similarity_relative_scores.up.sql +++ /dev/null @@ -1,51 +0,0 @@ --- Before: ListenBrainz similarity scores were stored raw. They are counts, into --- the thousands, and every reader treats similarity as 0 to 1. After: the --- stored rows are rescaled relative to each seed's best score, as the worker --- now writes them. --- --- A seed's best is taken over everything stored for it: the cached LB answer --- and its edges for tracks, matched and unmatched rows for artists. A seed --- whose best is already at most 1 is left alone, so a second run changes --- nothing. - -WITH best AS ( - SELECT seed_id, max(score) AS score - FROM ( - SELECT track_a_id AS seed_id, score FROM track_similarity WHERE source = 'listenbrainz' - UNION ALL - SELECT seed_track_id, score FROM listenbrainz_similar_recordings - ) s - GROUP BY seed_id -) -UPDATE track_similarity ts - SET score = ts.score / b.score - FROM best b - WHERE ts.source = 'listenbrainz' - AND ts.track_a_id = b.seed_id - AND b.score > 1; - --- One statement, so both updates divide by the best as it stood before either. -WITH best AS ( - SELECT seed_id, max(score) AS score - FROM ( - SELECT artist_a_id AS seed_id, score FROM artist_similarity WHERE source = 'listenbrainz' - UNION ALL - SELECT seed_artist_id, score FROM artist_similarity_unmatched WHERE source = 'listenbrainz' - ) s - GROUP BY seed_id -), -matched AS ( - UPDATE artist_similarity a - SET score = a.score / b.score - FROM best b - WHERE a.source = 'listenbrainz' - AND a.artist_a_id = b.seed_id - AND b.score > 1 - RETURNING 1 -) -UPDATE artist_similarity_unmatched u - SET score = u.score / b.score - FROM best b - WHERE u.source = 'listenbrainz' - AND u.seed_artist_id = b.seed_id - AND b.score > 1; diff --git a/internal/db/migrations/0097_requeue_short_track_prints.down.sql b/internal/db/migrations/0097_requeue_short_track_prints.down.sql deleted file mode 100644 index f1513b02..00000000 --- a/internal/db/migrations/0097_requeue_short_track_prints.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- The cleared rows were failures; the workers write them again, or better. --- Nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0097_requeue_short_track_prints.up.sql b/internal/db/migrations/0097_requeue_short_track_prints.up.sql deleted file mode 100644 index 47288f43..00000000 --- a/internal/db/migrations/0097_requeue_short_track_prints.up.sql +++ /dev/null @@ -1,20 +0,0 @@ --- The image's fpcalc exits 3 ("Error decoding audio frame (End of file)") on --- every file shorter than the span it is asked for, so every track under two --- minutes failed both prints. Before: the failure was stored as a verdict, and --- a verdict is not retried until the file changes. After: fpcalcReadToEnd keeps --- those prints; clear the failures so the workers take them again. - --- The AcoustID lookup's queue takes a track with no lookup row. -DELETE FROM track_acoustid_lookups - WHERE state = 'failed' - AND detail LIKE '%Error decoding audio frame (End of file)%'; - --- The fingerprint backfill's queue takes a track with no fingerprint row. A --- NULL chromaprint is always a verdict (an inconclusive attempt stores --- nothing), and on a track no longer than the span it was taken at it is this --- failure. A track that is damaged fails again and is stamped again. -DELETE FROM track_fingerprints f - USING tracks t - WHERE f.track_id = t.id - AND f.chromaprint IS NULL - AND t.duration_ms <= f.chromaprint_length_sec * 1000; diff --git a/internal/db/migrations/0098_release_blocks_gone.down.sql b/internal/db/migrations/0098_release_blocks_gone.down.sql deleted file mode 100644 index 97d45aea..00000000 --- a/internal/db/migrations/0098_release_blocks_gone.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DELETE FROM release_blocks WHERE reason = 'gone'; -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import', 'stalled')); diff --git a/internal/db/migrations/0098_release_blocks_gone.up.sql b/internal/db/migrations/0098_release_blocks_gone.up.sql deleted file mode 100644 index 1b2a2cfe..00000000 --- a/internal/db/migrations/0098_release_blocks_gone.up.sql +++ /dev/null @@ -1,6 +0,0 @@ --- gone: a release its download client would not let Minstrel follow: --- held outside Minstrel's category, or leaving the client twice. Held back --- until expires_at, as stalled is. -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import', 'stalled', 'gone')); diff --git a/internal/db/migrations/0106_baseline.down.sql b/internal/db/migrations/0106_baseline.down.sql new file mode 100644 index 00000000..98893644 --- /dev/null +++ b/internal/db/migrations/0106_baseline.down.sql @@ -0,0 +1 @@ +DO $$ BEGIN RAISE EXCEPTION 'the baseline is the whole schema and cannot be undone; restore a backup instead'; END $$; diff --git a/internal/db/migrations/0106_baseline.up.sql b/internal/db/migrations/0106_baseline.up.sql new file mode 100644 index 00000000..7f3de9ff --- /dev/null +++ b/internal/db/migrations/0106_baseline.up.sql @@ -0,0 +1,1433 @@ +-- The whole schema at version 106, and the settings rows it starts with. +-- Earlier versions were folded into this one; a database already at 106 +-- skips it, and an older one restores from a backup instead. + +CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; + +CREATE TYPE public.quarantine_action_kind AS ENUM ( + 'resolved', + 'deleted_file', + 'deleted_album', + 'removed_file' +); + +CREATE TYPE public.quarantine_reason AS ENUM ( + 'bad_rip', + 'wrong_file', + 'wrong_tags', + 'duplicate', + 'other' +); + +CREATE TABLE public.acoustid_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT false NOT NULL, + api_key text, + min_score real DEFAULT 0.85 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT acoustid_settings_min_score_range CHECK (((min_score >= (0.5)::double precision) AND (min_score <= (1)::double precision))), + CONSTRAINT acoustid_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.album_loudness ( + album_id uuid NOT NULL, + integrated_lufs real, + true_peak_dbtp real, + tracks_total integer NOT NULL, + tracks_settled integer NOT NULL, + inputs_digest text NOT NULL, + computed_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.albums ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + title text NOT NULL, + sort_title text NOT NULL, + artist_id uuid NOT NULL, + release_date date, + mbid text, + cover_art_path text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + cover_art_source text, + cover_art_sources_version integer DEFAULT 0 NOT NULL, + release_group_mbid text, + announced_at timestamp with time zone, + CONSTRAINT albums_cover_art_source_check CHECK (((cover_art_source IS NULL) OR (cover_art_source <> ''::text))) +); + +CREATE TABLE public.artist_similarity ( + artist_a_id uuid NOT NULL, + artist_b_id uuid NOT NULL, + score double precision NOT NULL, + source text NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT artist_similarity_check CHECK ((artist_a_id <> artist_b_id)), + CONSTRAINT artist_similarity_source_check CHECK ((source = ANY (ARRAY['listenbrainz'::text, 'musicbrainz_tag'::text, 'user_cooccurrence'::text]))) +); + +CREATE TABLE public.artist_similarity_fetches ( + artist_id uuid NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + returned integer NOT NULL +); + +CREATE TABLE public.artists ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + name text NOT NULL, + sort_name text NOT NULL, + mbid text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + artist_thumb_path text, + artist_fanart_path text, + artist_art_source text, + artist_art_sources_version integer DEFAULT 0 NOT NULL, + CONSTRAINT artists_artist_art_source_check CHECK (((artist_art_source IS NULL) OR (artist_art_source <> ''::text))) +); + +CREATE TABLE public.audit_log ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + actor_id uuid, + target_id uuid, + action text NOT NULL, + metadata jsonb, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.backup_music_files ( + track_id uuid NOT NULL, + size bigint NOT NULL, + mtime timestamp with time zone NOT NULL, + location text NOT NULL, + checked_at timestamp with time zone DEFAULT now() NOT NULL, + error text DEFAULT ''::text NOT NULL +); + +CREATE TABLE public.backup_runs ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + trigger text NOT NULL, + status text DEFAULT 'running'::text NOT NULL, + started_at timestamp with time zone DEFAULT now() NOT NULL, + finished_at timestamp with time zone, + location text DEFAULT ''::text NOT NULL, + bytes bigint DEFAULT 0 NOT NULL, + error text DEFAULT ''::text NOT NULL, + music_files integer DEFAULT 0 NOT NULL, + music_bytes bigint DEFAULT 0 NOT NULL, + music_note text DEFAULT ''::text NOT NULL, + CONSTRAINT backup_runs_status_check CHECK ((status = ANY (ARRAY['running'::text, 'succeeded'::text, 'failed'::text]))), + CONSTRAINT backup_runs_trigger_check CHECK ((trigger = ANY (ARRAY['schedule'::text, 'manual'::text]))) +); + +CREATE TABLE public.backup_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT false NOT NULL, + destination text DEFAULT 's3'::text NOT NULL, + folder text DEFAULT ''::text NOT NULL, + endpoint text DEFAULT ''::text NOT NULL, + bucket text DEFAULT ''::text NOT NULL, + access_key text DEFAULT ''::text NOT NULL, + secret_key text DEFAULT ''::text NOT NULL, + run_hour smallint DEFAULT 3 NOT NULL, + upload_limit_kib integer DEFAULT 4096 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + include_music boolean DEFAULT false NOT NULL, + CONSTRAINT backup_settings_destination_check CHECK ((destination = ANY (ARRAY['folder'::text, 's3'::text]))), + CONSTRAINT backup_settings_one_row CHECK (id), + CONSTRAINT backup_settings_run_hour_check CHECK (((run_hour >= 0) AND (run_hour <= 23))), + CONSTRAINT backup_settings_upload_limit_check CHECK ((upload_limit_kib >= 0)) +); + +CREATE TABLE public.contextual_likes ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + track_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL, + deleted_at timestamp with time zone, + session_vector jsonb, + session_id uuid +); + +CREATE TABLE public.cover_art_provider_settings ( + provider_id text NOT NULL, + enabled boolean DEFAULT true NOT NULL, + api_key text, + display_order integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.cover_art_sources_meta ( + id boolean DEFAULT true NOT NULL, + current_version integer DEFAULT 1 NOT NULL, + last_registered_providers_hash text DEFAULT ''::text NOT NULL, + CONSTRAINT cover_art_sources_meta_singleton CHECK ((id = true)) +); + +CREATE TABLE public.diagnostic_events ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + client_id text NOT NULL, + app_version text, + os_version text, + kind text NOT NULL, + payload jsonb DEFAULT '{}'::jsonb NOT NULL, + occurred_at timestamp with time zone NOT NULL, + received_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT diagnostic_events_kind_check CHECK ((kind = ANY (ARRAY['connectivity'::text, 'upnp_sync'::text, 'power'::text, 'lifecycle'::text, 'heartbeat'::text, 'http'::text, 'playback'::text]))) +); + +CREATE TABLE public.duplicate_group_members ( + group_id uuid NOT NULL, + track_id uuid NOT NULL +); + +CREATE TABLE public.duplicate_groups ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + member_key text NOT NULL, + tier text NOT NULL, + worst_bit_error_rate real, + status text DEFAULT 'pending'::text NOT NULL, + detected_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen_sweep_id uuid, + resolved_at timestamp with time zone, + class text, + resolve_note text, + resolved_automatically boolean DEFAULT false NOT NULL, + CONSTRAINT duplicate_groups_class_check CHECK ((class = ANY (ARRAY['same_release'::text, 'cross_release'::text, 'mismatch'::text, 'distinct'::text, 'review'::text]))), + CONSTRAINT duplicate_groups_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'dismissed'::text, 'merged'::text]))), + CONSTRAINT duplicate_groups_tier_check CHECK ((tier = ANY (ARRAY['exact'::text, 'acoustic'::text]))) +); + +CREATE TABLE public.duplicate_sweeps ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + started_at timestamp with time zone DEFAULT now() NOT NULL, + finished_at timestamp with time zone, + candidates integer, + groups_found integer, + oversize_clusters integer, + error_message text +); + +CREATE TABLE public.fingerprint_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT true NOT NULL, + chromaprint_length_sec integer DEFAULT 120 NOT NULL, + acoustic_max_bit_error_rate double precision DEFAULT 0.15 NOT NULL, + backfill_concurrency integer DEFAULT 2 NOT NULL, + sweep_interval_hours integer DEFAULT 1 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + auto_resolve boolean DEFAULT true NOT NULL, + CONSTRAINT fingerprint_settings_concurrency_range CHECK (((backfill_concurrency >= 1) AND (backfill_concurrency <= 8))), + CONSTRAINT fingerprint_settings_length_range CHECK (((chromaprint_length_sec >= 30) AND (chromaprint_length_sec <= 600))), + CONSTRAINT fingerprint_settings_singleton CHECK ((id = true)), + CONSTRAINT fingerprint_settings_sweep_interval_range CHECK (((sweep_interval_hours >= 1) AND (sweep_interval_hours <= 168))), + CONSTRAINT fingerprint_settings_threshold_range CHECK (((acoustic_max_bit_error_rate >= (0.01)::double precision) AND (acoustic_max_bit_error_rate <= (0.35)::double precision))) +); + +CREATE TABLE public.general_likes ( + user_id uuid NOT NULL, + track_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.general_likes_albums ( + user_id uuid NOT NULL, + album_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.general_likes_artists ( + user_id uuid NOT NULL, + artist_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.library_changes ( + id bigint NOT NULL, + entity_type text NOT NULL, + entity_id text NOT NULL, + op text NOT NULL, + changed_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT library_changes_entity_type_check CHECK ((entity_type = ANY (ARRAY['artist'::text, 'album'::text, 'track'::text, 'like_track'::text, 'like_album'::text, 'like_artist'::text, 'playlist'::text, 'playlist_track'::text]))), + CONSTRAINT library_changes_op_check CHECK ((op = ANY (ARRAY['upsert'::text, 'delete'::text]))) +); + +CREATE SEQUENCE public.library_changes_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +ALTER SEQUENCE public.library_changes_id_seq OWNED BY public.library_changes.id; + +CREATE TABLE public.library_changes_trimmed ( + id boolean DEFAULT true NOT NULL, + through bigint DEFAULT 0 NOT NULL, + CONSTRAINT library_changes_trimmed_one_row CHECK (id) +); + +CREATE TABLE public.library_settings ( + id boolean DEFAULT true NOT NULL, + scan_paths text[], + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT library_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.listenbrainz_similar_recordings ( + seed_track_id uuid NOT NULL, + recording_mbid text NOT NULL, + score double precision NOT NULL +); + +CREATE TABLE public.loudness_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT true NOT NULL, + backfill_concurrency integer DEFAULT 2 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + leveled_cache_mb integer DEFAULT 2048 NOT NULL, + CONSTRAINT loudness_settings_concurrency_range CHECK (((backfill_concurrency >= 1) AND (backfill_concurrency <= 8))), + CONSTRAINT loudness_settings_leveled_cache_range CHECK (((leveled_cache_mb >= 256) AND (leveled_cache_mb <= 65536))), + CONSTRAINT loudness_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.mb_release_groups ( + mbid text NOT NULL, + title text NOT NULL, + primary_type text DEFAULT ''::text NOT NULL, + secondary_types text[] DEFAULT '{}'::text[] NOT NULL, + first_release_date text DEFAULT ''::text NOT NULL, + artist_credit text DEFAULT ''::text NOT NULL, + releases_refreshed_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.mb_release_tracks ( + release_mbid text NOT NULL, + medium_position integer NOT NULL, + "position" integer NOT NULL, + medium_format text DEFAULT ''::text NOT NULL, + number text DEFAULT ''::text NOT NULL, + title text NOT NULL, + length_ms integer DEFAULT 0 NOT NULL, + recording_mbid text DEFAULT ''::text NOT NULL +); + +CREATE TABLE public.mb_releases ( + mbid text NOT NULL, + release_group_mbid text NOT NULL, + title text NOT NULL, + status text DEFAULT ''::text NOT NULL, + release_date text DEFAULT ''::text NOT NULL, + country text DEFAULT ''::text NOT NULL, + disambiguation text DEFAULT ''::text NOT NULL, + formats text DEFAULT ''::text NOT NULL, + track_count integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.network_settings ( + id boolean DEFAULT true NOT NULL, + trusted_proxy_hops integer DEFAULT 1 NOT NULL, + public_url text DEFAULT ''::text NOT NULL, + CONSTRAINT network_settings_hops_range CHECK (((trusted_proxy_hops >= 0) AND (trusted_proxy_hops <= 10))), + CONSTRAINT network_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.notification_email_settings ( + id boolean DEFAULT true NOT NULL, + summary_hour integer DEFAULT 9 NOT NULL, + batch_window_minutes integer DEFAULT 60 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT notification_email_settings_hour_range CHECK (((summary_hour >= 0) AND (summary_hour <= 23))), + CONSTRAINT notification_email_settings_singleton CHECK ((id = true)), + CONSTRAINT notification_email_settings_window_range CHECK (((batch_window_minutes >= 15) AND (batch_window_minutes <= 1440))) +); + +CREATE TABLE public.password_resets ( + token text NOT NULL, + user_id uuid NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + expires_at timestamp with time zone NOT NULL, + used_at timestamp with time zone +); + +CREATE TABLE public.play_events ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + track_id uuid NOT NULL, + session_id uuid NOT NULL, + started_at timestamp with time zone NOT NULL, + ended_at timestamp with time zone, + duration_played_ms integer, + completion_ratio double precision, + was_skipped boolean DEFAULT false NOT NULL, + client_id text, + session_vector_at_play jsonb, + scrobbled_at timestamp with time zone, + source text, + pick_kind text, + device_class text, + CONSTRAINT play_events_pick_kind_check CHECK ((pick_kind = ANY (ARRAY['taste'::text, 'fresh'::text, 'dormant'::text, 'cross_user'::text, 'random'::text, 'taste_unheard'::text, 'tier1'::text, 'tier2'::text, 'tier3'::text]))) +); + +CREATE TABLE public.play_sessions ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + started_at timestamp with time zone NOT NULL, + ended_at timestamp with time zone, + last_event_at timestamp with time zone NOT NULL, + track_count integer DEFAULT 0 NOT NULL, + client_id text +); + +CREATE TABLE public.playback_errors ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + track_id uuid NOT NULL, + user_id uuid NOT NULL, + client_id text NOT NULL, + kind text NOT NULL, + detail text, + occurred_at timestamp with time zone DEFAULT now() NOT NULL, + resolved_at timestamp with time zone, + resolved_by uuid, + resolution text, + CONSTRAINT playback_errors_kind_check CHECK ((kind = ANY (ARRAY['zero_duration'::text, 'load_failed'::text, 'stalled'::text]))), + CONSTRAINT playback_errors_resolution_check CHECK (((resolution IS NULL) OR (resolution = ANY (ARRAY['hidden'::text, 'deleted'::text, 'fixed'::text, 'ignored'::text])))), + CONSTRAINT playback_errors_resolved_consistency CHECK (((resolved_at IS NULL) = (resolution IS NULL))) +); + +CREATE TABLE public.playlist_tracks ( + playlist_id uuid NOT NULL, + "position" integer NOT NULL, + track_id uuid, + title text NOT NULL, + artist_name text NOT NULL, + album_title text NOT NULL, + duration_sec integer NOT NULL, + added_at timestamp with time zone DEFAULT now() NOT NULL, + pick_kind text, + CONSTRAINT playlist_tracks_pick_kind_check CHECK ((pick_kind = ANY (ARRAY['taste'::text, 'fresh'::text, 'dormant'::text, 'cross_user'::text, 'random'::text, 'taste_unheard'::text, 'tier1'::text, 'tier2'::text, 'tier3'::text]))) +); + +CREATE TABLE public.playlists ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + name text NOT NULL, + description text DEFAULT ''::text NOT NULL, + is_public boolean DEFAULT false NOT NULL, + cover_path text, + track_count integer DEFAULT 0 NOT NULL, + duration_sec integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + kind text DEFAULT 'user'::text NOT NULL, + system_variant text, + seed_artist_id uuid, + CONSTRAINT playlists_kind_variant_consistent CHECK ((((kind = 'user'::text) AND (system_variant IS NULL)) OR ((kind = 'system'::text) AND (system_variant = ANY (ARRAY['for_you'::text, 'songs_like_artist'::text, 'discover'::text, 'deep_cuts'::text, 'rediscover'::text, 'new_for_you'::text, 'on_this_day'::text, 'first_listens'::text, 'genre_mix'::text]))))), + CONSTRAINT playlists_seed_consistent CHECK ((((system_variant IS NULL) AND (seed_artist_id IS NULL)) OR ((system_variant = 'for_you'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'discover'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'deep_cuts'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'rediscover'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'new_for_you'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'on_this_day'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'first_listens'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'genre_mix'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'songs_like_artist'::text) AND (seed_artist_id IS NOT NULL)))) +); + +CREATE TABLE public.quarantine ( + user_id uuid NOT NULL, + track_id uuid NOT NULL, + reason public.quarantine_reason NOT NULL, + notes text, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.quarantine_actions ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + track_id uuid NOT NULL, + track_title text NOT NULL, + artist_name text NOT NULL, + album_title text, + action public.quarantine_action_kind NOT NULL, + admin_id uuid, + album_mbid text, + affected_users integer NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.recommendation_tuning_audit ( + id bigint NOT NULL, + changed_at timestamp with time zone DEFAULT now() NOT NULL, + scope text NOT NULL, + action text NOT NULL, + changes jsonb NOT NULL, + CONSTRAINT recommendation_tuning_audit_action_check CHECK ((action = ANY (ARRAY['update'::text, 'reset'::text]))), + CONSTRAINT recommendation_tuning_audit_scope_check CHECK ((scope = ANY (ARRAY['radio'::text, 'daily_mix'::text, 'taste'::text, 'discover'::text, 'songs_like'::text]))) +); + +CREATE SEQUENCE public.recommendation_tuning_audit_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +ALTER SEQUENCE public.recommendation_tuning_audit_id_seq OWNED BY public.recommendation_tuning_audit.id; + +CREATE TABLE public.recommendation_weight_profiles ( + profile text NOT NULL, + base_weight double precision NOT NULL, + like_boost double precision NOT NULL, + recency_weight double precision NOT NULL, + skip_penalty double precision NOT NULL, + jitter_magnitude double precision NOT NULL, + context_weight double precision NOT NULL, + similarity_weight double precision NOT NULL, + taste_weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + context_time_weight double precision DEFAULT 1.0 NOT NULL, + CONSTRAINT recommendation_weight_profiles_profile_check CHECK ((profile = ANY (ARRAY['radio'::text, 'daily_mix'::text, 'songs_like'::text]))) +); + +CREATE TABLE public.registration_settings ( + id boolean DEFAULT true NOT NULL, + mode text DEFAULT 'invite_only'::text NOT NULL, + CONSTRAINT registration_settings_mode_check CHECK ((mode = ANY (ARRAY['invite_only'::text, 'open'::text]))), + CONSTRAINT registration_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.scan_runs ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + started_at timestamp with time zone DEFAULT now() NOT NULL, + finished_at timestamp with time zone, + library jsonb, + mbid_backfill jsonb, + cover_enrich jsonb, + error_message text, + artist_art_enrich jsonb +); + +CREATE TABLE public.scrobble_queue ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + play_event_id uuid NOT NULL, + status text NOT NULL, + attempts integer DEFAULT 0 NOT NULL, + next_attempt_at timestamp with time zone DEFAULT now() NOT NULL, + last_error text, + enqueued_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT scrobble_queue_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'failed'::text]))) +); + +CREATE TABLE public.sessions ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + token_hash bytea NOT NULL, + user_agent text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen_at timestamp with time zone DEFAULT now() NOT NULL, + created_ip text DEFAULT ''::text NOT NULL, + last_ip text DEFAULT ''::text NOT NULL +); + +CREATE TABLE public.skip_events ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + track_id uuid NOT NULL, + session_id uuid NOT NULL, + skipped_at timestamp with time zone NOT NULL, + position_ms integer NOT NULL +); + +CREATE TABLE public.smtp_config ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT false NOT NULL, + host text DEFAULT ''::text NOT NULL, + port integer DEFAULT 587 NOT NULL, + username text DEFAULT ''::text NOT NULL, + password text DEFAULT ''::text NOT NULL, + from_address text DEFAULT ''::text NOT NULL, + from_name text DEFAULT 'Minstrel'::text NOT NULL, + use_tls boolean DEFAULT true NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT smtp_config_singleton CHECK ((id = true)) +); + +CREATE TABLE public.system_playlist_rotation_state ( + user_id uuid NOT NULL, + playlist_kind text NOT NULL, + played_track_ids uuid[] DEFAULT '{}'::uuid[] NOT NULL, + rotation_started_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.system_playlist_runs ( + user_id uuid NOT NULL, + last_run_at timestamp with time zone, + last_run_date date, + in_flight boolean DEFAULT false NOT NULL, + last_error text +); + +CREATE TABLE public.tag_provider_settings ( + provider_id text NOT NULL, + enabled boolean DEFAULT true NOT NULL, + api_key text, + display_order integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.tag_sources_meta ( + id boolean DEFAULT true NOT NULL, + current_version integer DEFAULT 1 NOT NULL, + last_registered_providers_hash text DEFAULT ''::text NOT NULL, + CONSTRAINT tag_sources_meta_singleton CHECK ((id = true)) +); + +CREATE TABLE public.taste_profile_artists ( + user_id uuid NOT NULL, + artist_id uuid NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_profile_eras ( + user_id uuid NOT NULL, + era text NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_profile_moods ( + user_id uuid NOT NULL, + mood text NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_profile_tags ( + user_id uuid NOT NULL, + tag text NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_tuning ( + singleton boolean DEFAULT true NOT NULL, + half_life_days double precision NOT NULL, + engagement_hard_skip double precision NOT NULL, + engagement_neutral double precision NOT NULL, + engagement_full double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + enriched_tag_scale double precision DEFAULT 0.5 NOT NULL, + era_scale double precision DEFAULT 0.5 NOT NULL, + mood_scale double precision DEFAULT 0.5 NOT NULL, + CONSTRAINT taste_tuning_singleton_check CHECK (singleton) +); + +CREATE TABLE public.track_acoustid_lookups ( + track_id uuid NOT NULL, + state text NOT NULL, + best_score real, + candidates integer DEFAULT 0 NOT NULL, + recording_mbid text, + detail text, + looked_up_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT track_acoustid_lookups_matched_has_mbid CHECK (((state = 'matched'::text) = (recording_mbid IS NOT NULL))), + CONSTRAINT track_acoustid_lookups_state_check CHECK ((state = ANY (ARRAY['matched'::text, 'ambiguous'::text, 'no_match'::text, 'failed'::text]))) +); + +CREATE TABLE public.track_fingerprints ( + track_id uuid NOT NULL, + audio_stream_sha256 bytea, + chromaprint integer[], + fingerprint_version smallint NOT NULL, + computed_at timestamp with time zone DEFAULT now() NOT NULL, + chromaprint_length_sec integer DEFAULT 120 NOT NULL, + CONSTRAINT track_fingerprints_audio_stream_sha256_check CHECK (((audio_stream_sha256 IS NULL) OR (octet_length(audio_stream_sha256) = 32))) +); + +CREATE TABLE public.track_loudness ( + track_id uuid NOT NULL, + integrated_lufs real, + true_peak_dbtp real, + loudness_range_lu real, + block_hist_start smallint, + block_hist integer[], + unreadable boolean DEFAULT false NOT NULL, + analysis_version smallint NOT NULL, + analyzed_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT track_loudness_hist_pair CHECK (((block_hist IS NULL) = (block_hist_start IS NULL))) +); + +CREATE TABLE public.track_similarity ( + track_a_id uuid NOT NULL, + track_b_id uuid NOT NULL, + score double precision NOT NULL, + source text NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT track_similarity_check CHECK ((track_a_id <> track_b_id)), + CONSTRAINT track_similarity_source_check CHECK ((source = ANY (ARRAY['listenbrainz'::text, 'musicbrainz_tag'::text, 'user_cooccurrence'::text]))) +); + +CREATE TABLE public.track_similarity_fetches ( + track_id uuid NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + returned integer NOT NULL +); + +CREATE TABLE public.track_tags ( + track_id uuid NOT NULL, + tag text NOT NULL, + weight double precision DEFAULT 1 NOT NULL +); + +CREATE TABLE public.tracks ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + title text NOT NULL, + album_id uuid NOT NULL, + artist_id uuid NOT NULL, + track_number integer, + disc_number integer, + duration_ms integer NOT NULL, + file_path text NOT NULL, + file_size bigint NOT NULL, + file_format text NOT NULL, + bitrate integer, + mbid text, + genre text, + added_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + tag_source text, + tag_sources_version integer DEFAULT 0 NOT NULL, + tag_read_version smallint DEFAULT 0 NOT NULL, + missing_since timestamp with time zone, + mbid_source text, + song_id uuid, + song_key uuid GENERATED ALWAYS AS (COALESCE(song_id, id)) STORED, + source_verdict text, + source_verdict_at timestamp with time zone, + emptied_at timestamp with time zone, + removed_reason text, + removed_by uuid, + CONSTRAINT tracks_mbid_source_check CHECK ((mbid_source = ANY (ARRAY['tag'::text, 'acoustid'::text]))), + CONSTRAINT tracks_mbid_source_pair CHECK (((mbid IS NULL) = (mbid_source IS NULL))), + CONSTRAINT tracks_removed_only_missing CHECK (((missing_since IS NOT NULL) OR ((removed_reason IS NULL) AND (removed_by IS NULL)))), + CONSTRAINT tracks_removed_reason_check CHECK ((removed_reason = ANY (ARRAY['report'::text, 'duplicate'::text, 'suspect'::text]))), + CONSTRAINT tracks_source_verdict_check CHECK ((source_verdict = ANY (ARRAY['suspect'::text, 'fine'::text]))) +); + +CREATE TABLE public.user_invites ( + token text NOT NULL, + invited_by uuid NOT NULL, + note text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + expires_at timestamp with time zone NOT NULL, + redeemed_at timestamp with time zone, + redeemed_by uuid +); + +CREATE TABLE public.user_normalization_prefs ( + user_id uuid NOT NULL, + mode text DEFAULT 'auto'::text NOT NULL, + target_lufs smallint DEFAULT '-18'::integer NOT NULL, + boost text DEFAULT 'headroom'::text NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT user_normalization_prefs_boost_check CHECK ((boost = ANY (ARRAY['headroom'::text, 'limiter'::text]))), + CONSTRAINT user_normalization_prefs_mode_check CHECK ((mode = ANY (ARRAY['off'::text, 'auto'::text, 'track'::text, 'album'::text]))), + CONSTRAINT user_normalization_prefs_target_lufs_check CHECK ((target_lufs = ANY (ARRAY['-18'::integer, '-16'::integer, '-14'::integer]))) +); + +CREATE TABLE public.user_notification_email_state ( + user_id uuid NOT NULL, + email_group text NOT NULL, + batch_opened_at timestamp with time zone, + last_sent_at timestamp with time zone, + failures integer DEFAULT 0 NOT NULL, + retry_after timestamp with time zone, + CONSTRAINT user_notification_email_state_email_group_check CHECK ((email_group = ANY (ARRAY['batch'::text, 'summary'::text]))) +); + +CREATE TABLE public.user_notification_prefs ( + user_id uuid NOT NULL, + kind text NOT NULL, + inbox boolean NOT NULL, + phone boolean NOT NULL, + email boolean NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT user_notification_prefs_kind_check CHECK ((kind = ANY (ARRAY['new_music'::text, 'quarantine_flagged'::text, 'scan_failed'::text, 'tracks_missing'::text, 'duplicates_found'::text, 'duplicates_resolved'::text, 'playback_errors'::text]))) +); + +CREATE TABLE public.user_notifications ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + kind text NOT NULL, + payload jsonb DEFAULT '{}'::jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + read_at timestamp with time zone, + coalesce_key text, + emailed_at timestamp with time zone, + CONSTRAINT user_notifications_kind_check CHECK ((kind = ANY (ARRAY['new_music'::text, 'quarantine_flagged'::text, 'scan_failed'::text, 'tracks_missing'::text, 'duplicates_found'::text, 'duplicates_resolved'::text, 'playback_errors'::text]))) +); + +CREATE TABLE public.users ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + username text NOT NULL, + password_hash text NOT NULL, + is_admin boolean DEFAULT false NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + subsonic_password text, + listenbrainz_token text, + listenbrainz_enabled boolean DEFAULT false NOT NULL, + display_name text, + email text, + timezone text DEFAULT 'UTC'::text NOT NULL, + timezone_updated_at timestamp with time zone, + debug_mode_enabled boolean DEFAULT false NOT NULL, + api_token_hash text NOT NULL +); + +CREATE TABLE public.you_might_like_albums ( + user_id uuid NOT NULL, + album_id uuid NOT NULL, + rank integer NOT NULL, + built_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.you_might_like_artists ( + user_id uuid NOT NULL, + artist_id uuid NOT NULL, + rank integer NOT NULL, + built_at timestamp with time zone DEFAULT now() NOT NULL +); + +ALTER TABLE ONLY public.library_changes ALTER COLUMN id SET DEFAULT nextval('public.library_changes_id_seq'::regclass); + +ALTER TABLE ONLY public.recommendation_tuning_audit ALTER COLUMN id SET DEFAULT nextval('public.recommendation_tuning_audit_id_seq'::regclass); + +INSERT INTO public.acoustid_settings (id, enabled, api_key, min_score, updated_at) VALUES (true, false, NULL, 0.85, now()); + +INSERT INTO public.backup_settings (id, enabled, destination, folder, endpoint, bucket, access_key, secret_key, run_hour, upload_limit_kib, updated_at, include_music) VALUES (true, false, 's3', '', '', '', '', '', 3, 4096, now(), false); + +INSERT INTO public.cover_art_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('mbcaa', true, NULL, 0, now(), now()); +INSERT INTO public.cover_art_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('theaudiodb', true, NULL, 1, now(), now()); + +INSERT INTO public.cover_art_sources_meta (id, current_version, last_registered_providers_hash) VALUES (true, 1, ''); + +INSERT INTO public.fingerprint_settings (id, enabled, chromaprint_length_sec, acoustic_max_bit_error_rate, backfill_concurrency, sweep_interval_hours, updated_at, auto_resolve) VALUES (true, true, 120, 0.15, 2, 1, now(), true); + +INSERT INTO public.library_changes_trimmed (id, through) VALUES (true, 0); + +INSERT INTO public.library_settings (id, scan_paths, updated_at) VALUES (true, NULL, now()); + +INSERT INTO public.loudness_settings (id, enabled, backfill_concurrency, updated_at, leveled_cache_mb) VALUES (true, true, 2, now(), 2048); + +INSERT INTO public.network_settings (id, trusted_proxy_hops, public_url) VALUES (true, 1, ''); + +INSERT INTO public.notification_email_settings (id, summary_hour, batch_window_minutes, updated_at) VALUES (true, 9, 60, now()); + +INSERT INTO public.registration_settings (id, mode) VALUES (true, 'invite_only'); + +INSERT INTO public.smtp_config (id, enabled, host, port, username, password, from_address, from_name, use_tls, updated_at) VALUES (true, false, '', 587, '', '', '', 'Minstrel', true, now()); + +INSERT INTO public.tag_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('musicbrainz', true, NULL, 0, now(), now()); +INSERT INTO public.tag_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('lastfm', false, NULL, 1, now(), now()); + +INSERT INTO public.tag_sources_meta (id, current_version, last_registered_providers_hash) VALUES (true, 1, ''); + +SELECT pg_catalog.setval('public.library_changes_id_seq', 1, false); + +SELECT pg_catalog.setval('public.recommendation_tuning_audit_id_seq', 1, false); + +ALTER TABLE ONLY public.acoustid_settings + ADD CONSTRAINT acoustid_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.album_loudness + ADD CONSTRAINT album_loudness_pkey PRIMARY KEY (album_id); + +ALTER TABLE ONLY public.albums + ADD CONSTRAINT albums_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.artist_similarity_fetches + ADD CONSTRAINT artist_similarity_fetches_pkey PRIMARY KEY (artist_id); + +ALTER TABLE ONLY public.artist_similarity + ADD CONSTRAINT artist_similarity_pkey PRIMARY KEY (artist_a_id, artist_b_id, source); + +ALTER TABLE ONLY public.artists + ADD CONSTRAINT artists_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.audit_log + ADD CONSTRAINT audit_log_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.backup_music_files + ADD CONSTRAINT backup_music_files_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.backup_runs + ADD CONSTRAINT backup_runs_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.backup_settings + ADD CONSTRAINT backup_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.cover_art_provider_settings + ADD CONSTRAINT cover_art_provider_settings_pkey PRIMARY KEY (provider_id); + +ALTER TABLE ONLY public.cover_art_sources_meta + ADD CONSTRAINT cover_art_sources_meta_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.diagnostic_events + ADD CONSTRAINT diagnostic_events_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.duplicate_group_members + ADD CONSTRAINT duplicate_group_members_pkey PRIMARY KEY (group_id, track_id); + +ALTER TABLE ONLY public.duplicate_groups + ADD CONSTRAINT duplicate_groups_member_key_key UNIQUE (member_key); + +ALTER TABLE ONLY public.duplicate_groups + ADD CONSTRAINT duplicate_groups_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.duplicate_sweeps + ADD CONSTRAINT duplicate_sweeps_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.fingerprint_settings + ADD CONSTRAINT fingerprint_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.general_likes_albums + ADD CONSTRAINT general_likes_albums_pkey PRIMARY KEY (user_id, album_id); + +ALTER TABLE ONLY public.general_likes_artists + ADD CONSTRAINT general_likes_artists_pkey PRIMARY KEY (user_id, artist_id); + +ALTER TABLE ONLY public.general_likes + ADD CONSTRAINT general_likes_pkey PRIMARY KEY (user_id, track_id); + +ALTER TABLE ONLY public.library_changes + ADD CONSTRAINT library_changes_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.library_changes_trimmed + ADD CONSTRAINT library_changes_trimmed_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.library_settings + ADD CONSTRAINT library_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.listenbrainz_similar_recordings + ADD CONSTRAINT listenbrainz_similar_recordings_pkey PRIMARY KEY (seed_track_id, recording_mbid); + +ALTER TABLE ONLY public.loudness_settings + ADD CONSTRAINT loudness_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.mb_release_groups + ADD CONSTRAINT mb_release_groups_pkey PRIMARY KEY (mbid); + +ALTER TABLE ONLY public.mb_release_tracks + ADD CONSTRAINT mb_release_tracks_pkey PRIMARY KEY (release_mbid, medium_position, "position"); + +ALTER TABLE ONLY public.mb_releases + ADD CONSTRAINT mb_releases_pkey PRIMARY KEY (mbid); + +ALTER TABLE ONLY public.network_settings + ADD CONSTRAINT network_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.notification_email_settings + ADD CONSTRAINT notification_email_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.password_resets + ADD CONSTRAINT password_resets_pkey PRIMARY KEY (token); + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.play_sessions + ADD CONSTRAINT play_sessions_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.playlist_tracks + ADD CONSTRAINT playlist_tracks_pkey PRIMARY KEY (playlist_id, "position"); + +ALTER TABLE ONLY public.playlists + ADD CONSTRAINT playlists_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.quarantine_actions + ADD CONSTRAINT quarantine_actions_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.quarantine + ADD CONSTRAINT quarantine_pkey PRIMARY KEY (user_id, track_id); + +ALTER TABLE ONLY public.recommendation_tuning_audit + ADD CONSTRAINT recommendation_tuning_audit_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.recommendation_weight_profiles + ADD CONSTRAINT recommendation_weight_profiles_pkey PRIMARY KEY (profile); + +ALTER TABLE ONLY public.registration_settings + ADD CONSTRAINT registration_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.scan_runs + ADD CONSTRAINT scan_runs_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_play_event_id_key UNIQUE (play_event_id); + +ALTER TABLE ONLY public.sessions + ADD CONSTRAINT sessions_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.sessions + ADD CONSTRAINT sessions_token_hash_key UNIQUE (token_hash); + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.smtp_config + ADD CONSTRAINT smtp_config_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.system_playlist_rotation_state + ADD CONSTRAINT system_playlist_rotation_state_pkey PRIMARY KEY (user_id, playlist_kind); + +ALTER TABLE ONLY public.system_playlist_runs + ADD CONSTRAINT system_playlist_runs_pkey PRIMARY KEY (user_id); + +ALTER TABLE ONLY public.tag_provider_settings + ADD CONSTRAINT tag_provider_settings_pkey PRIMARY KEY (provider_id); + +ALTER TABLE ONLY public.tag_sources_meta + ADD CONSTRAINT tag_sources_meta_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.taste_profile_artists + ADD CONSTRAINT taste_profile_artists_pkey PRIMARY KEY (user_id, artist_id); + +ALTER TABLE ONLY public.taste_profile_eras + ADD CONSTRAINT taste_profile_eras_pkey PRIMARY KEY (user_id, era); + +ALTER TABLE ONLY public.taste_profile_moods + ADD CONSTRAINT taste_profile_moods_pkey PRIMARY KEY (user_id, mood); + +ALTER TABLE ONLY public.taste_profile_tags + ADD CONSTRAINT taste_profile_tags_pkey PRIMARY KEY (user_id, tag); + +ALTER TABLE ONLY public.taste_tuning + ADD CONSTRAINT taste_tuning_pkey PRIMARY KEY (singleton); + +ALTER TABLE ONLY public.track_acoustid_lookups + ADD CONSTRAINT track_acoustid_lookups_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_fingerprints + ADD CONSTRAINT track_fingerprints_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_loudness + ADD CONSTRAINT track_loudness_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_similarity_fetches + ADD CONSTRAINT track_similarity_fetches_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_similarity + ADD CONSTRAINT track_similarity_pkey PRIMARY KEY (track_a_id, track_b_id, source); + +ALTER TABLE ONLY public.track_tags + ADD CONSTRAINT track_tags_pkey PRIMARY KEY (track_id, tag); + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_file_path_key UNIQUE (file_path); + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.user_invites + ADD CONSTRAINT user_invites_pkey PRIMARY KEY (token); + +ALTER TABLE ONLY public.user_normalization_prefs + ADD CONSTRAINT user_normalization_prefs_pkey PRIMARY KEY (user_id); + +ALTER TABLE ONLY public.user_notification_email_state + ADD CONSTRAINT user_notification_email_state_pkey PRIMARY KEY (user_id, email_group); + +ALTER TABLE ONLY public.user_notification_prefs + ADD CONSTRAINT user_notification_prefs_pkey PRIMARY KEY (user_id, kind); + +ALTER TABLE ONLY public.user_notifications + ADD CONSTRAINT user_notifications_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_api_token_hash_key UNIQUE (api_token_hash); + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_username_key UNIQUE (username); + +ALTER TABLE ONLY public.you_might_like_albums + ADD CONSTRAINT you_might_like_albums_pkey PRIMARY KEY (user_id, album_id); + +ALTER TABLE ONLY public.you_might_like_artists + ADD CONSTRAINT you_might_like_artists_pkey PRIMARY KEY (user_id, artist_id); + +CREATE INDEX albums_artist ON public.albums USING btree (artist_id); + +CREATE INDEX albums_cover_art_source_idx ON public.albums USING btree (cover_art_source); + +CREATE UNIQUE INDEX albums_mbid_unique ON public.albums USING btree (mbid) WHERE (mbid IS NOT NULL); + +CREATE INDEX albums_release_group_mbid_idx ON public.albums USING btree (release_group_mbid) WHERE (release_group_mbid IS NOT NULL); + +CREATE INDEX albums_sort_title ON public.albums USING btree (sort_title); + +CREATE INDEX artist_similarity_a_score_idx ON public.artist_similarity USING btree (artist_a_id, score DESC); + +CREATE INDEX artists_artist_art_source_idx ON public.artists USING btree (artist_art_source); + +CREATE UNIQUE INDEX artists_mbid_unique ON public.artists USING btree (mbid) WHERE (mbid IS NOT NULL); + +CREATE INDEX artists_sort_name ON public.artists USING btree (sort_name); + +CREATE INDEX audit_log_actor_id_idx ON public.audit_log USING btree (actor_id); + +CREATE INDEX audit_log_created_at_idx ON public.audit_log USING btree (created_at DESC); + +CREATE INDEX audit_log_target_id_idx ON public.audit_log USING btree (target_id); + +CREATE INDEX backup_runs_started_at_idx ON public.backup_runs USING btree (started_at DESC); + +CREATE INDEX contextual_likes_active_idx ON public.contextual_likes USING btree (user_id, track_id) WHERE (deleted_at IS NULL); + +CREATE INDEX contextual_likes_vector_idx ON public.contextual_likes USING gin (session_vector); + +CREATE INDEX duplicate_group_members_track_idx ON public.duplicate_group_members USING btree (track_id); + +CREATE INDEX duplicate_groups_status_idx ON public.duplicate_groups USING btree (status); + +CREATE INDEX duplicate_sweeps_started_at_idx ON public.duplicate_sweeps USING btree (started_at DESC); + +CREATE INDEX general_likes_albums_user_liked_at_idx ON public.general_likes_albums USING btree (user_id, liked_at DESC); + +CREATE INDEX general_likes_artists_user_liked_at_idx ON public.general_likes_artists USING btree (user_id, liked_at DESC); + +CREATE INDEX general_likes_user_liked_at_idx ON public.general_likes USING btree (user_id, liked_at DESC); + +CREATE INDEX idx_diagnostic_events_client ON public.diagnostic_events USING btree (client_id, occurred_at DESC); + +CREATE INDEX idx_diagnostic_events_received ON public.diagnostic_events USING btree (received_at); + +CREATE INDEX idx_diagnostic_events_user ON public.diagnostic_events USING btree (user_id, occurred_at DESC); + +CREATE INDEX idx_library_changes_entity ON public.library_changes USING btree (entity_type, entity_id, id DESC); + +CREATE INDEX idx_library_changes_id ON public.library_changes USING btree (id); + +CREATE INDEX idx_playback_errors_track ON public.playback_errors USING btree (track_id); + +CREATE INDEX idx_playback_errors_unresolved ON public.playback_errors USING btree (occurred_at DESC) WHERE (resolved_at IS NULL); + +CREATE INDEX listenbrainz_similar_recordings_mbid_idx ON public.listenbrainz_similar_recordings USING btree (recording_mbid); + +CREATE INDEX mb_release_tracks_recording_idx ON public.mb_release_tracks USING btree (recording_mbid) WHERE (recording_mbid <> ''::text); + +CREATE INDEX mb_releases_group_idx ON public.mb_releases USING btree (release_group_mbid); + +CREATE INDEX password_resets_active_idx ON public.password_resets USING btree (expires_at) WHERE (used_at IS NULL); + +CREATE INDEX password_resets_user_id_idx ON public.password_resets USING btree (user_id); + +CREATE INDEX play_events_started_idx ON public.play_events USING btree (started_at); + +CREATE INDEX play_events_track_idx ON public.play_events USING btree (track_id); + +CREATE INDEX play_events_user_started_idx ON public.play_events USING btree (user_id, started_at DESC); + +CREATE INDEX play_events_user_track_idx ON public.play_events USING btree (user_id, track_id); + +CREATE INDEX play_sessions_user_last_event_idx ON public.play_sessions USING btree (user_id, last_event_at DESC); + +CREATE INDEX playlist_tracks_track_idx ON public.playlist_tracks USING btree (track_id) WHERE (track_id IS NOT NULL); + +CREATE INDEX playlists_public_idx ON public.playlists USING btree (is_public, updated_at DESC) WHERE is_public; + +CREATE INDEX playlists_user_idx ON public.playlists USING btree (user_id, updated_at DESC); + +CREATE INDEX playlists_user_kind_idx ON public.playlists USING btree (user_id, kind); + +CREATE INDEX quarantine_actions_created_idx ON public.quarantine_actions USING btree (created_at DESC); + +CREATE INDEX quarantine_actions_track_idx ON public.quarantine_actions USING btree (track_id); + +CREATE INDEX quarantine_track_idx ON public.quarantine USING btree (track_id); + +CREATE INDEX recommendation_tuning_audit_changed_at_idx ON public.recommendation_tuning_audit USING btree (changed_at DESC); + +CREATE INDEX scan_runs_started_at_idx ON public.scan_runs USING btree (started_at DESC); + +CREATE INDEX scrobble_queue_pending_idx ON public.scrobble_queue USING btree (next_attempt_at) WHERE (status = 'pending'::text); + +CREATE INDEX sessions_user_id_idx ON public.sessions USING btree (user_id); + +CREATE INDEX skip_events_user_skipped_idx ON public.skip_events USING btree (user_id, skipped_at DESC); + +CREATE INDEX taste_profile_artists_user_weight_idx ON public.taste_profile_artists USING btree (user_id, weight DESC); + +CREATE INDEX taste_profile_eras_user_weight_idx ON public.taste_profile_eras USING btree (user_id, weight DESC); + +CREATE INDEX taste_profile_moods_user_weight_idx ON public.taste_profile_moods USING btree (user_id, weight DESC); + +CREATE INDEX taste_profile_tags_user_weight_idx ON public.taste_profile_tags USING btree (user_id, weight DESC); + +CREATE INDEX track_acoustid_lookups_state ON public.track_acoustid_lookups USING btree (state); + +CREATE INDEX track_fingerprints_audio_stream_sha256 ON public.track_fingerprints USING btree (audio_stream_sha256) WHERE (audio_stream_sha256 IS NOT NULL); + +CREATE INDEX track_similarity_a_score_idx ON public.track_similarity USING btree (track_a_id, score DESC); + +CREATE INDEX track_tags_track_idx ON public.track_tags USING btree (track_id); + +CREATE INDEX tracks_album ON public.tracks USING btree (album_id, disc_number, track_number); + +CREATE INDEX tracks_artist ON public.tracks USING btree (artist_id); + +CREATE INDEX tracks_duration_id_idx ON public.tracks USING btree (duration_ms, id); + +CREATE INDEX tracks_mbid_idx ON public.tracks USING btree (mbid) WHERE (mbid IS NOT NULL); + +CREATE INDEX tracks_missing_since_idx ON public.tracks USING btree (missing_since) WHERE (missing_since IS NOT NULL); + +CREATE INDEX tracks_song_key_idx ON public.tracks USING btree (song_key); + +CREATE INDEX tracks_source_suspect_idx ON public.tracks USING btree (id) WHERE (source_verdict = 'suspect'::text); + +CREATE INDEX tracks_tag_source_idx ON public.tracks USING btree (tag_source, tag_sources_version); + +CREATE INDEX user_invites_active_idx ON public.user_invites USING btree (expires_at) WHERE (redeemed_at IS NULL); + +CREATE UNIQUE INDEX user_notifications_coalesce_idx ON public.user_notifications USING btree (user_id, coalesce_key) WHERE ((read_at IS NULL) AND (coalesce_key IS NOT NULL)); + +CREATE INDEX user_notifications_email_pending_idx ON public.user_notifications USING btree (user_id, created_at) WHERE ((read_at IS NULL) AND (emailed_at IS NULL)); + +CREATE INDEX user_notifications_unread_idx ON public.user_notifications USING btree (user_id, created_at DESC) WHERE (read_at IS NULL); + +CREATE INDEX user_notifications_user_created_idx ON public.user_notifications USING btree (user_id, created_at DESC); + +CREATE UNIQUE INDEX users_email_unique ON public.users USING btree (lower(email)) WHERE (email IS NOT NULL); + +CREATE INDEX you_might_like_albums_user_rank_idx ON public.you_might_like_albums USING btree (user_id, rank); + +CREATE INDEX you_might_like_artists_user_rank_idx ON public.you_might_like_artists USING btree (user_id, rank); + +ALTER TABLE ONLY public.album_loudness + ADD CONSTRAINT album_loudness_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.albums + ADD CONSTRAINT albums_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.artist_similarity + ADD CONSTRAINT artist_similarity_artist_a_id_fkey FOREIGN KEY (artist_a_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.artist_similarity + ADD CONSTRAINT artist_similarity_artist_b_id_fkey FOREIGN KEY (artist_b_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.artist_similarity_fetches + ADD CONSTRAINT artist_similarity_fetches_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.audit_log + ADD CONSTRAINT audit_log_actor_id_fkey FOREIGN KEY (actor_id) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.audit_log + ADD CONSTRAINT audit_log_target_id_fkey FOREIGN KEY (target_id) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.backup_music_files + ADD CONSTRAINT backup_music_files_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_session_id_fkey FOREIGN KEY (session_id) REFERENCES public.play_sessions(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.diagnostic_events + ADD CONSTRAINT diagnostic_events_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.duplicate_group_members + ADD CONSTRAINT duplicate_group_members_group_id_fkey FOREIGN KEY (group_id) REFERENCES public.duplicate_groups(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.duplicate_group_members + ADD CONSTRAINT duplicate_group_members_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.duplicate_groups + ADD CONSTRAINT duplicate_groups_last_seen_sweep_id_fkey FOREIGN KEY (last_seen_sweep_id) REFERENCES public.duplicate_sweeps(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.general_likes_albums + ADD CONSTRAINT general_likes_albums_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes_albums + ADD CONSTRAINT general_likes_albums_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes_artists + ADD CONSTRAINT general_likes_artists_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes_artists + ADD CONSTRAINT general_likes_artists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes + ADD CONSTRAINT general_likes_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes + ADD CONSTRAINT general_likes_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.listenbrainz_similar_recordings + ADD CONSTRAINT listenbrainz_similar_recordings_seed_track_id_fkey FOREIGN KEY (seed_track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.mb_release_tracks + ADD CONSTRAINT mb_release_tracks_release_mbid_fkey FOREIGN KEY (release_mbid) REFERENCES public.mb_releases(mbid) ON DELETE CASCADE; + +ALTER TABLE ONLY public.mb_releases + ADD CONSTRAINT mb_releases_release_group_mbid_fkey FOREIGN KEY (release_group_mbid) REFERENCES public.mb_release_groups(mbid) ON DELETE CASCADE; + +ALTER TABLE ONLY public.password_resets + ADD CONSTRAINT password_resets_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_session_id_fkey FOREIGN KEY (session_id) REFERENCES public.play_sessions(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_sessions + ADD CONSTRAINT play_sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_resolved_by_fkey FOREIGN KEY (resolved_by) REFERENCES public.users(id); + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playlist_tracks + ADD CONSTRAINT playlist_tracks_playlist_id_fkey FOREIGN KEY (playlist_id) REFERENCES public.playlists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playlist_tracks + ADD CONSTRAINT playlist_tracks_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.playlists + ADD CONSTRAINT playlists_seed_artist_id_fkey FOREIGN KEY (seed_artist_id) REFERENCES public.artists(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.playlists + ADD CONSTRAINT playlists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.quarantine_actions + ADD CONSTRAINT quarantine_actions_admin_id_fkey FOREIGN KEY (admin_id) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.quarantine + ADD CONSTRAINT quarantine_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.quarantine + ADD CONSTRAINT quarantine_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_play_event_id_fkey FOREIGN KEY (play_event_id) REFERENCES public.play_events(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.sessions + ADD CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_session_id_fkey FOREIGN KEY (session_id) REFERENCES public.play_sessions(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.system_playlist_rotation_state + ADD CONSTRAINT system_playlist_rotation_state_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.system_playlist_runs + ADD CONSTRAINT system_playlist_runs_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_artists + ADD CONSTRAINT taste_profile_artists_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_artists + ADD CONSTRAINT taste_profile_artists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_eras + ADD CONSTRAINT taste_profile_eras_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_moods + ADD CONSTRAINT taste_profile_moods_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_tags + ADD CONSTRAINT taste_profile_tags_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_acoustid_lookups + ADD CONSTRAINT track_acoustid_lookups_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_fingerprints + ADD CONSTRAINT track_fingerprints_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_loudness + ADD CONSTRAINT track_loudness_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_similarity_fetches + ADD CONSTRAINT track_similarity_fetches_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_similarity + ADD CONSTRAINT track_similarity_track_a_id_fkey FOREIGN KEY (track_a_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_similarity + ADD CONSTRAINT track_similarity_track_b_id_fkey FOREIGN KEY (track_b_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_tags + ADD CONSTRAINT track_tags_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_removed_by_fkey FOREIGN KEY (removed_by) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.user_invites + ADD CONSTRAINT user_invites_invited_by_fkey FOREIGN KEY (invited_by) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_invites + ADD CONSTRAINT user_invites_redeemed_by_fkey FOREIGN KEY (redeemed_by) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.user_normalization_prefs + ADD CONSTRAINT user_normalization_prefs_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_notification_email_state + ADD CONSTRAINT user_notification_email_state_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_notification_prefs + ADD CONSTRAINT user_notification_prefs_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_notifications + ADD CONSTRAINT user_notifications_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_albums + ADD CONSTRAINT you_might_like_albums_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_albums + ADD CONSTRAINT you_might_like_albums_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_artists + ADD CONSTRAINT you_might_like_artists_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_artists + ADD CONSTRAINT you_might_like_artists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; diff --git a/internal/db/migrations/0107_playlist_shelf_rank.down.sql b/internal/db/migrations/0107_playlist_shelf_rank.down.sql new file mode 100644 index 00000000..8c599531 --- /dev/null +++ b/internal/db/migrations/0107_playlist_shelf_rank.down.sql @@ -0,0 +1 @@ +ALTER TABLE playlists DROP COLUMN shelf_rank; diff --git a/internal/db/migrations/0107_playlist_shelf_rank.up.sql b/internal/db/migrations/0107_playlist_shelf_rank.up.sql new file mode 100644 index 00000000..6b4d5d00 --- /dev/null +++ b/internal/db/migrations/0107_playlist_shelf_rank.up.sql @@ -0,0 +1,6 @@ +-- Where a system mix sits on its Home shelf, 1 first. The genre mix builder +-- numbers its mixes by how much the user listens to each genre, so the +-- "Your genres" shelf leads with their main genres rather than reading +-- A to Z. 0 means unranked: every other playlist, which clients order their +-- own way. +ALTER TABLE playlists ADD COLUMN shelf_rank integer NOT NULL DEFAULT 0; diff --git a/internal/db/migrations/0108_track_artist_credit.down.sql b/internal/db/migrations/0108_track_artist_credit.down.sql new file mode 100644 index 00000000..e11d891b --- /dev/null +++ b/internal/db/migrations/0108_track_artist_credit.down.sql @@ -0,0 +1 @@ +ALTER TABLE tracks DROP COLUMN artist_credit; diff --git a/internal/db/migrations/0108_track_artist_credit.up.sql b/internal/db/migrations/0108_track_artist_credit.up.sql new file mode 100644 index 00000000..51aa6067 --- /dev/null +++ b/internal/db/migrations/0108_track_artist_credit.up.sql @@ -0,0 +1,6 @@ +-- The artist credit a track's tags give when it names more than its filing +-- artist: "Low Tide Choir feat. Ruby Calloway", or a collaboration the file +-- lists artist by artist. The track is filed under the first artist, so the +-- guest does not become an artist of their own, and this text is what a +-- listener sees beside the track. NULL when the credit is the artist's name. +ALTER TABLE tracks ADD COLUMN artist_credit text; diff --git a/internal/db/migrations/0109_play_queues.down.sql b/internal/db/migrations/0109_play_queues.down.sql new file mode 100644 index 00000000..53291db5 --- /dev/null +++ b/internal/db/migrations/0109_play_queues.down.sql @@ -0,0 +1 @@ +DROP TABLE play_queues; diff --git a/internal/db/migrations/0109_play_queues.up.sql b/internal/db/migrations/0109_play_queues.up.sql new file mode 100644 index 00000000..67cae4a6 --- /dev/null +++ b/internal/db/migrations/0109_play_queues.up.sql @@ -0,0 +1,14 @@ +-- The play queue a Subsonic app saves (savePlayQueue) so another app or +-- device can pick up where it left off (getPlayQueue): one queue per user, +-- the songs in order, the one playing and how far into it. track_ids is not +-- a foreign key: a song removed from the library drops out of the queue +-- when it is read, rather than blocking the removal. +CREATE TABLE play_queues ( + user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + track_ids uuid[] NOT NULL DEFAULT '{}', + current_track_id uuid, + position_ms bigint NOT NULL DEFAULT 0, + changed_at timestamptz NOT NULL DEFAULT now(), + -- The app that saved it, from the Subsonic c parameter. + changed_by text NOT NULL DEFAULT '' +); diff --git a/internal/db/migrations/0110_drop_registration_settings.down.sql b/internal/db/migrations/0110_drop_registration_settings.down.sql new file mode 100644 index 00000000..1416c12c --- /dev/null +++ b/internal/db/migrations/0110_drop_registration_settings.down.sql @@ -0,0 +1,7 @@ +CREATE TABLE registration_settings ( + id boolean DEFAULT true NOT NULL PRIMARY KEY, + mode text DEFAULT 'invite_only'::text NOT NULL, + CONSTRAINT registration_settings_mode_check CHECK ((mode = ANY (ARRAY['invite_only'::text, 'open'::text]))), + CONSTRAINT registration_settings_singleton CHECK ((id = true)) +); +INSERT INTO registration_settings (id, mode) VALUES (true, 'invite_only'); diff --git a/internal/db/migrations/0110_drop_registration_settings.up.sql b/internal/db/migrations/0110_drop_registration_settings.up.sql new file mode 100644 index 00000000..1581bbcf --- /dev/null +++ b/internal/db/migrations/0110_drop_registration_settings.up.sql @@ -0,0 +1,4 @@ +-- An account needs an invite from an admin; the first account needs the +-- setup token from the server log. There is no open registration, so the +-- setting that would have chosen between the two is gone. +DROP TABLE registration_settings; diff --git a/internal/db/migrations/0111_lookup_settings.down.sql b/internal/db/migrations/0111_lookup_settings.down.sql new file mode 100644 index 00000000..f4afec89 --- /dev/null +++ b/internal/db/migrations/0111_lookup_settings.down.sql @@ -0,0 +1 @@ +DROP TABLE lookup_settings; diff --git a/internal/db/migrations/0111_lookup_settings.up.sql b/internal/db/migrations/0111_lookup_settings.up.sql new file mode 100644 index 00000000..fdf7831f --- /dev/null +++ b/internal/db/migrations/0111_lookup_settings.up.sql @@ -0,0 +1,12 @@ +-- Switches for the two outside lookups that no source under Admin › Metadata +-- sources covers: ListenBrainz's similar songs and artists, which radio and +-- the mixes draw on, and MusicBrainz's album track lists, which the duplicate +-- resolver reads to tell a song filed in the wrong slot from a repeat. Both +-- start on; turning one off keeps what was already fetched. +CREATE TABLE lookup_settings ( + id boolean PRIMARY KEY DEFAULT true CHECK (id), + listenbrainz_similarity boolean NOT NULL DEFAULT true, + musicbrainz_track_lists boolean NOT NULL DEFAULT true, + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO lookup_settings (id) VALUES (true); diff --git a/internal/db/migrations/0112_sync_log_library_only.down.sql b/internal/db/migrations/0112_sync_log_library_only.down.sql new file mode 100644 index 00000000..dbd9391d --- /dev/null +++ b/internal/db/migrations/0112_sync_log_library_only.down.sql @@ -0,0 +1,2 @@ +-- The cleared rows were never read; there is nothing to put back. +SELECT 1; diff --git a/internal/db/migrations/0112_sync_log_library_only.up.sql b/internal/db/migrations/0112_sync_log_library_only.up.sql new file mode 100644 index 00000000..c5043a44 --- /dev/null +++ b/internal/db/migrations/0112_sync_log_library_only.up.sql @@ -0,0 +1,7 @@ +-- The delta sync (GET /api/library/sync) carries the shared library only: +-- artists, albums and tracks. Likes and playlists reach the apps through +-- their own endpoints and live events, so their rows here were written and +-- never read. Clear them. The entity_type check still admits the old +-- values, so a backup from before this change still restores; nothing +-- writes them any more. +DELETE FROM library_changes WHERE entity_type NOT IN ('artist', 'album', 'track'); diff --git a/internal/db/migrations/0113_playlist_append_requests.down.sql b/internal/db/migrations/0113_playlist_append_requests.down.sql new file mode 100644 index 00000000..b05f6403 --- /dev/null +++ b/internal/db/migrations/0113_playlist_append_requests.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS playlist_append_requests; diff --git a/internal/db/migrations/0113_playlist_append_requests.up.sql b/internal/db/migrations/0113_playlist_append_requests.up.sql new file mode 100644 index 00000000..a33af9fb --- /dev/null +++ b/internal/db/migrations/0113_playlist_append_requests.up.sql @@ -0,0 +1,13 @@ +-- An append the phone sent but never heard back about (a timeout, the app +-- killed mid-request) stays in its offline queue and is sent again. An +-- append is an action, not a state, so the second send would add the songs +-- a second time. The phone now names each append with a request id, and +-- the server keeps the ids it has applied here: a send whose id is already +-- recorded for the playlist changes nothing. Rows older than 30 days are +-- pruned as new appends arrive; a queued write is replayed long before that. +CREATE TABLE playlist_append_requests ( + playlist_id uuid NOT NULL REFERENCES playlists(id) ON DELETE CASCADE, + request_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (playlist_id, request_id) +); diff --git a/internal/db/migrations/0114_auto_resolve_off_by_default.down.sql b/internal/db/migrations/0114_auto_resolve_off_by_default.down.sql new file mode 100644 index 00000000..a36330d0 --- /dev/null +++ b/internal/db/migrations/0114_auto_resolve_off_by_default.down.sql @@ -0,0 +1 @@ +ALTER TABLE fingerprint_settings ALTER COLUMN auto_resolve SET DEFAULT true; diff --git a/internal/db/migrations/0114_auto_resolve_off_by_default.up.sql b/internal/db/migrations/0114_auto_resolve_off_by_default.up.sql new file mode 100644 index 00000000..8c1cb1d9 --- /dev/null +++ b/internal/db/migrations/0114_auto_resolve_off_by_default.up.sql @@ -0,0 +1,9 @@ +-- Duplicate auto-resolve starts off. Other programs file music into the +-- library, so Minstrel acts on duplicates only once an admin has turned this +-- on. The pass never removes a file either way: on, it links copies of one +-- song so they count once and notes which song a misfiled recording is. +-- +-- Installs that never chose a value hold the old default, true, and are set +-- off here too; an admin who wants it turns it back on. +ALTER TABLE fingerprint_settings ALTER COLUMN auto_resolve SET DEFAULT false; +UPDATE fingerprint_settings SET auto_resolve = false; diff --git a/internal/db/queries/acoustid.sql b/internal/db/queries/acoustid.sql index cb677a6c..22a4eca0 100644 --- a/internal/db/queries/acoustid.sql +++ b/internal/db/queries/acoustid.sql @@ -1,5 +1,5 @@ --- AcoustID recording-id lookup. Migration 0069 says what each --- lookup state means. +-- AcoustID recording-id lookup. The CHECK on track_acoustid_lookups.state +-- lists the lookup states. -- name: ListTracksNeedingAcoustIDLookup :many -- The lookup worker's queue: present tracks with no tag MBID and no lookup diff --git a/internal/db/queries/acquisition.sql b/internal/db/queries/acquisition.sql deleted file mode 100644 index 82e11b15..00000000 --- a/internal/db/queries/acquisition.sql +++ /dev/null @@ -1,76 +0,0 @@ --- Indexers and download clients. - --- name: ListAcquisitionServices :many --- Returns no secret, only whether one is set: this feeds the settings page. -SELECT code, kind, protocol, label, enabled, base_url, - (api_key <> '')::boolean AS has_api_key, - (password <> '')::boolean AS has_password, - username, category, timeout_ms, - serves_search, serves_downloads, serves_enrichment, - local_path, remote_path, searches_per_hour, - created_at, updated_at -FROM acquisition_services -ORDER BY kind, label, code; - --- name: GetAcquisitionService :one --- The full row, credentials included. For building a client, never for a --- response. -SELECT * FROM acquisition_services WHERE code = sqlc.arg(code); - --- name: ListUsableAcquisitionServices :many --- Every enabled, addressed service doing one job. An exchange row does a job --- when its switch for it is on; any other row does the job its kind names. --- Ordered by code so a fan-out is deterministic. -SELECT * FROM acquisition_services -WHERE enabled AND base_url <> '' - AND CASE WHEN protocol = 'exchange' THEN - CASE sqlc.arg(job)::text - WHEN 'search' THEN serves_search - WHEN 'download' THEN serves_downloads - WHEN 'enrichment' THEN serves_enrichment - ELSE false - END - ELSE kind = sqlc.arg(job)::text - END -ORDER BY code; - --- name: CreateAcquisitionService :one --- ON CONFLICT so the caller can try the next code when this one is taken. -INSERT INTO acquisition_services - (code, kind, protocol, label, category, timeout_ms, searches_per_hour) -VALUES - (sqlc.arg(code), sqlc.arg(kind), sqlc.arg(protocol), sqlc.arg(label), - sqlc.arg(category), sqlc.arg(timeout_ms), sqlc.arg(searches_per_hour)) -ON CONFLICT (code) DO NOTHING -RETURNING *; - --- name: UpdateAcquisitionService :one --- Everything on the settings form except the credentials, which have their --- own write-only calls. -UPDATE acquisition_services SET - label = sqlc.arg(label), - enabled = sqlc.arg(enabled), - base_url = sqlc.arg(base_url), - username = sqlc.arg(username), - category = sqlc.arg(category), - timeout_ms = sqlc.arg(timeout_ms), - serves_search = sqlc.arg(serves_search), - serves_downloads = sqlc.arg(serves_downloads), - serves_enrichment = sqlc.arg(serves_enrichment), - local_path = sqlc.arg(local_path), - remote_path = sqlc.arg(remote_path), - searches_per_hour = sqlc.arg(searches_per_hour), - updated_at = now() -WHERE code = sqlc.arg(code) -RETURNING *; - --- name: DeleteAcquisitionService :execrows -DELETE FROM acquisition_services WHERE code = sqlc.arg(code); - --- name: SetAcquisitionServiceAPIKey :execrows -UPDATE acquisition_services SET api_key = sqlc.arg(api_key), updated_at = now() -WHERE code = sqlc.arg(code); - --- name: SetAcquisitionServicePassword :execrows -UPDATE acquisition_services SET password = sqlc.arg(password), updated_at = now() -WHERE code = sqlc.arg(code); diff --git a/internal/db/queries/admin_status.sql b/internal/db/queries/admin_status.sql index e36b2a37..95471f56 100644 --- a/internal/db/queries/admin_status.sql +++ b/internal/db/queries/admin_status.sql @@ -1,5 +1,5 @@ --- The admin Overview's status sections: who is listening, what is --- downloading, what the library holds. Each is one cheap read. +-- The admin Overview's status sections: who is listening and what the +-- library holds. Each is one cheap read. -- name: ListListeningNow :many -- Plays in progress: open play events still inside their track's length, @@ -29,20 +29,6 @@ SELECT COUNT(*)::bigint AS plays, FROM play_events WHERE started_at > now() - INTERVAL '24 hours'; --- name: DownloadsStatus :one --- Downloads at a glance: running, waiting on a person (and since when), and --- the last day's imports and give-ups. -SELECT COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting', 'importing'))::bigint AS running, - COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::bigint AS needs_you, - MIN(COALESCE(import_updated_at, grabbed_at)) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::timestamptz AS needs_you_since, - COUNT(*) FILTER (WHERE imported_at > now() - INTERVAL '24 hours')::bigint AS imported_day, - COUNT(*) FILTER (WHERE ended_at > now() - INTERVAL '24 hours' - AND end_reason IN ('stalled', 'failed', 'gone', 'abandoned'))::bigint AS given_up_day - FROM grabs - WHERE ended_at IS NULL - OR ended_at > now() - INTERVAL '24 hours' - OR imported_at > now() - INTERVAL '24 hours'; - -- name: LibraryStatus :one -- What the library holds on disk: tracks whose files are present, the -- albums and artists they make, and their size. diff --git a/internal/db/queries/admin_summary.sql b/internal/db/queries/admin_summary.sql index 9d4167f7..bb8f9a4b 100644 --- a/internal/db/queries/admin_summary.sql +++ b/internal/db/queries/admin_summary.sql @@ -5,8 +5,6 @@ -- oldest item still waiting: how long the queue has been left, which is what -- tells an admin a count of 2 is fine today and wrong after a month. SELECT - (SELECT count(*) FROM requests WHERE status = 'pending')::bigint AS requests, - (SELECT min(requested_at) FROM requests WHERE status = 'pending')::timestamptz AS requests_since, -- A broken track is one report however it was found: a listener flagged -- it, or it failed to play. Counted by track, as the Reports -- page lists them. diff --git a/internal/db/queries/albums.sql b/internal/db/queries/albums.sql index b74cb1fb..8c78a585 100644 --- a/internal/db/queries/albums.sql +++ b/internal/db/queries/albums.sql @@ -12,6 +12,29 @@ DO UPDATE SET updated_at = now() RETURNING *; +-- name: AnyAlbumAnnounced :one +-- False on a library no scan has announced yet: its first import is the +-- library being set up, not new music arriving. +SELECT EXISTS (SELECT 1 FROM albums WHERE announced_at IS NOT NULL); + +-- name: ClaimUnannouncedAlbums :many +-- Stamps every album not yet announced and returns them, so each album is +-- claimed by exactly one scan even when a full scan and the watcher overlap. +-- arrived is whether it is news: it has a track on disk, and none of its +-- tracks is older than the album. An album that formed because files already +-- in the library were retagged holds older tracks, and is not new music. +WITH claimed AS ( + UPDATE albums SET announced_at = now() + WHERE announced_at IS NULL + RETURNING id, title, artist_id, created_at +) +SELECT c.id, c.title, ar.id AS artist_id, ar.name AS artist_name, + (EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = c.id AND t.missing_since IS NULL) + AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = c.id AND t.added_at < c.created_at))::boolean AS arrived + FROM claimed c + JOIN artists ar ON ar.id = c.artist_id + ORDER BY c.created_at, c.id; + -- name: GetAlbumByID :one SELECT * FROM albums WHERE id = $1; @@ -152,7 +175,7 @@ LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off); -- name: SearchAlbums :many SELECT * FROM albums WHERE title ILIKE '%' || $1 || '%' -ORDER BY sort_title +ORDER BY sort_title, id LIMIT $2 OFFSET $3; -- name: CountAlbumsMatching :one @@ -182,11 +205,6 @@ LIMIT $1 OFFSET $2; -- Total album count for the /api/library/albums envelope. SELECT COUNT(*) FROM albums; --- name: CountAlbumsByArtist :one --- Used by request-progress reporting to count how many albums have been --- ingested for a matched artist while a request is still in flight. -SELECT COUNT(*) FROM albums WHERE artist_id = $1; - -- name: DeleteAlbumIfEmpty :one -- Deletes the album row only when it has no remaining tracks. -- Used after a track delete to tidy up orphaned albums. RETURNING gives @@ -198,6 +216,16 @@ WHERE a.id = $1 AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) RETURNING a.id, a.artist_id; +-- name: DeleteEmptyAlbums :many +-- The scan's tidy-up: removes every album no track points to, missing or +-- not. A row made in the last ten minutes is left alone, so a file being +-- added right now (its album created, its track not yet written) is never +-- caught between the two. +DELETE FROM albums a +WHERE NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) + AND a.created_at < now() - interval '10 minutes' +RETURNING a.id; + -- name: SetAlbumMbidIfNull :exec -- Heal MBID on existing album rows during rescan. Idempotent — -- only updates when the existing mbid is NULL. @@ -207,30 +235,13 @@ UPDATE albums WHERE id = $1 AND mbid IS NULL; -- name: SetAlbumReleaseGroupMbidIfNull :exec --- Heal the release-group id on an existing album row, from a rescan's --- tags or from the re-acquisition sweeper's MusicBrainz lookup. Only fills a --- NULL, so a tag never gets overwritten by a later guess or vice versa. +-- Heal the release-group id on an existing album row from a rescan's tags. +-- Only fills a NULL, so a stored id is never overwritten. UPDATE albums SET release_group_mbid = $2, updated_at = now() WHERE id = $1 AND release_group_mbid IS NULL; --- name: GetReleaseGroupForReleaseMbid :one --- The release group the library already knows for a release id, so a --- request carrying a release id can be repaired without asking MusicBrainz. -SELECT release_group_mbid::text - FROM albums - WHERE mbid = $1 AND release_group_mbid IS NOT NULL - LIMIT 1; - --- name: SetReleaseGroupForReleaseMbidIfNull :exec --- Cache a MusicBrainz-resolved release group onto the album row that --- holds the release, filling only a NULL. -UPDATE albums - SET release_group_mbid = sqlc.arg(release_group_mbid)::text, - updated_at = now() - WHERE mbid = sqlc.arg(release_mbid)::text AND release_group_mbid IS NULL; - -- name: ListAlbumsMissingMbidWithTrack :many -- One-shot MBID backfill: returns each album where mbid IS NULL alongside -- one of its tracks' file_path so the worker can re-read tags. LIMIT @@ -288,7 +299,6 @@ UPDATE albums updated_at = now() WHERE id = $1; - -- name: GetAlbumsByIDs :many -- Batched lookup used by /api/library/sync to hydrate upsert payloads --. Mirror of GetArtistsByIDs. diff --git a/internal/db/queries/artists.sql b/internal/db/queries/artists.sql index dbb8048f..8b88adf3 100644 --- a/internal/db/queries/artists.sql +++ b/internal/db/queries/artists.sql @@ -1,5 +1,8 @@ -- name: UpsertArtist :one --- Insert or update by mbid when present; otherwise by (name, sort_name). +-- Inserts an artist, or updates the row that already has this mbid. Only +-- the mbid is matched: called without one, it inserts a new row every time, +-- so a caller that may meet the same artist again looks it up by name first +-- (the scanner's resolveArtist does). -- Callers pass the canonical sort_name; scanner is responsible for derivation. INSERT INTO artists (name, sort_name, mbid) VALUES ($1, $2, $3) @@ -24,12 +27,9 @@ SELECT * FROM artists ORDER BY sort_name; -- name: SearchArtists :many SELECT * FROM artists WHERE name ILIKE '%' || $1 || '%' -ORDER BY sort_name +ORDER BY sort_name, id LIMIT $2 OFFSET $3; --- name: ListArtistsAlpha :many -SELECT * FROM artists ORDER BY sort_name, name, id LIMIT $1 OFFSET $2; - -- name: ListArtistsNewest :many -- Secondary id tiebreaker keeps pagination stable when created_at ties. SELECT * FROM artists ORDER BY created_at DESC, id DESC LIMIT $1 OFFSET $2; @@ -40,6 +40,14 @@ SELECT COUNT(*) FROM artists; -- name: CountArtistsMatching :one SELECT COUNT(*) FROM artists WHERE name ILIKE '%' || $1::text || '%'; +-- name: ListTrackArtistsForAlbum :many +-- The artists credited on an album's tracks. They differ from the album's own +-- artist on a compilation and on a track with a featured guest. +SELECT DISTINCT ar.id, ar.name + FROM artists ar + JOIN tracks t ON t.artist_id = ar.id + WHERE t.album_id = $1; + -- name: GetArtistsByIDs :many -- Batched lookup used by M5c suggestion attribution to resolve top-3 -- contributing seed UUIDs back to artist names in one round-trip. @@ -67,6 +75,19 @@ LEFT JOIN LATERAL ( ORDER BY artists.sort_name, artists.name, artists.id LIMIT $1 OFFSET $2; +-- name: DeleteEmptyArtists :many +-- The scan's tidy-up: removes every artist with no albums and no tracks. +-- An artist a Songs like playlist is seeded from is kept, since that +-- playlist must always name its seed; it goes when the playlist is next +-- rebuilt without it. Rows made in the last ten minutes are left alone, as +-- in DeleteEmptyAlbums. +DELETE FROM artists a +WHERE NOT EXISTS (SELECT 1 FROM albums al WHERE al.artist_id = a.id) + AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.artist_id = a.id) + AND NOT EXISTS (SELECT 1 FROM playlists p WHERE p.seed_artist_id = a.id) + AND a.created_at < now() - interval '10 minutes' +RETURNING a.id; + -- name: DeleteArtistIfEmpty :one -- Deletes the artist row only when it has no remaining albums -- AND no remaining tracks (defensive — tracks can in principle exist diff --git a/internal/db/queries/audit_log.sql b/internal/db/queries/audit_log.sql index ea699eb1..a47503bc 100644 --- a/internal/db/queries/audit_log.sql +++ b/internal/db/queries/audit_log.sql @@ -2,11 +2,6 @@ INSERT INTO audit_log (actor_id, target_id, action, metadata) VALUES ($1, $2, $3, $4); --- name: ListAuditLog :many -SELECT * FROM audit_log - ORDER BY created_at DESC - LIMIT $1 OFFSET $2; - -- name: CountAuditLogByActions :one -- System actions carry no actor; system_only narrows to them. SELECT count(*)::bigint FROM audit_log diff --git a/internal/db/queries/backups.sql b/internal/db/queries/backups.sql new file mode 100644 index 00000000..da66879c --- /dev/null +++ b/internal/db/queries/backups.sql @@ -0,0 +1,110 @@ +-- Minstrel's own backup: its settings and its runs. + +-- name: GetBackupSettings :one +SELECT * FROM backup_settings WHERE id = true; + +-- name: SaveBackupSettings :exec +UPDATE backup_settings + SET enabled = $1, + destination = $2, + folder = $3, + endpoint = $4, + bucket = $5, + access_key = $6, + secret_key = $7, + run_hour = $8, + upload_limit_kib = $9, + include_music = $10, + updated_at = now() + WHERE id = true; + +-- name: StartBackupRun :one +INSERT INTO backup_runs (trigger) VALUES ($1) +RETURNING id, started_at; + +-- name: FinishBackupRun :exec +UPDATE backup_runs + SET status = $2, + finished_at = now(), + location = $3, + bytes = $4, + error = $5, + music_files = $6, + music_bytes = $7, + music_note = $8 + WHERE id = $1; + +-- name: ListBackupRuns :many +SELECT id, trigger, status, started_at, finished_at, location, bytes, error, + music_files, music_bytes, music_note + FROM backup_runs + ORDER BY started_at DESC + LIMIT $1; + +-- name: BackupRunTimes :one +-- The times the verdict turns on. A run that never happened is the epoch, +-- so the row always exists. failing_since is the first failure after the last +-- success, and the epoch when the latest finished run succeeded. +SELECT + COALESCE((SELECT max(started_at) FROM backup_runs WHERE status = 'succeeded'), + 'epoch'::timestamptz)::timestamptz AS last_success, + COALESCE((SELECT max(started_at) FROM backup_runs), + 'epoch'::timestamptz)::timestamptz AS last_attempt, + COALESCE((SELECT min(started_at) FROM backup_runs + WHERE status = 'failed' + AND started_at > COALESCE((SELECT max(started_at) FROM backup_runs WHERE status = 'succeeded'), + 'epoch'::timestamptz)), + 'epoch'::timestamptz)::timestamptz AS failing_since; + +-- name: FailUnfinishedBackupRuns :execrows +UPDATE backup_runs + SET status = 'failed', finished_at = now(), + error = 'The server stopped while the backup was running.' + WHERE status = 'running'; + +-- name: PruneBackupRuns :execrows +DELETE FROM backup_runs WHERE status <> 'running' AND started_at < $1; + +-- name: PendingBackupMusic :many +-- Library files the backup may not hold as they are now, in path order from +-- after_path, so a night that runs out of time carries on where it stopped: +-- never sent, a different size, touched by a scan since they were last +-- checked, or refused before the settings were last saved (a fixed key gets +-- another go). The caller compares the file's own size and mtime before +-- sending. +SELECT t.id, t.file_path, t.file_size, + m.size AS sent_size, m.mtime AS sent_mtime, m.error AS sent_error + FROM tracks t + LEFT JOIN backup_music_files m ON m.track_id = t.id + WHERE t.missing_since IS NULL + AND t.file_path > sqlc.arg(after_path)::text + AND (m.track_id IS NULL OR m.size <> t.file_size OR t.updated_at > m.checked_at + OR (m.error <> '' AND m.checked_at < (SELECT updated_at FROM backup_settings))) + ORDER BY t.file_path + LIMIT sqlc.arg(max_rows); + +-- name: RecordBackupMusic :exec +INSERT INTO backup_music_files (track_id, size, mtime, location, error) +VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (track_id) DO UPDATE + SET size = EXCLUDED.size, mtime = EXCLUDED.mtime, location = EXCLUDED.location, + error = EXCLUDED.error, checked_at = now(); + +-- name: BackupMusicProgress :one +-- How much of the library the backup holds as it is now. +SELECT count(*)::bigint AS total_files, + COALESCE(sum(t.file_size), 0)::bigint AS total_bytes, + count(*) FILTER (WHERE m.error = '' AND m.size = t.file_size AND t.updated_at <= m.checked_at)::bigint AS sent_files, + COALESCE(sum(t.file_size) FILTER (WHERE m.error = '' AND m.size = t.file_size AND t.updated_at <= m.checked_at), 0)::bigint AS sent_bytes, + count(*) FILTER (WHERE m.error <> '' AND m.size = t.file_size AND t.updated_at <= m.checked_at)::bigint AS refused_files + FROM tracks t + LEFT JOIN backup_music_files m ON m.track_id = t.id + WHERE t.missing_since IS NULL; + +-- name: RefusedBackupMusic :many +SELECT t.file_path, m.error, m.checked_at + FROM backup_music_files m + JOIN tracks t ON t.id = m.track_id + WHERE m.error <> '' AND m.size = t.file_size AND t.updated_at <= m.checked_at + ORDER BY m.checked_at DESC + LIMIT $1; diff --git a/internal/db/queries/browse.sql b/internal/db/queries/browse.sql index 4a200fc4..67814d2f 100644 --- a/internal/db/queries/browse.sql +++ b/internal/db/queries/browse.sql @@ -36,7 +36,11 @@ -- Ordered by count first: raw ID3 data has a long tail of one-off junk tags, -- so alphabetical would bury the handful of genres a library actually has -- a lot of. Name breaks ties for a stable order. -SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count +-- +-- album_count is the albums holding at least one of those tracks, which is +-- what a Subsonic app shows beside the genre. +SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count, + COUNT(DISTINCT tracks.album_id)::bigint AS album_count FROM tracks JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) ON true WHERE trim(g.genre) <> '' @@ -66,6 +70,29 @@ WHERE EXISTS ( ORDER BY albums.sort_title, albums.id LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off); +-- name: ListTracksByGenre :many +-- One genre's songs for the Subsonic getSongsByGenre, a page at a time. +-- Splits and trims identically to ListGenresWithCount, so the songs a genre +-- leads to are the ones it counted. The listener's quarantined tracks are +-- left out: an app asks for these to play them. Album by album in track +-- order, so paging walks a stable order. +SELECT sqlc.embed(tracks) +FROM tracks +JOIN albums ON albums.id = tracks.album_id +WHERE tracks.missing_since IS NULL + AND EXISTS ( + SELECT 1 + FROM regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) + WHERE trim(g.genre) = trim(sqlc.arg(genre)::text) + ) + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = tracks.id + ) +ORDER BY albums.sort_title, albums.id, + tracks.disc_number NULLS FIRST, tracks.track_number NULLS FIRST, tracks.id +LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off); + -- name: CountAlbumsByGenre :one -- Total for the paging envelope. EXISTS mirrors the list query exactly; a -- JOIN + DISTINCT here would count differently the moment an album has two @@ -144,3 +171,22 @@ JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genr WHERE tracks.artist_id = $1 AND trim(g.genre) <> '' AND tracks.missing_since IS NULL ORDER BY trim(g.genre); + +-- name: ListAlbumsByYearOrdered :many +-- Subsonic getAlbumList2 type=byYear: albums released within an inclusive +-- year range, oldest first, or newest first when the caller asks for the +-- range backwards (fromYear > toYear), as the Subsonic API defines it. +SELECT albums.* FROM albums +WHERE albums.release_date IS NOT NULL + AND EXTRACT(YEAR FROM albums.release_date)::int + BETWEEN LEAST(sqlc.arg(from_year)::int, sqlc.arg(to_year)::int) + AND GREATEST(sqlc.arg(from_year)::int, sqlc.arg(to_year)::int) + AND EXISTS ( + SELECT 1 FROM tracks + WHERE tracks.album_id = albums.id + AND tracks.missing_since IS NULL + ) +ORDER BY CASE WHEN sqlc.arg(from_year)::int <= sqlc.arg(to_year)::int THEN albums.release_date END ASC, + CASE WHEN sqlc.arg(from_year)::int > sqlc.arg(to_year)::int THEN albums.release_date END DESC, + albums.sort_title, albums.id +LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off); diff --git a/internal/db/queries/candidate_artist_tags.sql b/internal/db/queries/candidate_artist_tags.sql deleted file mode 100644 index 4bc94881..00000000 --- a/internal/db/queries/candidate_artist_tags.sql +++ /dev/null @@ -1,103 +0,0 @@ --- Folksonomy tags for out-of-library Discover candidates. Parallel to --- track_tags.sql, but keyed by MBID because the artist has no local row. See --- 0050_candidate_artist_tags.up.sql for why the bookkeeping is its own table. - --- name: ListCandidateArtistsMissingTags :many --- Candidates eligible for tag enrichment: never processed (no state row) or --- settled 'none' under an older provider version. --- --- artist_similarity_unmatched holds one row per (seed, candidate, source), so --- this GROUPs to one row per candidate — enriching the same MBID once per seed --- that pointed at it would multiply the API calls for no gain. --- --- ORDER BY summed similarity DESC is the load-bearing part. The candidate pool --- is O(library artists x neighbours per artist) — thousands — and MusicBrainz --- allows ~1 req/s, so it can NEVER be fully enriched in one pass. Draining in --- strength order means the candidates most likely to actually reach a user's --- deck get tags first, and the long tail fills in over subsequent ticks --- instead of starving behind it. --- --- Already-in-library candidates are skipped: they have an artists row, so --- their tags belong in track_tags, and the suggestion query filters them out --- anyway. $1 = current tag_sources_version, $2 = limit. --- candidate_name is coalesced to the empty string so it lands non-nullable in --- Go: the name is only a Last.fm lookup key, and empty simply means "MBID-keyed --- providers only", which the provider chain already handles. max() is an --- arbitrary-but-deterministic pick when several seeds spell one MBID --- differently. -SELECT u.candidate_mbid, - coalesce(max(u.candidate_name), '')::text AS candidate_name, - sum(u.score)::float8 AS total_score - FROM artist_similarity_unmatched u - LEFT JOIN candidate_artist_tag_state s ON s.candidate_mbid = u.candidate_mbid - WHERE NOT EXISTS (SELECT 1 FROM artists a WHERE a.mbid = u.candidate_mbid) - AND ( - s.candidate_mbid IS NULL - OR (s.tag_source = 'none' AND s.tag_sources_version < $1) - ) - GROUP BY u.candidate_mbid - ORDER BY total_score DESC, u.candidate_mbid - LIMIT $2; - --- name: DeleteCandidateArtistTags :exec --- Clear a candidate's cached tags before rewriting (atomic replace by the --- caller, same shape as DeleteTrackTags). -DELETE FROM candidate_artist_tags WHERE candidate_mbid = $1; - --- name: InsertCandidateArtistTag :exec --- Upsert one (candidate, tag); keep the stronger weight when two providers --- agree on a tag with different folksonomy strengths. -INSERT INTO candidate_artist_tags (candidate_mbid, tag, weight) -VALUES ($1, $2, $3) -ON CONFLICT (candidate_mbid, tag) - DO UPDATE SET weight = GREATEST(candidate_artist_tags.weight, EXCLUDED.weight); - --- name: SetCandidateArtistTagState :exec --- Stamp the enrichment outcome so the drainer skips settled candidates. --- $2 = 'musicbrainz' | 'lastfm' | 'mixed' | 'none', $3 = current version. -INSERT INTO candidate_artist_tag_state (candidate_mbid, tag_source, tag_sources_version) -VALUES ($1, $2, $3) -ON CONFLICT (candidate_mbid) DO UPDATE - SET tag_source = EXCLUDED.tag_source, - tag_sources_version = EXCLUDED.tag_sources_version, - updated_at = now(); - --- name: ListCandidateArtistTagsForMbids :many --- Cached tags for a set of candidates, for the taste-overlap ranking. --- One row per (candidate, tag). -SELECT candidate_mbid, tag, weight - FROM candidate_artist_tags - WHERE candidate_mbid = ANY($1::text[]); - --- name: CountCandidateArtistTagCoverage :one --- Operator-facing coverage: how many distinct candidates have been processed, --- and how many of those actually yielded tags. The gap is the honest ceiling --- from the task — obscure artists with no MBID presence or no upstream tags --- stay thin no matter how long the worker runs, and that is worth being able --- to see rather than inferring from a silent surface. -SELECT count(*)::bigint AS processed, - count(*) FILTER (WHERE tag_source <> 'none')::bigint AS with_tags - FROM candidate_artist_tag_state; - --- name: GcDeleteOrphanedCandidateArtistTags :execrows --- Drops cached tags for candidates that no longer appear in the similarity --- feed, or that have since been added to the library (their tags now live in --- track_tags). The feed is refetched periodically and churns, so without this --- the cache only ever grows. -DELETE FROM candidate_artist_tags t - WHERE NOT EXISTS ( - SELECT 1 FROM artist_similarity_unmatched u - WHERE u.candidate_mbid = t.candidate_mbid - ) - OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = t.candidate_mbid); - --- name: GcDeleteOrphanedCandidateArtistTagState :execrows --- Same sweep for the bookkeeping rows. Kept as a separate statement rather --- than a cascade: the two tables are independent by design (a 'none' outcome --- has state but no tags), so neither can be the parent of the other. -DELETE FROM candidate_artist_tag_state s - WHERE NOT EXISTS ( - SELECT 1 FROM artist_similarity_unmatched u - WHERE u.candidate_mbid = s.candidate_mbid - ) - OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = s.candidate_mbid); diff --git a/internal/db/queries/catalogue.sql b/internal/db/queries/catalogue.sql index 6d8d5309..c39d2220 100644 --- a/internal/db/queries/catalogue.sql +++ b/internal/db/queries/catalogue.sql @@ -1,34 +1,8 @@ -- The release catalogue read from MusicBrainz. --- name: UpsertMBArtist :exec -INSERT INTO mb_artists (mbid, name, sort_name, disambiguation, artist_type, country) -VALUES (sqlc.arg(mbid), sqlc.arg(name), sqlc.arg(sort_name), sqlc.arg(disambiguation), - sqlc.arg(artist_type), sqlc.arg(country)) -ON CONFLICT (mbid) DO UPDATE SET - name = EXCLUDED.name, - sort_name = EXCLUDED.sort_name, - disambiguation = EXCLUDED.disambiguation, - artist_type = EXCLUDED.artist_type, - country = EXCLUDED.country, - updated_at = now(); - --- name: GetMBArtist :one -SELECT * FROM mb_artists WHERE mbid = sqlc.arg(mbid); - --- name: MarkMBArtistDiscographyRefreshed :exec -UPDATE mb_artists SET discography_refreshed_at = now() WHERE mbid = sqlc.arg(mbid); - --- name: ListMBArtistsDueForRefresh :many --- Artists whose discography has never been read, or was read before the --- cutoff: never-read first, then oldest first. -SELECT mbid FROM mb_artists -WHERE discography_refreshed_at IS NULL OR discography_refreshed_at < sqlc.arg(before) -ORDER BY discography_refreshed_at NULLS FIRST, mbid -LIMIT sqlc.arg(max_rows); - -- name: UpsertMBReleaseGroup :exec --- Leaves releases_refreshed_at alone: re-reading a discography says nothing --- about whether the group's track lists are current. +-- Leaves releases_refreshed_at alone: only a full read of the group's +-- releases and track lists marks it. INSERT INTO mb_release_groups (mbid, title, primary_type, secondary_types, first_release_date, artist_credit) VALUES (sqlc.arg(mbid), sqlc.arg(title), sqlc.arg(primary_type), sqlc.arg(secondary_types)::text[], sqlc.arg(first_release_date), sqlc.arg(artist_credit)) @@ -43,21 +17,6 @@ ON CONFLICT (mbid) DO UPDATE SET -- name: GetMBReleaseGroup :one SELECT * FROM mb_release_groups WHERE mbid = sqlc.arg(mbid); --- name: DeleteMBArtistReleaseGroups :exec -DELETE FROM mb_artist_release_groups WHERE artist_mbid = sqlc.arg(artist_mbid); - --- name: AddMBArtistReleaseGroup :exec -INSERT INTO mb_artist_release_groups (artist_mbid, release_group_mbid) -VALUES (sqlc.arg(artist_mbid), sqlc.arg(release_group_mbid)) -ON CONFLICT DO NOTHING; - --- name: ListMBArtistReleaseGroups :many --- An artist's discography, oldest first; undated groups last. -SELECT g.* FROM mb_release_groups g -JOIN mb_artist_release_groups ag ON ag.release_group_mbid = g.mbid -WHERE ag.artist_mbid = sqlc.arg(artist_mbid) -ORDER BY g.first_release_date = '', g.first_release_date, g.title, g.mbid; - -- name: MarkMBReleaseGroupReleasesRefreshed :exec UPDATE mb_release_groups SET releases_refreshed_at = now() WHERE mbid = sqlc.arg(mbid); @@ -88,12 +47,6 @@ VALUES (sqlc.arg(release_mbid), sqlc.arg(medium_position), sqlc.arg(position), sqlc.arg(medium_format), sqlc.arg(number), sqlc.arg(title), sqlc.arg(length_ms), sqlc.arg(recording_mbid)); --- name: ListMBReleasesForGroup :many --- Official editions first, then by date; undated last. -SELECT * FROM mb_releases -WHERE release_group_mbid = sqlc.arg(release_group_mbid) -ORDER BY status <> 'Official', release_date = '', release_date, title, mbid; - -- name: ListMBReleaseTracksForGroup :many SELECT t.* FROM mb_release_tracks t JOIN mb_releases r ON r.mbid = t.release_mbid diff --git a/internal/db/queries/contextual_likes.sql b/internal/db/queries/contextual_likes.sql index c84fdb5f..917b9a68 100644 --- a/internal/db/queries/contextual_likes.sql +++ b/internal/db/queries/contextual_likes.sql @@ -3,19 +3,30 @@ INSERT INTO contextual_likes (user_id, track_id, session_vector, session_id) VALUES ($1, $2, $3, $4); -- name: SoftDeleteContextualLikesForUserTrack :exec --- Marks all currently-active rows for (user, track) as deleted. Idempotent — --- already-deleted rows aren't re-touched. +-- Marks the user's active rows for the song as deleted: every copy sharing +-- the track's song_key, as UnlikeTrack removes the like from every copy. +-- The context was captured on whichever copy was playing, which needn't be +-- the one the unlike names. Idempotent — already-deleted rows aren't +-- re-touched. UPDATE contextual_likes SET deleted_at = now() -WHERE user_id = $1 AND track_id = $2 AND deleted_at IS NULL; +WHERE user_id = sqlc.arg(user_id)::uuid + AND deleted_at IS NULL + AND (track_id = sqlc.arg(track_id)::uuid + OR track_id IN (SELECT t.id FROM tracks t + WHERE t.song_key = (SELECT s.song_key FROM tracks s WHERE s.id = sqlc.arg(track_id)::uuid))); -- name: ListActiveContextualLikesForUser :many -- Returns all the user's active (non-soft-deleted) contextual_likes with -- non-null vectors. Cardinality is bounded by the user's actual like-while- -- playing history — typically tens to low hundreds. Used by the engine to -- compute contextual_match_score for the candidate pool. -SELECT track_id, session_vector -FROM contextual_likes -WHERE user_id = $1 - AND deleted_at IS NULL - AND session_vector IS NOT NULL; +-- +-- Only rows whose song is still liked count, so a context left active by +-- an unlike that missed it can't keep boosting a song the user let go of. +SELECT cl.track_id, cl.session_vector +FROM contextual_likes cl +WHERE cl.user_id = $1 + AND cl.deleted_at IS NULL + AND cl.session_vector IS NOT NULL + AND EXISTS (SELECT 1 FROM general_likes g WHERE g.user_id = cl.user_id AND g.track_id = cl.track_id); diff --git a/internal/db/queries/covers.sql b/internal/db/queries/covers.sql index ecad7846..e2a8ca86 100644 --- a/internal/db/queries/covers.sql +++ b/internal/db/queries/covers.sql @@ -59,14 +59,3 @@ UPDATE albums UPDATE albums SET cover_art_source = NULL WHERE id = $1 AND cover_art_source = 'none'; - --- name: CountAlbumCoverSources :one --- Diagnostic for the admin overview: counts by source, including NULL. --- Returns one row with named tallies. -SELECT - COUNT(*) FILTER (WHERE cover_art_source IS NULL) ::bigint AS untried, - COUNT(*) FILTER (WHERE cover_art_source = 'sidecar') ::bigint AS sidecar, - COUNT(*) FILTER (WHERE cover_art_source = 'embedded')::bigint AS embedded, - COUNT(*) FILTER (WHERE cover_art_source = 'mbcaa') ::bigint AS mbcaa, - COUNT(*) FILTER (WHERE cover_art_source = 'none') ::bigint AS none - FROM albums; diff --git a/internal/db/queries/duplicates.sql b/internal/db/queries/duplicates.sql index 168e6aed..7aadcba7 100644 --- a/internal/db/queries/duplicates.sql +++ b/internal/db/queries/duplicates.sql @@ -103,15 +103,6 @@ DELETE FROM duplicate_groups g OR (SELECT s.started_at FROM duplicate_sweeps s WHERE s.id = g.last_seen_sweep_id) < (SELECT s.started_at FROM duplicate_sweeps s WHERE s.id = sqlc.arg(sweep_id))); --- name: CountPendingDuplicateGroups :one --- Proposals awaiting review. A group left with one member — its other tracks --- deleted since the sweep — is no proposal at all and is not counted; the next --- sweep retires it. -SELECT count(*)::bigint - FROM duplicate_groups g - WHERE g.status = 'pending' - AND (SELECT count(*) FROM duplicate_group_members m WHERE m.group_id = g.id) >= 2; - -- name: CountPendingDuplicateGroupsInView :one -- CountPendingDuplicateGroups narrowed to one view of the report: -- review what an admin still has to decide: every class but @@ -221,7 +212,7 @@ SELECT g.id AS group_id, AND t.track_number IS NOT NULL AND o.disc_number IS NOT DISTINCT FROM t.disc_number AND o.track_number = t.track_number)::boolean AS position_clash, - COALESCE(NULLIF(al.release_group_mbid, ''), lam.release_group_mbid, '')::text AS release_group_mbid, + COALESCE(al.release_group_mbid, '')::text AS release_group_mbid, l.state AS acoustid_state, l.recording_mbid AS acoustid_recording FROM duplicate_groups g @@ -229,7 +220,6 @@ SELECT g.id AS group_id, JOIN tracks t ON t.id = m.track_id JOIN artists ON artists.id = t.artist_id JOIN albums al ON al.id = t.album_id - LEFT JOIN library_album_matches lam ON lam.album_id = t.album_id AND lam.outcome = 'listed' LEFT JOIN track_acoustid_lookups l ON l.track_id = t.id WHERE g.status = 'pending' AND t.missing_since IS NULL diff --git a/internal/db/queries/fingerprint_settings.sql b/internal/db/queries/fingerprint_settings.sql index 010f5ff6..cfa698aa 100644 --- a/internal/db/queries/fingerprint_settings.sql +++ b/internal/db/queries/fingerprint_settings.sql @@ -2,7 +2,7 @@ SELECT * FROM fingerprint_settings WHERE id = true; -- name: UpdateFingerprintSettings :one --- Whole-row write from the admin card; migration 0061's CHECKs are the backstop +-- Whole-row write from the admin card; fingerprint_settings's CHECKs are the backstop -- behind the service's own validation. UPDATE fingerprint_settings SET enabled = sqlc.arg(enabled), diff --git a/internal/db/queries/genre_mixes.sql b/internal/db/queries/genre_mixes.sql new file mode 100644 index 00000000..6859a8dc --- /dev/null +++ b/internal/db/queries/genre_mixes.sql @@ -0,0 +1,193 @@ +-- Candidate queries for the genre mixes: one daily system playlist per genre +-- the user listens to. Genres live inline on tracks.genre as a delimited +-- string and are split on [;,] the same way the Discover and radio tag arms +-- split them. Matching is case-insensitive, so the ID3 "Post-Punk" and the +-- folksonomy "post-punk" in the taste profile count as one genre. + +-- name: ListGenreMixCandidates :many +-- Library genres big enough to carry a mix (>= 25 playable tracks across +-- >= 3 artists), each tagged with how close it is to the user's listening: +-- +-- tier 1: a positive taste-profile genre, scored by its taste weight +-- tier 2: a genre of tracks the user has played through or liked, scored +-- by how many — catches a profile that has not been built yet or +-- has decayed past its window +-- tier 3: any other library genre, scored by its size +-- +-- track_ids lets the caller tell how much music two genres share: a genre +-- whose songs mostly sit in genres already picked adds no new channel, and a +-- broad genre ("Rock") whose songs mostly carry narrower ones ("Pop Punk", +-- "Ska Punk") gives way to them. +-- $1 user_id. +WITH library_genres AS ( + SELECT lower(trim(g.g)) AS genre_key, + min(trim(g.g))::text AS label, + COUNT(DISTINCT t.id) AS track_count, + array_agg(DISTINCT t.id)::uuid[] AS track_ids + FROM tracks t + CROSS JOIN LATERAL regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE t.missing_since IS NULL + AND trim(g.g) <> '' + GROUP BY lower(trim(g.g)) + HAVING COUNT(DISTINCT t.id) >= 25 + AND COUNT(DISTINCT t.artist_id) >= 3 +), +taste AS ( + SELECT lower(trim(tpt.tag)) AS genre_key, SUM(tpt.weight) AS weight + FROM taste_profile_tags tpt + WHERE tpt.user_id = $1 + GROUP BY lower(trim(tpt.tag)) + HAVING SUM(tpt.weight) > 0 +), +listened AS ( + SELECT t.id + FROM play_events pe + JOIN tracks t ON t.id = pe.track_id + WHERE pe.user_id = $1 AND pe.was_skipped = false + UNION ALL + SELECT gl.track_id + FROM general_likes gl + WHERE gl.user_id = $1 +), +history AS ( + SELECT lower(trim(g.g)) AS genre_key, COUNT(*) AS plays + FROM listened l + JOIN tracks t ON t.id = l.id + CROSS JOIN LATERAL regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE trim(g.g) <> '' + GROUP BY lower(trim(g.g)) +) +SELECT lg.genre_key::text AS genre_key, + lg.label AS label, + (CASE WHEN ta.genre_key IS NOT NULL THEN 1 + WHEN h.genre_key IS NOT NULL THEN 2 + ELSE 3 END)::int AS tier, + (CASE WHEN ta.genre_key IS NOT NULL THEN ta.weight + WHEN h.genre_key IS NOT NULL THEN h.plays::float8 + ELSE lg.track_count::float8 END)::float8 AS score, + lg.track_ids + FROM library_genres lg + LEFT JOIN taste ta ON ta.genre_key = lg.genre_key + LEFT JOIN history h ON h.genre_key = lg.genre_key + ORDER BY tier, score DESC, lg.genre_key + LIMIT 60; + +-- name: ListGenreMixTracks :many +-- Playable tracks carrying one genre, split into the two halves a genre mix +-- blends: familiar (the user has played it through or liked it) and unheard. +-- Up to 200 of each, drawn by a weighted lottery seeded with the date, so the +-- mix changes day to day, holds still within a day, and leans toward what the +-- user likes without becoming the same 50 songs every day. +-- +-- The lottery is the Efraimidis-Spirakis draw: each track gets +-- -ln(u) / weight with u uniform in (0, 1) from md5(track, date), and the +-- smallest keys win. A track of weight 3 is three times as likely as one of +-- weight 1 to come before it, and every track keeps some chance. +-- +-- Familiar weight: 1 + ln(1 + plays through) + 1 if liked, times the share of +-- its plays that were not skips. A song played 40 times weighs about 4.7, one +-- played once about 1.7. +-- +-- Unheard weight: 1 + ln(1 + the artist's plays through + 2 × its liked +-- tracks) + 2 × how similar the artist is to the user's own artists (the best +-- artist_similarity score from any artist they have played through or liked, +-- 0 to 1), times the share of the artist's plays that were not skips. An +-- artist the user has never met weighs 1, so new artists still come up; an +-- artist they keep skipping weighs well under 1. +-- +-- A track the user keeps skipping stays out: twice-skipped and skipped more +-- often than played through. The second half of that test keeps a favourite +-- with a couple of stray skips in. +-- +-- exclude_genres keeps each song in one mix: a track carrying a genre that +-- already has a mix today is left to that mix. +WITH play_counts AS ( + SELECT pe.track_id, COUNT(*) AS c + FROM play_events pe + WHERE pe.user_id = sqlc.arg(user_id) AND pe.was_skipped = false + GROUP BY pe.track_id +), +skip_counts AS ( + SELECT pe.track_id, COUNT(*) AS c + FROM play_events pe + WHERE pe.user_id = sqlc.arg(user_id) AND pe.was_skipped = true + GROUP BY pe.track_id +), +artist_plays AS ( + SELECT t.artist_id, + COUNT(*) FILTER (WHERE NOT pe.was_skipped) AS plays, + COUNT(*) FILTER (WHERE pe.was_skipped) AS skips + FROM play_events pe + JOIN tracks t ON t.id = pe.track_id + WHERE pe.user_id = sqlc.arg(user_id) + GROUP BY t.artist_id +), +artist_likes AS ( + SELECT t.artist_id, COUNT(*) AS likes + FROM general_likes gl + JOIN tracks t ON t.id = gl.track_id + WHERE gl.user_id = sqlc.arg(user_id) + GROUP BY t.artist_id +), +own_artists AS ( + SELECT ap.artist_id FROM artist_plays ap WHERE ap.plays > 0 + UNION + SELECT al.artist_id FROM artist_likes al +), +artist_sim AS ( + SELECT asim.artist_b_id AS artist_id, + MAX(LEAST(GREATEST(asim.score, 0), 1)) AS sim + FROM artist_similarity asim + JOIN own_artists oa ON oa.artist_id = asim.artist_a_id + GROUP BY asim.artist_b_id +), +eligible AS ( + SELECT t.id, t.album_id, t.artist_id, + (COALESCE(pc.c, 0) > 0 OR gl.track_id IS NOT NULL) AS familiar, + CASE + WHEN COALESCE(pc.c, 0) > 0 OR gl.track_id IS NOT NULL THEN + (1 + ln(1 + COALESCE(pc.c, 0)::float8) + + CASE WHEN gl.track_id IS NOT NULL THEN 1 ELSE 0 END) + * ((COALESCE(pc.c, 0) + 1)::float8 / (COALESCE(pc.c, 0) + COALESCE(sc.c, 0) + 1)) + ELSE + (1 + ln(1 + COALESCE(ap.plays, 0)::float8 + 2 * COALESCE(al.likes, 0)::float8) + + 2 * COALESCE(asm.sim, 0)) + * ((COALESCE(ap.plays, 0) + 1)::float8 / (COALESCE(ap.plays, 0) + COALESCE(ap.skips, 0) + 1)) + END::float8 AS weight, + -- u in (0, 1): the first 32 bits of md5(track, date), shifted off 0. + ((('x' || substr(md5(t.id::text || sqlc.arg(date_seed)::text), 1, 8))::bit(32)::bigint)::float8 + 1) + / 4294967297.0 AS u + FROM tracks t + LEFT JOIN play_counts pc ON pc.track_id = t.id + LEFT JOIN skip_counts sc ON sc.track_id = t.id + LEFT JOIN general_likes gl ON gl.user_id = sqlc.arg(user_id) AND gl.track_id = t.id + LEFT JOIN artist_plays ap ON ap.artist_id = t.artist_id + LEFT JOIN artist_likes al ON al.artist_id = t.artist_id + LEFT JOIN artist_sim asm ON asm.artist_id = t.artist_id + WHERE t.missing_since IS NULL -- never offer a file that is gone + AND NOT (COALESCE(sc.c, 0) >= 2 AND COALESCE(sc.c, 0) > COALESCE(pc.c, 0)) + AND EXISTS ( + SELECT 1 + FROM regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE lower(trim(g.g)) = sqlc.arg(genre_key)::text + ) + AND NOT EXISTS ( + SELECT 1 + FROM regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(g) + WHERE lower(trim(g.g)) = ANY(sqlc.arg(exclude_genres)::text[]) + ) + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = t.id + ) +), +ranked AS ( + SELECT e.id, e.album_id, e.artist_id, e.familiar, + -ln(e.u) / e.weight AS draw, + row_number() OVER (PARTITION BY e.familiar ORDER BY -ln(e.u) / e.weight, e.id) AS rn + FROM eligible e +) +SELECT r.id, r.album_id, r.artist_id, r.familiar::bool AS familiar + FROM ranked r + WHERE r.rn <= 200 + ORDER BY r.familiar DESC, r.draw, r.id; diff --git a/internal/db/queries/imports.sql b/internal/db/queries/imports.sql deleted file mode 100644 index e373303c..00000000 --- a/internal/db/queries/imports.sql +++ /dev/null @@ -1,176 +0,0 @@ --- Import with verification. - --- name: ListLiveGrabs :many --- Every download still running or waiting on its import, oldest first. -SELECT g.*, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title AS want_title, - w.reason AS want_reason, w.album_id AS want_album_id - FROM grabs g - LEFT JOIN wants w ON w.id = g.want_id - WHERE g.ended_at IS NULL - ORDER BY g.grabbed_at, g.id; - --- name: GetGrab :one -SELECT * FROM grabs WHERE id = $1; - --- name: SetGrabProgress :exec --- What the download client says of a download not yet finished, or finished --- and waiting for what the import needs. Leaves a claimed, decided or failed --- import alone. -UPDATE grabs - SET progress = sqlc.arg(progress), - import_state = sqlc.arg(import_state), - import_reason = sqlc.arg(import_reason), - import_updated_at = now() - WHERE id = sqlc.arg(id) AND ended_at IS NULL - AND import_state IN ('', 'downloading', 'waiting'); - --- name: ClaimGrabImport :one --- Takes a finished download for import. The update is the lock: a second --- pass finds nothing to claim. -UPDATE grabs - SET import_state = 'importing', import_attempts = import_attempts + 1, - import_updated_at = now(), progress = 1 - WHERE id = $1 AND ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting') -RETURNING *; - --- name: ReclaimStaleImports :execrows --- An import cut short (a restart mid-copy) is tried again. -UPDATE grabs - SET import_state = 'waiting', - import_reason = 'The last import was cut short, so it is being tried again.' - WHERE ended_at IS NULL AND import_state = 'importing' - AND import_updated_at < now() - make_interval(mins => sqlc.arg(minutes)::int); - --- name: RecordImport :one --- The import's outcome. An end reason ends the grab: imported, refused or --- held. Without one the grab stays live: review and failed wait for a person. -UPDATE grabs - SET import_state = sqlc.arg(import_state), - import_reason = sqlc.arg(import_reason), - import_detail = sqlc.arg(import_detail), - import_updated_at = now(), - import_forced = false, - imported_at = CASE WHEN sqlc.arg(import_state)::text = 'imported' THEN now() ELSE imported_at END, - -- The files were copied, so an imported download goes on sharing - -- until the lifecycle removes it. - seeding = sqlc.arg(import_state)::text = 'imported', - imported_files = sqlc.arg(imported_files), - destination = sqlc.arg(destination), - ended_at = CASE WHEN sqlc.arg(end_reason)::text <> '' THEN now() ELSE ended_at END, - end_reason = sqlc.arg(end_reason), - end_detail = CASE WHEN sqlc.arg(end_reason)::text <> '' THEN sqlc.arg(import_reason)::text ELSE end_detail END - WHERE id = sqlc.arg(id) -RETURNING *; - --- name: ForceGrabImport :one --- "Import anyway": the next pass imports the download whatever the check said. -UPDATE grabs - SET import_state = '', import_forced = true, import_reason = '', import_updated_at = now() - WHERE id = $1 AND ended_at IS NULL AND import_state IN ('review', 'failed') -RETURNING *; - --- name: RetryGrabImport :one -UPDATE grabs - SET import_state = '', import_reason = '', import_updated_at = now() - WHERE id = $1 AND ended_at IS NULL AND import_state = 'failed' -RETURNING *; - --- name: RehomeGrab :one --- A download that turned out to be another wanted album is that want's grab, --- when the want has none running. -UPDATE grabs g - SET want_id = sqlc.arg(want_id) - WHERE g.id = sqlc.arg(id) AND g.ended_at IS NULL - AND NOT EXISTS (SELECT 1 FROM grabs o WHERE o.want_id = sqlc.arg(want_id) AND o.ended_at IS NULL) -RETURNING *; - --- name: OpenWantsForGroups :many --- Open wants for these release groups with no download running. -SELECT w.* FROM wants w - WHERE w.fulfilled_at IS NULL AND w.release_group_mbid = ANY(sqlc.arg(groups)::text[]) - AND NOT EXISTS (SELECT 1 FROM grabs g WHERE g.want_id = w.id AND g.ended_at IS NULL); - --- name: MarkWantSearched :exec --- Imported: nothing to search for until the wanted pass settles the want. -UPDATE wants SET searched_at = now() WHERE id = $1; - --- name: SearchWantAgain :exec --- Refused: search again on the next pass. -UPDATE wants SET searched_at = NULL, search_outcome = '' WHERE id = $1; - --- name: HeldRecordings :many --- Which of these recordings the library holds a file for. -SELECT DISTINCT mbid::text AS mbid FROM tracks - WHERE mbid = ANY(sqlc.arg(recordings)::text[]) AND missing_since IS NULL; - --- name: HeldPositions :many --- The disc and track positions the library holds for an album of this group. -SELECT DISTINCT COALESCE(t.disc_number, 1)::int AS disc, t.track_number::int AS track - FROM tracks t - JOIN albums a ON a.id = t.album_id - WHERE a.release_group_mbid = sqlc.arg(release_group_mbid) - AND t.missing_since IS NULL AND t.track_number IS NOT NULL; - --- name: ListGrabs :many --- The Wanted view's Activity tab: downloads waiting on a person first, then --- the rest still running, then the ended ones newest first. Each carries --- what is wrong with it now, if anything. -SELECT g.id, g.want_id, g.name, g.indexer, g.client, g.quality, g.origin, g.forced, - g.grabbed_at, g.ended_at, g.end_reason, g.end_detail, g.progress, g.import_state, - g.import_reason, g.import_detail, g.import_updated_at, g.imported_at, g.imported_files, - g.destination, g.seeding, g.ratio, g.seed_released_at, - w.title AS want_title, w.artist_name AS want_artist, - di.trigger AS condition, di.detail AS condition_detail, di.remediations AS condition_retries, - di.first_seen AS condition_since - FROM grabs g - LEFT JOIN wants w ON w.id = g.want_id - LEFT JOIN download_interventions di - ON di.id = (SELECT x.id FROM download_interventions x - WHERE x.grab_id = g.id AND x.outcome = 'open' - ORDER BY x.last_seen DESC LIMIT 1) - ORDER BY (g.ended_at IS NULL AND g.import_state IN ('review', 'failed')) DESC, - g.ended_at IS NULL DESC, g.grabbed_at DESC, g.id - LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip); - --- name: ListReleaseBlocksPage :many -SELECT b.info_hash, b.name, b.reason, b.detail, b.blocked_at, b.expires_at, w.title AS want_title, - w.artist_name AS want_artist - FROM release_blocks b - LEFT JOIN wants w ON w.id = b.want_id - WHERE b.expires_at IS NULL OR b.expires_at > now() - ORDER BY b.blocked_at DESC, b.info_hash - LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip); - --- name: ListUpgradeTracks :many --- The tracks an upgrade may replace: the present tracks of the album --- the want holds. -SELECT id, file_path, mbid, COALESCE(disc_number, 1)::int AS disc, track_number, - file_format, file_size, duration_ms, source_verdict - FROM tracks - WHERE album_id = $1 AND missing_since IS NULL; - --- name: FinishUpgrade :exec --- An upgrade was imported: the want holds the album the new tracks are in, --- and is judged again by the next upgrade check. -UPDATE wants - SET album_id = COALESCE(sqlc.narg(album_id), album_id), - upgrade = '', - upgrade_checked_at = NULL, - updated_at = now() - WHERE id = sqlc.arg(id); - --- name: ClearTrackSourceVerdict :exec --- A track whose file was replaced in place is no longer the rip it was. -UPDATE tracks SET source_verdict = NULL, source_verdict_at = NULL - WHERE id = $1 AND source_verdict = 'suspect'; - --- name: ListImportedGrabsHolding :many --- The downloads Minstrel imported into the folder holding path: the releases a --- file there came from, to block when the files proved not to be the album ---. A file imported before Minstrel downloaded anything has none. -SELECT id, info_hash, name, want_id - FROM grabs - WHERE import_state = 'imported' - AND info_hash <> '' - AND destination <> '' - AND starts_with(sqlc.arg(path)::text, rtrim(destination, '/') || '/'); diff --git a/internal/db/queries/invites.sql b/internal/db/queries/invites.sql index 2ede3f45..dea66e5c 100644 --- a/internal/db/queries/invites.sql +++ b/internal/db/queries/invites.sql @@ -13,13 +13,6 @@ SELECT * FROM user_invites WHERE redeemed_at IS NULL AND expires_at > now() ORDER BY created_at DESC; --- name: ListInvitesAll :many --- Includes redeemed + expired for full audit visibility. Caller --- supplies a LIMIT to bound the response. -SELECT * FROM user_invites - ORDER BY created_at DESC - LIMIT $1; - -- name: RedeemInvite :execrows -- Atomic claim: returns rows-affected so the caller can detect -- already-redeemed / expired tokens (rows=0) versus successful claim diff --git a/internal/db/queries/library_changes.sql b/internal/db/queries/library_changes.sql index 0437b36a..712850cc 100644 --- a/internal/db/queries/library_changes.sql +++ b/internal/db/queries/library_changes.sql @@ -22,11 +22,34 @@ LIMIT $2; -- name: GetMaxLibraryChangeCursor :one SELECT COALESCE(MAX(id), 0)::BIGINT FROM library_changes; --- name: GetMinLibraryChangeCursor :one -SELECT COALESCE(MIN(id), 0)::BIGINT FROM library_changes; +-- name: GetLastIssuedLibraryChangeCursor :one +-- The highest cursor this server has handed out, even once the compactor has +-- trimmed the rows: the id sequence's last value. A restored server's +-- sequence stands at the backup's last change. +SELECT COALESCE(pg_sequence_last_value(pg_get_serial_sequence('library_changes', 'id')::regclass), 0)::BIGINT; --- name: DeleteOldLibraryChanges :execrows --- Removes library_changes rows older than the given cutoff. Run from --- the sync compactor goroutine on a daily tick. Returns the number of --- rows deleted so the worker can log meaningful progress. -DELETE FROM library_changes WHERE changed_at < $1; +-- name: GetLibraryChangesTrimmedThrough :one +-- The highest id of a delete the compactor has dropped. A cursor below it may +-- have missed that delete. +SELECT through FROM library_changes_trimmed; + +-- name: DeleteSupersededLibraryChanges :execrows +-- Removes every row a newer row for the same entity has superseded. An app +-- reading from any cursor still meets the newer row, so it loses nothing. +DELETE FROM library_changes old + WHERE EXISTS (SELECT 1 FROM library_changes newer + WHERE newer.entity_type = old.entity_type + AND newer.entity_id = old.entity_id + AND newer.id > old.id); + +-- name: DeleteOldLibraryDeletes :one +-- Removes deletes older than the cutoff and raises the trimmed mark past the +-- highest one, so an app whose cursor is below it starts over. Returns how +-- many went. +WITH gone AS ( + DELETE FROM library_changes WHERE op = 'delete' AND changed_at < $1 RETURNING id +), mark AS ( + UPDATE library_changes_trimmed + SET through = GREATEST(through, (SELECT COALESCE(max(id), 0) FROM gone)) +) +SELECT count(*)::BIGINT FROM gone; diff --git a/internal/db/queries/library_settings.sql b/internal/db/queries/library_settings.sql index 99d0fd37..cab5dc23 100644 --- a/internal/db/queries/library_settings.sql +++ b/internal/db/queries/library_settings.sql @@ -23,17 +23,6 @@ UPDATE albums SET cover_art_path = sqlc.arg(new_root)::text || substr(cover_art_path, length(sqlc.arg(old_root)::text) + 1) WHERE starts_with(cover_art_path, sqlc.arg(old_root)::text || '/'); --- name: RerootGrabDestinations :execrows -UPDATE grabs - SET destination = sqlc.arg(new_root)::text || substr(destination, length(sqlc.arg(old_root)::text) + 1) - WHERE destination = sqlc.arg(old_root)::text - OR starts_with(destination, sqlc.arg(old_root)::text || '/'); - --- name: RerootImportRoot :execrows -UPDATE acquisition_settings - SET import_root = sqlc.arg(new_root)::text - WHERE import_root = sqlc.arg(old_root)::text; - -- name: SampleTrackPathsUnder :many -- A few present tracks under a folder, to check a move before rewriting it. SELECT file_path FROM tracks diff --git a/internal/db/queries/lifecycle.sql b/internal/db/queries/lifecycle.sql deleted file mode 100644 index 8b5b21c0..00000000 --- a/internal/db/queries/lifecycle.sql +++ /dev/null @@ -1,102 +0,0 @@ --- The download lifecycle: the intervention ledger, giving a --- download up, and seeding after import. - --- name: RaiseIntervention :one --- A condition seen, or seen again: a second pass lands on the open row, so --- a download stuck for a week is one row that says how long. The name only --- improves, and the detail is the latest word. -INSERT INTO download_interventions (client, info_hash, grab_id, name, trigger, detail) -VALUES (sqlc.arg(client), sqlc.arg(info_hash), sqlc.narg(grab_id), sqlc.arg(name), - sqlc.arg(trigger), sqlc.arg(detail)) -ON CONFLICT (client, info_hash, trigger) WHERE outcome = 'open' DO UPDATE SET - observations = download_interventions.observations + 1, - last_seen = now(), - detail = EXCLUDED.detail, - grab_id = COALESCE(EXCLUDED.grab_id, download_interventions.grab_id), - name = CASE WHEN EXCLUDED.name <> '' THEN EXCLUDED.name ELSE download_interventions.name END -RETURNING *; - --- name: SettleIntervention :execrows --- The condition cleared. -UPDATE download_interventions - SET outcome = 'resolved', settled_at = now(), last_seen = now() - WHERE client = sqlc.arg(client) AND info_hash = sqlc.arg(info_hash) - AND trigger = sqlc.arg(trigger) AND outcome = 'open'; - --- name: SettleInterventionsFor :execrows --- Everything open about one download is over: it is gone from the client. -UPDATE download_interventions - SET outcome = 'resolved', settled_at = now(), last_seen = now() - WHERE client = sqlc.arg(client) AND info_hash = sqlc.arg(info_hash) AND outcome = 'open'; - --- name: SettleEndedGrabs :execrows --- What was wrong with a download whose grab has ended (imported, refused, --- given up) is over, except a download left in the client to remove. -UPDATE download_interventions di - SET outcome = 'resolved', settled_at = now(), last_seen = now() - FROM grabs g - WHERE g.id = di.grab_id AND g.ended_at IS NOT NULL - AND di.outcome = 'open' AND di.trigger <> 'not_removed'; - --- name: CountRemediation :one --- Minstrel acted on an open condition. A retry climbs the ladder; giving up --- or removing ends the condition, since what it was about is gone. Written --- before the act, so a retry that happened is never uncounted. -UPDATE download_interventions - SET remediations = remediations + 1, - action = sqlc.arg(action), - last_seen = now(), - outcome = CASE WHEN sqlc.arg(action)::text IN ('given_up', 'removed') THEN 'resolved' ELSE outcome END, - settled_at = CASE WHEN sqlc.arg(action)::text IN ('given_up', 'removed') THEN now() ELSE settled_at END - WHERE client = sqlc.arg(client) AND info_hash = sqlc.arg(info_hash) - AND trigger = sqlc.arg(trigger) AND outcome = 'open' -RETURNING remediations; - --- name: ListLeftovers :many --- Downloads given up on that the client would not remove; each pass asks --- again. -SELECT * FROM download_interventions - WHERE trigger = 'not_removed' AND outcome = 'open' AND info_hash <> '' - ORDER BY first_seen; - --- name: ListClientsDown :many --- Download clients not answering now, for the Activity tab. -SELECT client, detail, first_seen FROM download_interventions - WHERE trigger = 'client_unreachable' AND outcome = 'open' - ORDER BY client; - --- name: LiveGrabOnHash :one -SELECT EXISTS (SELECT 1 FROM grabs WHERE info_hash = sqlc.arg(info_hash) AND ended_at IS NULL)::bool; - --- name: GiveUpGrab :one --- Ends a running grab, given up on. Only from the states named: the update --- is the lock against an import that claimed the download meanwhile. -UPDATE grabs - SET ended_at = now(), end_reason = sqlc.arg(end_reason), end_detail = sqlc.arg(end_detail), - import_updated_at = now() - WHERE id = sqlc.arg(id) AND ended_at IS NULL AND import_state = ANY(sqlc.arg(states)::text[]) -RETURNING *; - --- name: CountGoneGrabs :one --- How many of a release's grabs ended gone since a time: a release that keeps --- leaving its client is held back rather than taken on every pass. -SELECT count(*) FROM grabs - WHERE info_hash = sqlc.arg(info_hash) AND end_reason = 'gone' AND ended_at > sqlc.arg(since); - --- name: ListSeedingGrabs :many --- Imported downloads still sharing, oldest import first. -SELECT id, client, info_hash, name, imported_at FROM grabs - WHERE seeding AND seed_released_at IS NULL - ORDER BY imported_at, id; - --- name: SetGrabRatio :exec -UPDATE grabs SET ratio = sqlc.arg(ratio) WHERE id = sqlc.arg(id); - --- name: ReleaseSeed :exec --- The seeding download was removed, or found gone. -UPDATE grabs SET seed_released_at = now() WHERE id = $1 AND seed_released_at IS NULL; - --- name: DeleteExpiredBlocks :execrows --- A release given up on is held back for a while; after that the search may --- take it again. -DELETE FROM release_blocks WHERE expires_at IS NOT NULL AND expires_at <= now(); diff --git a/internal/db/queries/likes.sql b/internal/db/queries/likes.sql index 11289c29..f1c596ae 100644 --- a/internal/db/queries/likes.sql +++ b/internal/db/queries/likes.sql @@ -33,6 +33,26 @@ JOIN (SELECT DISTINCT ON (lt.song_key) l.track_id, l.liked_at ORDER BY l.liked_at DESC, t.id LIMIT $2 OFFSET $3; +-- name: ListPlayableLikedTrackRows :many +-- Subsonic's starred songs: one row per liked song the listener can play, so +-- a copy present on disk and not quarantined by them, preferring one that is +-- not a held-back video rip, then the one liked first. Subsonic has no way to +-- show a song as unplayable; an app would only fail to stream it, or play the +-- copy the listener hid. Filtered here rather than after the LIMIT so the cap +-- counts playable songs. +SELECT t.* FROM tracks t +JOIN (SELECT DISTINCT ON (lt.song_key) l.track_id, l.liked_at + FROM general_likes l + JOIN tracks lt ON lt.id = l.track_id + WHERE l.user_id = sqlc.arg(user_id) + AND lt.missing_since IS NULL + AND NOT EXISTS (SELECT 1 FROM quarantine q + WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = lt.id) + ORDER BY lt.song_key, (lt.source_verdict IS NOT DISTINCT FROM 'suspect'), l.liked_at, lt.id) l + ON l.track_id = t.id +ORDER BY l.liked_at DESC, t.id +LIMIT sqlc.arg(row_limit); + -- name: CountLikedTracks :one -- Liked songs, each counted once however many releases hold it. SELECT count(DISTINCT t.song_key) FROM general_likes l diff --git a/internal/db/queries/lookup_settings.sql b/internal/db/queries/lookup_settings.sql new file mode 100644 index 00000000..10a0c3c0 --- /dev/null +++ b/internal/db/queries/lookup_settings.sql @@ -0,0 +1,10 @@ +-- name: GetLookupSettings :one +SELECT * FROM lookup_settings WHERE id = true; + +-- name: UpdateLookupSettings :one +UPDATE lookup_settings + SET listenbrainz_similarity = sqlc.arg(listenbrainz_similarity), + musicbrainz_track_lists = sqlc.arg(musicbrainz_track_lists), + updated_at = now() + WHERE id = true +RETURNING *; diff --git a/internal/db/queries/merge.sql b/internal/db/queries/merge.sql index 4ea5001d..851e66c3 100644 --- a/internal/db/queries/merge.sql +++ b/internal/db/queries/merge.sql @@ -33,10 +33,6 @@ UPDATE contextual_likes SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_i -- name: MergeRepointPlaybackErrors :execrows UPDATE playback_errors SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_id = sqlc.arg(loser_id)::uuid; --- name: MergeRepointRequests :execrows -UPDATE requests SET matched_track_id = sqlc.arg(survivor_id)::uuid - WHERE matched_track_id = sqlc.arg(loser_id)::uuid; - -- name: MergeRepointPlaylistTracks :many -- playlist_tracks is keyed by (playlist_id, position), so repointing keeps every -- entry exactly where it was. A playlist that held both copies simply holds the diff --git a/internal/db/queries/missing_pairs.sql b/internal/db/queries/missing_pairs.sql index f7eec982..3ebbc0f1 100644 --- a/internal/db/queries/missing_pairs.sql +++ b/internal/db/queries/missing_pairs.sql @@ -1,7 +1,7 @@ -- Missing-pair pass. A track marked missing whose replacement is already -- on disk under another row — most often a quality upgrade, mp3 → flac at a new -- path — is folded into that replacement, so its history moves across and --- re-acquisition stops chasing music the library already has. +-- the track stops waiting for a file the library already has. -- -- Move adoption cannot catch these: it links a new file to a missing row -- at the moment the file is first inserted, and the replacement arrives as a @@ -26,7 +26,7 @@ -- they are different recordings. The caller folds a pair only when each side has -- exactly one candidate; anything else is ambiguous and left alone. -- --- A slot the duplicate resolver emptied (emptied_at, migration 0095) pairs by +-- A slot the duplicate resolver emptied (emptied_at) pairs by -- title only with a track added since: the album held no copy of the song as -- long as it is, so one already there under the title is another song. WITH grp AS ( diff --git a/internal/db/queries/normalization_prefs.sql b/internal/db/queries/normalization_prefs.sql index ebe3eb30..599f9d28 100644 --- a/internal/db/queries/normalization_prefs.sql +++ b/internal/db/queries/normalization_prefs.sql @@ -4,7 +4,7 @@ SELECT mode, target_lufs, boost, updated_at WHERE user_id = $1; -- name: UpsertNormalizationPrefs :one --- Whole-row write from either client; the CHECKs in migration 0067 back the +-- Whole-row write from either client; the CHECKs on user_normalization_prefs back the -- handler's own validation. INSERT INTO user_normalization_prefs (user_id, mode, target_lufs, boost) VALUES (sqlc.arg(user_id), sqlc.arg(mode), sqlc.arg(target_lufs), sqlc.arg(boost)) diff --git a/internal/db/queries/notifications.sql b/internal/db/queries/notifications.sql index 34e15991..a79a949a 100644 --- a/internal/db/queries/notifications.sql +++ b/internal/db/queries/notifications.sql @@ -83,6 +83,9 @@ DELETE FROM user_notifications -- name: ListAdminUserIDs :many SELECT id FROM users WHERE is_admin = true ORDER BY created_at, id; +-- name: ListUserIDs :many +SELECT id FROM users ORDER BY created_at, id; + -- name: ListNotificationPrefsForUser :many SELECT kind, inbox, phone, email FROM user_notification_prefs @@ -151,7 +154,7 @@ ON CONFLICT (user_id, email_group) DO UPDATE SET SELECT * FROM notification_email_settings WHERE id = true; -- name: UpdateNotificationEmailSettings :one --- Migration 0074's CHECKs are the backstop behind the service's validation. +-- notification_email_settings's CHECKs are the backstop behind the service's validation. UPDATE notification_email_settings SET summary_hour = sqlc.arg(summary_hour), batch_window_minutes = sqlc.arg(batch_window_minutes), diff --git a/internal/db/queries/password_resets.sql b/internal/db/queries/password_resets.sql index 8ff57f22..5ffc6f08 100644 --- a/internal/db/queries/password_resets.sql +++ b/internal/db/queries/password_resets.sql @@ -15,8 +15,3 @@ UPDATE password_resets WHERE token = $1 AND used_at IS NULL AND expires_at > now(); - --- name: DeleteExpiredPasswordResets :exec --- Cleanup: drop tokens that have been expired more than 7 days. --- Not wired in U3; useful to have for a future cron sweep. -DELETE FROM password_resets WHERE expires_at < now() - interval '7 days'; diff --git a/internal/db/queries/play_queue.sql b/internal/db/queries/play_queue.sql new file mode 100644 index 00000000..2c5c6b9d --- /dev/null +++ b/internal/db/queries/play_queue.sql @@ -0,0 +1,16 @@ +-- name: GetPlayQueue :one +SELECT * FROM play_queues WHERE user_id = $1; + +-- name: SavePlayQueue :exec +-- Replaces the user's saved queue. +INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_at, changed_by) +VALUES (sqlc.arg(user_id), sqlc.arg(track_ids)::uuid[], sqlc.narg(current_track_id), sqlc.arg(position_ms), now(), sqlc.arg(changed_by)) +ON CONFLICT (user_id) DO UPDATE + SET track_ids = EXCLUDED.track_ids, + current_track_id = EXCLUDED.current_track_id, + position_ms = EXCLUDED.position_ms, + changed_at = EXCLUDED.changed_at, + changed_by = EXCLUDED.changed_by; + +-- name: DeletePlayQueue :exec +DELETE FROM play_queues WHERE user_id = $1; diff --git a/internal/db/queries/playlists.sql b/internal/db/queries/playlists.sql index 92585184..c33523b7 100644 --- a/internal/db/queries/playlists.sql +++ b/internal/db/queries/playlists.sql @@ -1,6 +1,10 @@ -- name: CreatePlaylist :one -INSERT INTO playlists (user_id, name, description, is_public) -VALUES ($1, $2, $3, $4) +-- id is the client's own id for the list, or NULL for a new one. A client +-- that made the list offline sends its id again on every retry, so an id +-- already taken inserts nothing and returns no row. +INSERT INTO playlists (id, user_id, name, description, is_public) +VALUES (COALESCE(sqlc.narg(id)::uuid, gen_random_uuid()), sqlc.arg(user_id), sqlc.arg(name), sqlc.arg(description), sqlc.arg(is_public)) +ON CONFLICT (id) DO NOTHING RETURNING *; -- name: GetPlaylist :one @@ -42,13 +46,29 @@ SET WHERE id = $1; -- name: SetPlaylistCover :exec -UPDATE playlists SET cover_path = $2, updated_at = now() WHERE id = $1; +-- Only a changed path counts as a change to the playlist: a collage drawn +-- again to the same file leaves updated_at alone. +UPDATE playlists SET cover_path = $2, updated_at = now() + WHERE id = $1 AND cover_path IS DISTINCT FROM $2; + +-- name: ListUserPlaylistIDsForOwner :many +-- The playlists a person made, not their system mixes. +SELECT id FROM playlists WHERE user_id = $1 AND kind = 'user' ORDER BY id; -- name: DeletePlaylist :one -- Returns cover_path so the caller can clean up the cached collage on disk. DELETE FROM playlists WHERE id = $1 RETURNING id, cover_path; +-- name: ListPlaylistEntriesForUpdate :many +-- The track at each position, locking the rows while a reorder rewrites +-- them. +SELECT position, track_id +FROM playlist_tracks +WHERE playlist_id = $1 +ORDER BY position +FOR UPDATE; + -- name: ListPlaylistTracks :many -- Joined to tracks for the live track id (the service layer derives the -- stream URL from it); LEFT JOIN preserves the row when track_id is NULL @@ -83,7 +103,7 @@ SELECT COALESCE((SELECT MAX(position) + 1 FROM playlist_tracks WHERE playlist_id = sqlc.arg(playlist_id)::uuid), 0), t.id, t.title, - artists.name, + COALESCE(t.artist_credit, artists.name), albums.title, (t.duration_ms / 1000)::integer, sqlc.narg(pick_kind)::text @@ -93,6 +113,19 @@ JOIN artists ON artists.id = t.artist_id WHERE t.id = sqlc.arg(track_id)::uuid RETURNING *; +-- name: RecordPlaylistAppendRequest :execrows +-- Claims a client's append request id for the playlist. No row affected +-- means the id was already applied: the append is a replay. +INSERT INTO playlist_append_requests (playlist_id, request_id) +VALUES (sqlc.arg(playlist_id)::uuid, sqlc.arg(request_id)::uuid) +ON CONFLICT DO NOTHING; + +-- name: PrunePlaylistAppendRequests :exec +-- Forgets the playlist's append request ids older than 30 days, by which +-- time any queued replay of them has long since been sent. +DELETE FROM playlist_append_requests +WHERE playlist_id = $1 AND created_at < now() - interval '30 days'; + -- name: DeletePlaylistTrack :exec -- Two-step: delete the row at `position`, then renumber subsequent rows -- to close the gap. The renumber is a single UPDATE; the service layer @@ -122,3 +155,22 @@ LIMIT $2; -- Batched lookup used by /api/library/sync to hydrate upsert payloads --. Mirror of GetArtistsByIDs. SELECT * FROM playlists WHERE id = ANY($1::uuid[]); + +-- name: ListPlaylistCoverAlbums :many +-- The albums a playlist's tiles can show: up to six distinct albums with +-- cover art per playlist, in the order they first appear in its tracks. +-- More than one per playlist, so a shelf of tiles can give each one a +-- cover no other tile on the shelf is already showing. +SELECT s.playlist_id, + (array_agg(s.album_id ORDER BY s.first_position))[1:6]::uuid[] AS album_ids +FROM ( + SELECT pt.playlist_id, t.album_id, MIN(pt.position) AS first_position + FROM playlist_tracks pt + JOIN tracks t ON t.id = pt.track_id + JOIN albums a ON a.id = t.album_id + WHERE pt.playlist_id = ANY(sqlc.arg(playlist_ids)::uuid[]) + AND a.cover_art_path IS NOT NULL + AND a.cover_art_path <> '' + GROUP BY pt.playlist_id, t.album_id +) s +GROUP BY s.playlist_id; diff --git a/internal/db/queries/reacquisition.sql b/internal/db/queries/reacquisition.sql deleted file mode 100644 index be665a19..00000000 --- a/internal/db/queries/reacquisition.sql +++ /dev/null @@ -1,93 +0,0 @@ --- Re-acquisition of missing files. --- The unit is the album: an album whose files went missing becomes a want for --- its release group, and the search schedule looks for it. - --- name: GetReacquisitionSettings :one -SELECT * FROM reacquisition_settings WHERE id = true; - --- name: UpdateReacquisitionSettings :one --- Whole-row write from the admin card; the CHECKs in migration 0056 are the --- validation, so a bad value fails loudly rather than being clamped silently. -UPDATE reacquisition_settings - SET enabled = sqlc.arg(enabled), - grace_hours = sqlc.arg(grace_hours), - max_per_pass = sqlc.arg(max_per_pass) - WHERE id = true -RETURNING *; - --- name: ListAlbumsDueReacquisition :many --- The sweeper's selection. An album qualifies when: --- --- * it still has at least one track whose file has been missing longer than --- the grace window. Measured on missing_since, which reconcile never --- re-stamps, so it is a genuine "gone since" clock; --- * MusicBrainz can name it: the artist has an MBID, and the album a --- release MBID or a release group. The release MBID is only ever used to --- find the group, and an album matched to a group may carry no release --- id. Albums failing this are counted separately --- (CountAlbumsMissingWithoutMbid); --- * it is on the wanted list: an album taken off the list, or --- dropped into the library by hand, is not fetched back; --- * no want already covers it: none open, and none held since its files --- went missing. A want held after the loss means the library has a full --- copy despite the missing rows, so asking again would loop. -SELECT albums.id AS album_id, - albums.title AS album_title, - albums.mbid AS album_mbid, - albums.release_group_mbid AS album_release_group_mbid, - artists.name AS artist_name, - artists.mbid AS artist_mbid, - COUNT(tracks.id)::bigint AS missing_track_count, - MAX(tracks.missing_since)::timestamptz AS last_missing_since - FROM albums - JOIN artists ON artists.id = albums.artist_id - JOIN tracks ON tracks.album_id = albums.id - WHERE tracks.missing_since IS NOT NULL - AND tracks.missing_since <= now() - make_interval(hours => sqlc.arg(grace_hours)::int) - AND (albums.mbid IS NOT NULL OR albums.release_group_mbid IS NOT NULL) - AND artists.mbid IS NOT NULL - GROUP BY albums.id, albums.title, albums.mbid, albums.release_group_mbid, - artists.name, artists.mbid -HAVING EXISTS ( - SELECT 1 FROM wants w - WHERE w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid) - AND NOT EXISTS ( - SELECT 1 FROM wants w - WHERE (w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid) - AND (w.fulfilled_at IS NULL OR w.fulfilled_at > MAX(tracks.missing_since))) - ORDER BY MIN(tracks.missing_since), albums.sort_title - LIMIT sqlc.arg(page_limit); - --- name: CountAlbumsMissingWithoutMbid :one --- Albums with missing files that can never be wanted automatically because --- nothing identifies them to MusicBrainz. Surfaced on the admin card so the --- gap is visible: silently doing nothing for these would read as broken. -SELECT COUNT(DISTINCT albums.id)::bigint - FROM albums - JOIN artists ON artists.id = albums.artist_id - JOIN tracks ON tracks.album_id = albums.id - WHERE tracks.missing_since IS NOT NULL - AND ((albums.mbid IS NULL AND albums.release_group_mbid IS NULL) OR artists.mbid IS NULL); - --- name: WantMissingAlbum :one --- Records an album with missing files as wanted. A held want for the same --- group is reopened; an open one is left as it is, and no row comes back. -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id) -VALUES (sqlc.arg(release_group_mbid), sqlc.arg(artist_mbid), sqlc.arg(artist_name), - sqlc.arg(title), 'missing', sqlc.arg(album_id)) -ON CONFLICT (release_group_mbid) DO UPDATE - SET reason = 'missing', - album_id = EXCLUDED.album_id, - wanted_at = now(), - fulfilled_at = NULL, - updated_at = now() - WHERE wants.fulfilled_at IS NOT NULL -RETURNING *; - --- name: GetWantsForAlbums :many --- What the wanted list says about each album on the missing-files page. -SELECT a.id AS album_id, w.id AS want_id, w.wanted_at, w.fulfilled_at - FROM albums a - JOIN wants w ON w.album_id = a.id OR w.release_group_mbid = a.release_group_mbid - WHERE a.id = ANY(sqlc.arg(album_ids)::uuid[]) - ORDER BY w.wanted_at DESC; diff --git a/internal/db/queries/recommendation.sql b/internal/db/queries/recommendation.sql index d4c3c805..b92e87a1 100644 --- a/internal/db/queries/recommendation.sql +++ b/internal/db/queries/recommendation.sql @@ -310,109 +310,6 @@ WHERE user_id = $1 ORDER BY started_at DESC LIMIT 1; --- name: SuggestArtistsForUser :many --- Per-user artist suggestions ranked by taste signal x similarity, projected --- through artist_similarity_unmatched (out-of-library candidates only). --- --- Seeds are TIERED so the surface never empties: --- tier 1 - taste_profile_artists.weight: engagement-graded, time-decayed and --- SIGNED by internal/taste, so an artist the user has drifted away --- from stops contributing instead of accumulating forever. --- tier 2 - likes + completed plays, used ONLY when the profile has no rows --- (new account, or before the first daily recompute). --- --- The signal is log-damped: contribution is signal x similarity, and an --- undamped sum would let one heavily-played artist's neighbours take every --- slot -- entrenching harder the MORE the user listened. --- --- Candidates already in the library, already requested and not terminal, or --- snoozed by this user, are excluded. $1=user_id, $2=half_life_days (tier 2 --- decay), $3=limit. -WITH artist_plays AS ( - -- Completed plays only: counting every play_event would make skipping an - -- artist repeatedly INCREASE its signal and push more of its neighbours - -- at the user. - SELECT t.artist_id, count(*)::bigint AS play_count - FROM play_events pe - JOIN tracks t ON t.id = pe.track_id - WHERE pe.user_id = $1 AND pe.was_skipped = false - GROUP BY t.artist_id -), -profile_seeds AS ( - SELECT tpa.artist_id, tpa.weight AS raw_signal - FROM taste_profile_artists tpa - WHERE tpa.user_id = $1 AND tpa.weight > 0 -), -fallback_seeds AS ( - SELECT a.id AS artist_id, - 5.0 * (CASE WHEN gla.artist_id IS NOT NULL THEN 1 ELSE 0 END) - + COALESCE(SUM(EXP(- EXTRACT(epoch FROM now() - pe.started_at) / ($2::float8 * 86400.0))), 0) - AS raw_signal - FROM artists a - LEFT JOIN general_likes_artists gla ON gla.artist_id = a.id AND gla.user_id = $1 - LEFT JOIN tracks t ON t.artist_id = a.id - LEFT JOIN play_events pe - ON pe.track_id = t.id AND pe.user_id = $1 AND pe.was_skipped = false - WHERE (gla.artist_id IS NOT NULL OR pe.id IS NOT NULL) - AND NOT EXISTS (SELECT 1 FROM profile_seeds) - GROUP BY a.id, gla.artist_id -), -seeds AS ( - SELECT s.artist_id, - ln(1.0 + s.raw_signal) AS signal, - (gla.artist_id IS NOT NULL) AS is_liked, - COALESCE(ap.play_count, 0)::bigint AS play_count - FROM ( - SELECT artist_id, raw_signal FROM profile_seeds - UNION ALL - SELECT artist_id, raw_signal FROM fallback_seeds - ) s - LEFT JOIN general_likes_artists gla - ON gla.artist_id = s.artist_id AND gla.user_id = $1 - LEFT JOIN artist_plays ap ON ap.artist_id = s.artist_id - WHERE s.raw_signal > 0 -), -contributions AS ( - SELECT u.candidate_mbid, - u.candidate_name, - seeds.artist_id AS seed_id, - seeds.is_liked, - seeds.play_count, - seeds.signal * u.score AS contribution - FROM artist_similarity_unmatched u - JOIN seeds ON seeds.artist_id = u.seed_artist_id - WHERE NOT EXISTS (SELECT 1 FROM artists WHERE mbid = u.candidate_mbid) - AND NOT EXISTS ( - SELECT 1 FROM requests r - WHERE r.user_id = $1 - AND r.artist_mbid = u.candidate_mbid - AND r.status NOT IN ('rejected', 'failed') - ) - -- Snoozed by this user and not yet expired. Time-boxed and - -- per-user: the candidate returns on its own once snoozed_until - -- passes, and stays visible to everyone else meanwhile. Deliberately - -- filtered at the candidate stage, NOT folded into the score — a - -- snooze carries no opinion about the music, so it must not become a - -- ranking signal. - AND NOT EXISTS ( - SELECT 1 FROM suggestion_snoozes s - WHERE s.user_id = $1 - AND s.candidate_mbid = u.candidate_mbid - AND s.snoozed_until > now() - ) -) -SELECT candidate_mbid, - candidate_name, - SUM(contribution)::float8 AS total_score, - ((array_agg(seed_id ORDER BY contribution DESC))[1:3])::uuid[] AS top_seed_ids, - ((array_agg(contribution ORDER BY contribution DESC))[1:3])::float8[] AS top_contributions, - ((array_agg(is_liked ORDER BY contribution DESC))[1:3])::boolean[] AS top_is_liked, - ((array_agg(play_count ORDER BY contribution DESC))[1:3])::bigint[] AS top_play_counts -FROM contributions -GROUP BY candidate_mbid, candidate_name -ORDER BY total_score DESC -LIMIT $3; - -- name: ListMostPlayedTracksForUser :many -- Top-N tracks by completed-play count for the user. was_skipped -- excludes skips so a user spamming next doesn't fabricate a top track. diff --git a/internal/db/queries/recommendation_tuning.sql b/internal/db/queries/recommendation_tuning.sql index 49c627ed..215c23d9 100644 --- a/internal/db/queries/recommendation_tuning.sql +++ b/internal/db/queries/recommendation_tuning.sql @@ -53,24 +53,6 @@ UPDATE taste_tuning WHERE singleton = true RETURNING *; --- name: UpsertDiscoverTuningDefaults :exec --- Boot reconcile for the Discover scope. Never overwrites --- admin-tuned values, same contract as the other two. -INSERT INTO discover_tuning (singleton, tag_overlap_weight, snooze_days) -VALUES (true, $1, $2) -ON CONFLICT (singleton) DO NOTHING; - --- name: GetDiscoverTuning :one -SELECT * FROM discover_tuning WHERE singleton = true; - --- name: UpdateDiscoverTuning :one -UPDATE discover_tuning - SET tag_overlap_weight = $1, - snooze_days = $2, - updated_at = now() - WHERE singleton = true -RETURNING *; - -- name: InsertTuningAudit :exec -- changes is a jsonb array of {field, old, new} objects. INSERT INTO recommendation_tuning_audit (scope, action, changes) diff --git a/internal/db/queries/registration_settings.sql b/internal/db/queries/registration_settings.sql deleted file mode 100644 index 6dab0ea7..00000000 --- a/internal/db/queries/registration_settings.sql +++ /dev/null @@ -1,5 +0,0 @@ --- name: GetRegistrationMode :one -SELECT mode FROM registration_settings WHERE id = true; - --- name: SetRegistrationMode :exec -UPDATE registration_settings SET mode = $1 WHERE id = true; diff --git a/internal/db/queries/requests.sql b/internal/db/queries/requests.sql deleted file mode 100644 index 7eff0d01..00000000 --- a/internal/db/queries/requests.sql +++ /dev/null @@ -1,119 +0,0 @@ --- name: CreateRequest :one -INSERT INTO requests ( - user_id, kind, - artist_mbid, album_mbid, track_mbid, - artist_name, album_title, track_title -) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) -RETURNING *; - --- name: GetRequestByID :one -SELECT * FROM requests WHERE id = $1; - --- name: ListRequestsForUser :many -SELECT * FROM requests -WHERE user_id = $1 -ORDER BY requested_at DESC -LIMIT $2; - --- name: ListRequestsByStatus :many -SELECT * FROM requests -WHERE status = $1 -ORDER BY requested_at DESC -LIMIT $2; - --- name: ListApprovedRequestsForReconcile :many -SELECT * FROM requests -WHERE status = 'approved' -ORDER BY decided_at ASC -LIMIT $1; - --- name: ApproveRequest :one -UPDATE requests - SET status = 'approved', - decided_at = now(), - decided_by = $2, - updated_at = now() - WHERE id = $1 AND status = 'pending' - RETURNING *; - --- name: RejectRequest :one -UPDATE requests - SET status = 'rejected', - notes = $2, - decided_at = now(), - decided_by = $3, - updated_at = now() - WHERE id = $1 AND status = 'pending' - RETURNING *; - --- name: CancelRequest :one --- $2 serves as both the ownership guard (user_id = $2) and the --- decided_by audit field. The generated parameter struct names it --- DecidedBy — callers must pass the cancelling user's UUID, and --- a wrong UUID will silently no-op (zero rows updated) rather than --- erroring at the SQL layer. -UPDATE requests - SET status = 'rejected', - notes = 'cancelled by user', - decided_at = now(), - decided_by = $2, - updated_at = now() - WHERE id = $1 AND user_id = $2 AND status = 'pending' - RETURNING *; - --- name: CompleteRequest :one --- Reconciler transitions an approved request to completed when its --- target track/album/artist has appeared in the library. Callers --- should set ONLY the matched_*_id corresponding to the request's --- kind and pass pgtype.UUID{} (Valid: false) for the others — --- per-kind one-of-three is the contract, NULL for the others --- preserves auditability if the matched row is later evicted. -UPDATE requests - SET status = 'completed', - matched_track_id = $2, - matched_album_id = $3, - matched_artist_id = $4, - completed_at = now(), - updated_at = now() - WHERE id = $1 AND status = 'approved' - RETURNING *; - --- name: HasNonTerminalRequestForMBID :one --- Whether something is already on its way: a pending, approved or completed --- request at the given level, an open want for the release group, or a --- follow of the artist. Sets the `requested` flag on catalogue search. --- Terminal-status (rejected, failed) requests do not count. MBIDs are unique --- per entity type, so checking one id against every column cannot --- false-match. -SELECT (EXISTS ( - SELECT 1 FROM requests r - WHERE r.status IN ('pending', 'approved', 'completed') - AND ((r.kind = 'artist' AND r.artist_mbid = @mbid) - OR (r.kind = 'album' AND r.album_mbid = @mbid) - OR (r.kind = 'track' AND r.track_mbid = @mbid)) -) OR EXISTS ( - SELECT 1 FROM wants w WHERE w.release_group_mbid = @mbid AND w.fulfilled_at IS NULL -) OR EXISTS ( - SELECT 1 FROM follows f WHERE f.artist_mbid = @mbid -))::bool AS requested; - --- name: GetNonTerminalRequestForMBID :one --- Returns the oldest non-terminal (pending/approved/completed) request --- whose own-kind MBID matches @mbid, or pgx.ErrNoRows when none. Create() --- uses this to dedupe: a re-request for something already in flight --- returns the existing row instead of inserting a duplicate. -SELECT * FROM requests - WHERE status IN ('pending', 'approved', 'completed') - AND ((kind = 'artist' AND artist_mbid = @mbid) - OR (kind = 'album' AND album_mbid = @mbid) - OR (kind = 'track' AND track_mbid = @mbid)) - ORDER BY requested_at ASC - LIMIT 1; - --- name: RepointRequestsAlbumMbid :exec --- A want moved from a release id to its group takes the requests --- that name it along, so the reconciler finds it. -UPDATE requests - SET album_mbid = sqlc.arg(new_mbid), - updated_at = now() - WHERE album_mbid = sqlc.arg(old_mbid); diff --git a/internal/db/queries/scan_runs.sql b/internal/db/queries/scan_runs.sql index 03d1856d..f4cd1502 100644 --- a/internal/db/queries/scan_runs.sql +++ b/internal/db/queries/scan_runs.sql @@ -38,6 +38,15 @@ UPDATE scan_runs SET artist_art_enrich = $2 WHERE id = $1; +-- name: FailUnfinishedScanRuns :execrows +-- At startup no scan can be running yet, so a row still unfinished was cut +-- off when the server last stopped. Closing it keeps it from reading as a +-- scan in progress, which would block saving library folders. +UPDATE scan_runs + SET finished_at = now(), + error_message = 'The server stopped while the scan was running.' + WHERE finished_at IS NULL; + -- name: GetInFlightScanRun :one -- Used by POST /api/admin/scan/run to 409 when a scan is already running. -- "In flight" = finished_at IS NULL. diff --git a/internal/db/queries/scrobble.sql b/internal/db/queries/scrobble.sql index bc71b0d9..8e40a702 100644 --- a/internal/db/queries/scrobble.sql +++ b/internal/db/queries/scrobble.sql @@ -23,7 +23,8 @@ SELECT t.mbid AS track_mbid, al.title AS album_title, al.mbid AS album_mbid, - ar.name AS artist_name, + -- The full credit: ListenBrainz and Last.fm match "A feat. B" as written. + COALESCE(t.artist_credit, ar.name) AS artist_name, ar.mbid AS artist_mbid FROM scrobble_queue sq JOIN users u ON u.id = sq.user_id diff --git a/internal/db/queries/search.sql b/internal/db/queries/search.sql deleted file mode 100644 index 01c17fa3..00000000 --- a/internal/db/queries/search.sql +++ /dev/null @@ -1,141 +0,0 @@ --- Searching for wants and grabbing releases. - --- name: GetAcquisitionSettings :one -SELECT * FROM acquisition_settings WHERE id = true; - --- name: UpdateAcquisitionSettings :one -UPDATE acquisition_settings - SET auto_grab = sqlc.arg(auto_grab), - search_interval_hours = sqlc.arg(search_interval_hours), - allowed_qualities = sqlc.arg(allowed_qualities), - import_root = sqlc.arg(import_root), - seed_ratio = sqlc.arg(seed_ratio), - seed_days = sqlc.arg(seed_days), - stall_hours = sqlc.arg(stall_hours), - upgrade_until = sqlc.arg(upgrade_until), - updated_at = now() - WHERE id = true -RETURNING *; - --- name: RecordSearchPass :exec -UPDATE acquisition_settings SET last_pass_at = now(), last_pass = sqlc.arg(report) WHERE id = true; - --- name: ListWantsDueForSearch :many --- Wants with no download running that were never searched or not since --- @hours ago: open wants first (never-searched, then requests, then missing --- files, then followed artists' releases), then held albums wanted for an --- upgrade, which are searched at most weekly. -SELECT w.id, w.release_group_mbid, w.artist_name, w.title, w.reason, w.upgrade, w.held_tier, w.held_quality, - COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type, - COALESCE(g.secondary_types, '{}')::text[] AS secondary_types, - COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date - FROM wants w - LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid - WHERE (w.fulfilled_at IS NULL OR w.upgrade <> '') - AND NOT EXISTS (SELECT 1 FROM grabs gr WHERE gr.want_id = w.id AND gr.ended_at IS NULL) - AND (w.searched_at IS NULL - OR w.searched_at < now() - make_interval(hours => CASE WHEN w.fulfilled_at IS NULL - THEN sqlc.arg(hours)::int - ELSE GREATEST(sqlc.arg(hours)::int, 168) END)) - ORDER BY w.fulfilled_at IS NOT NULL, - w.searched_at IS NOT NULL, - CASE w.reason WHEN 'request' THEN 0 WHEN 'missing' THEN 1 ELSE 2 END, - w.searched_at NULLS FIRST, w.wanted_at, w.id - LIMIT sqlc.arg(max_rows); - --- name: GetWantForSearch :one -SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.reason, w.fulfilled_at, - w.upgrade, w.held_tier, w.held_quality, w.album_id, - COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type, - COALESCE(g.secondary_types, '{}')::text[] AS secondary_types, - COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date - FROM wants w - LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid - WHERE w.id = $1; - --- name: EditionTrackSpan :one --- The fewest tracks an official edition of the group has (any edition when --- none is official), and the most any has. Zero when none is catalogued. -SELECT COALESCE(MIN(track_count) FILTER (WHERE status = 'Official'), MIN(track_count), 0)::int AS min_tracks, - COALESCE(MAX(track_count), 0)::int AS max_tracks - FROM mb_releases - WHERE release_group_mbid = $1 AND track_count > 0; - --- name: RecordWantSearch :exec -UPDATE wants - SET searched_at = now(), - search_outcome = sqlc.arg(outcome), - search_considered = sqlc.arg(considered), - best_release = sqlc.arg(best_release), - best_verdict = sqlc.arg(best_verdict), - search_error = sqlc.arg(search_error), - updated_at = now() - WHERE id = sqlc.arg(id); - --- name: DeleteWantCandidates :exec -DELETE FROM want_candidates WHERE want_id = $1; - --- name: InsertWantCandidate :exec -INSERT INTO want_candidates (want_id, key, name, info_hash, indexer, source, size_bytes, seeders, - files_count, format, quality, year, verdict, reason, reasons, folded_from, rank) -VALUES (sqlc.arg(want_id), sqlc.arg(key), sqlc.arg(name), sqlc.arg(info_hash), sqlc.arg(indexer), - sqlc.arg(source), sqlc.arg(size_bytes), sqlc.arg(seeders), sqlc.arg(files_count), sqlc.arg(format), - sqlc.arg(quality), sqlc.arg(year), sqlc.arg(verdict), sqlc.arg(reason), sqlc.arg(reasons), - sqlc.arg(folded_from), sqlc.arg(rank)) -ON CONFLICT (want_id, key) DO NOTHING; - --- name: ListWantCandidates :many -SELECT * FROM want_candidates WHERE want_id = $1 ORDER BY rank, key; - --- name: GetWantCandidate :one -SELECT * FROM want_candidates WHERE want_id = $1 AND key = $2; - --- name: MarkCandidatesBlocked :exec -UPDATE want_candidates - SET verdict = 'blocked', reason = sqlc.arg(reason), - reasons = jsonb_build_array(jsonb_build_object('kind', 'hard', 'code', 'blocked', 'text', sqlc.arg(reason)::text)) - WHERE info_hash = sqlc.arg(info_hash); - --- name: MarkCandidatesUnblocked :exec -UPDATE want_candidates - SET verdict = 'review', reason = sqlc.arg(reason), - reasons = jsonb_build_array(jsonb_build_object('kind', 'soft', 'code', 'unblocked', 'text', sqlc.arg(reason)::text)) - WHERE info_hash = sqlc.arg(info_hash) AND verdict = 'blocked'; - --- name: GetLiveGrab :one -SELECT * FROM grabs WHERE want_id = $1 AND ended_at IS NULL; - --- name: InsertGrab :one -INSERT INTO grabs (want_id, info_hash, name, key, indexer, source, client, save_path, quality, - origin, forced, grabbed_by) -VALUES (sqlc.narg(want_id), sqlc.arg(info_hash), sqlc.arg(name), sqlc.arg(key), sqlc.arg(indexer), - sqlc.arg(source), sqlc.arg(client), sqlc.arg(save_path), sqlc.arg(quality), - sqlc.arg(origin), sqlc.arg(forced), sqlc.narg(grabbed_by)) -RETURNING *; - --- name: EndGrab :exec -UPDATE grabs - SET ended_at = now(), end_reason = sqlc.arg(end_reason), end_detail = sqlc.arg(end_detail) - WHERE id = sqlc.arg(id) AND ended_at IS NULL; - --- name: ListReleaseBlocks :many --- Every release set aside and still held back: a stalled one lifts by itself --- at expires_at. -SELECT * FROM release_blocks - WHERE expires_at IS NULL OR expires_at > now() - ORDER BY blocked_at DESC; - --- name: BlockRelease :exec --- A release set aside. expires_at NULL is for good. A block for good is never --- shortened by a timed one: only a timed block, or another for good, is --- replaced. -INSERT INTO release_blocks (info_hash, name, reason, detail, want_id, blocked_by, expires_at) -VALUES (sqlc.arg(info_hash), sqlc.arg(name), sqlc.arg(reason), sqlc.arg(detail), - sqlc.narg(want_id), sqlc.narg(blocked_by), sqlc.narg(expires_at)) -ON CONFLICT (info_hash) DO UPDATE - SET reason = EXCLUDED.reason, detail = EXCLUDED.detail, blocked_at = now(), - expires_at = EXCLUDED.expires_at, blocked_by = EXCLUDED.blocked_by - WHERE release_blocks.expires_at IS NOT NULL OR EXCLUDED.expires_at IS NULL; - --- name: UnblockRelease :execrows -DELETE FROM release_blocks WHERE info_hash = $1; diff --git a/internal/db/queries/similarity.sql b/internal/db/queries/similarity.sql index b4beef0d..072c2a5d 100644 --- a/internal/db/queries/similarity.sql +++ b/internal/db/queries/similarity.sql @@ -121,18 +121,6 @@ VALUES ($1, $2, $3, 'listenbrainz', now()) ON CONFLICT (artist_a_id, artist_b_id, source) DO UPDATE SET score = EXCLUDED.score, fetched_at = EXCLUDED.fetched_at; --- name: UpsertArtistSimilarityUnmatched :exec --- Persists an out-of-library similar-artist MBID. Idempotent on --- (seed_artist_id, candidate_mbid, source) — re-fetches refresh the --- name/score and bump fetched_at. -INSERT INTO artist_similarity_unmatched ( - seed_artist_id, candidate_mbid, candidate_name, score, source -) VALUES ($1, $2, $3, $4, $5) -ON CONFLICT (seed_artist_id, candidate_mbid, source) DO UPDATE SET - candidate_name = EXCLUDED.candidate_name, - score = EXCLUDED.score, - fetched_at = now(); - -- name: ListSimilarArtistsForArtist :many -- In-library artists similar to a seed artist, ranked by best similarity -- score across sources (deduped per candidate). cover_album_id + album_count diff --git a/internal/db/queries/songs.sql b/internal/db/queries/songs.sql index 5095c918..103f0f9e 100644 --- a/internal/db/queries/songs.sql +++ b/internal/db/queries/songs.sql @@ -1,5 +1,5 @@ -- Song links: copies of one song on different releases share a --- song_key (migration 0076). +-- song_key. -- name: LinkTracksAsSong :one -- Links the tracks into one song, joining any songs they already belong to. diff --git a/internal/db/queries/suggestion_snoozes.sql b/internal/db/queries/suggestion_snoozes.sql deleted file mode 100644 index 1bd47d0e..00000000 --- a/internal/db/queries/suggestion_snoozes.sql +++ /dev/null @@ -1,39 +0,0 @@ --- Time-boxed "not right now" on a Discover artist suggestion. --- --- See 0049_suggestion_snoozes.up.sql for why this is a snooze and not a --- dismissal: it records no verdict on the music, expires on its own, and --- must never reach the taste profile. Nothing in internal/taste may read --- this table. - --- name: SnoozeSuggestion :exec --- Upsert, so re-snoozing an already-snoozed candidate EXTENDS it instead of --- erroring on the PK. The name is refreshed too — a later suggestion may --- carry a corrected spelling from the similarity feed. --- $1=user_id, $2=candidate_mbid, $3=candidate_name, $4=duration in days. -INSERT INTO suggestion_snoozes (user_id, candidate_mbid, candidate_name, snoozed_until) -VALUES ($1, $2, $3, now() + ($4::float8 * INTERVAL '1 day')) -ON CONFLICT (user_id, candidate_mbid) DO UPDATE - SET snoozed_until = EXCLUDED.snoozed_until, - candidate_name = EXCLUDED.candidate_name; - --- name: UnsnoozeSuggestion :execrows --- Row count is returned so the handler can 404 an MBID that was never --- snoozed rather than reporting success for a no-op. -DELETE FROM suggestion_snoozes - WHERE user_id = $1 AND candidate_mbid = $2; - --- name: ListActiveSuggestionSnoozes :many --- Backs the manage / un-snooze surface. Expired rows are filtered HERE --- rather than left to the sweeper: gc runs on an hourly tick, so a row can --- outlive its expiry by up to a tick and must not read as still-snoozed in --- the meantime. -SELECT candidate_mbid, candidate_name, snoozed_until, created_at - FROM suggestion_snoozes - WHERE user_id = $1 AND snoozed_until > now() - ORDER BY snoozed_until, candidate_mbid; - --- name: GcDeleteExpiredSuggestionSnoozes :execrows --- Keeps the table from growing without bound. Every read already filters on --- snoozed_until > now(), so deleting an expired row changes no behaviour — --- this is purely reclamation. -DELETE FROM suggestion_snoozes WHERE snoozed_until < now(); diff --git a/internal/db/queries/system_playlists.sql b/internal/db/queries/system_playlists.sql index f5f76d0f..15c0030b 100644 --- a/internal/db/queries/system_playlists.sql +++ b/internal/db/queries/system_playlists.sql @@ -69,8 +69,8 @@ UPDATE system_playlist_runs SET in_flight = false WHERE in_flight = true; -- tiered pick-kind ladder and stamps the built tracks, so metrics -- can compare mixes seeded from fresh vs stale engagement. -- Score = unskipped-play count + 5 if user has liked the artist. The --- Go-side picker (pickSeedArtistsForDay) shuffles the 12 --- daily-deterministically and takes songsLikeSeedCount (6) so the mix +-- Go-side picker (pickSeedArtistsForDay) shuffles the 24 +-- daily-deterministically and takes songsLikeSeedCount (12) so the mix -- set both rotates day-to-day and fills the dedicated Home row. WITH liked AS ( SELECT gla.artist_id FROM general_likes_artists gla WHERE gla.user_id = $1 @@ -132,7 +132,7 @@ SELECT c.artist_id, FROM chosen c LEFT JOIN liked l ON l.artist_id = c.artist_id ORDER BY score DESC, c.artist_id - LIMIT 12; + LIMIT 24; -- name: PickTopPlayedTracksForUser :many -- For-You candidate seeds, tiered so For-You never silently vanishes: @@ -214,27 +214,27 @@ SELECT COALESCE( LIMIT 1) )::uuid AS id; --- name: PickTopAlbumCoverForArtistByUser :one --- "Songs like X" cover. Most-played album by user; tie-break by most-recent --- release. NULL if the artist has no albums or all covers are NULL. --- Note: albums uses cover_art_path (not cover_path). -SELECT a.cover_art_path - FROM albums a - LEFT JOIN tracks t ON t.album_id = a.id - LEFT JOIN play_events pe - ON pe.track_id = t.id - AND pe.user_id = $1 - AND pe.was_skipped = false - WHERE a.artist_id = $2 - AND a.cover_art_path IS NOT NULL - GROUP BY a.id, a.release_date, a.cover_art_path - ORDER BY COUNT(pe.id) DESC, a.release_date DESC NULLS LAST, a.id - LIMIT 1; +-- name: ListSystemPlaylistsForRebuild :many +-- The user's current mixes, so a rebuild can refill each in place and keep +-- its id. +SELECT id, name, system_variant, seed_artist_id + FROM playlists + WHERE user_id = $1 AND kind = 'system'; --- name: DeleteSystemPlaylistsForUser :exec --- Atomic-replace step. CASCADE on playlist_tracks.playlist_id handles --- the join rows. -DELETE FROM playlists WHERE user_id = $1 AND kind = 'system'; +-- name: RefreshSystemPlaylist :exec +-- A rebuild refilling an existing mix: its name, description and shelf +-- place may move with the day's build. updated_at moves with the rollups. +UPDATE playlists + SET name = $2, description = sqlc.arg(description), shelf_rank = sqlc.arg(shelf_rank) + WHERE id = $1; + +-- name: ClearPlaylistTracks :exec +DELETE FROM playlist_tracks WHERE playlist_id = $1; + +-- name: DeletePlaylistsByIDs :exec +-- Mixes a rebuild no longer makes. CASCADE on playlist_tracks.playlist_id +-- handles the join rows. +DELETE FROM playlists WHERE id = ANY(sqlc.arg(ids)::uuid[]); -- name: ListPlaylistsByUserAndKind :many -- Used in integration tests; production filter applied in Go @@ -253,11 +253,12 @@ SELECT id, user_id, name, description, is_public, kind, system_variant, -- name: CreateSystemPlaylist :one -- Inserts a system-generated playlist. Used by BuildSystemPlaylists. -- For 'for_you' variant, pass seed_artist_id as NULL (zero-value pgtype.UUID --- with Valid=false). +-- with Valid=false). shelf_rank is the mix's place on its Home shelf, 1 +-- first, or 0 for kinds the clients order themselves. INSERT INTO playlists ( user_id, name, description, is_public, - kind, system_variant, seed_artist_id, cover_path -) VALUES ($1, $2, '', false, 'system', $3, $4, $5) + kind, system_variant, seed_artist_id, cover_path, shelf_rank +) VALUES ($1, $2, sqlc.arg(description), false, 'system', $3, $4, $5, sqlc.arg(shelf_rank)) RETURNING *; -- name: GetSystemPlaylistByVariantForUser :one diff --git a/internal/db/queries/taste_profile.sql b/internal/db/queries/taste_profile.sql index d04da13f..16d55014 100644 --- a/internal/db/queries/taste_profile.sql +++ b/internal/db/queries/taste_profile.sql @@ -7,7 +7,9 @@ -- completion ratio (precomputed column when present, else duration_played / -- track duration, clamped to [0,1]); age_days drives the time-decay. Genre -- is split into tags in Go; release_date derives the decade for the era --- facet. Quarantined tracks are excluded. +-- facet. Quarantined tracks are excluded, and so is a play whose completion +-- isn't known: one still open (playing now), or one the sweeper closed +-- without hearing how it ended. Graded as 0 they would read as skips. SELECT t.id AS track_id, t.artist_id, @@ -23,6 +25,7 @@ JOIN tracks t ON t.id = pe.track_id JOIN albums a ON a.id = t.album_id WHERE pe.user_id = $1 AND pe.started_at > now() - ($2::float8 * INTERVAL '1 day') + AND (pe.completion_ratio IS NOT NULL OR pe.duration_played_ms IS NOT NULL) AND NOT EXISTS ( SELECT 1 FROM quarantine q WHERE q.user_id = $1 AND q.track_id = t.id diff --git a/internal/db/queries/tracks.sql b/internal/db/queries/tracks.sql index 6be1133e..645e0ce3 100644 --- a/internal/db/queries/tracks.sql +++ b/internal/db/queries/tracks.sql @@ -5,9 +5,9 @@ INSERT INTO tracks ( title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, - tag_read_version, mbid_source + tag_read_version, mbid_source, artist_credit ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, - CASE WHEN $11::text IS NOT NULL THEN 'tag' END) + CASE WHEN $11::text IS NOT NULL THEN 'tag' END, $14) ON CONFLICT (file_path) DO UPDATE SET title = EXCLUDED.title, album_id = EXCLUDED.album_id, @@ -24,6 +24,7 @@ ON CONFLICT (file_path) DO UPDATE SET mbid_source = CASE WHEN EXCLUDED.mbid IS NOT NULL THEN 'tag' WHEN tracks.mbid_source = 'acoustid' THEN 'acoustid' END, genre = EXCLUDED.genre, + artist_credit = EXCLUDED.artist_credit, -- Stamped on update too, so a tag-repair pass marks rows as done and the -- next scan can short-circuit them again. tag_read_version = EXCLUDED.tag_read_version, @@ -79,9 +80,38 @@ WHERE title ILIKE '%' || $1::text || '%' SELECT 1 FROM quarantine q WHERE q.user_id = $2 AND q.track_id = tracks.id ) -ORDER BY title +ORDER BY title, id LIMIT $3 OFFSET $4; +-- name: SearchPlayableTracks :many +-- Subsonic's song search: tracks whose title matches $1 that the listener +-- $2 can play, so neither a missing file nor one they quarantined. Subsonic +-- has no way to mark a song unplayable, and apps page through the whole +-- library with this, so the filter is here rather than after the LIMIT: +-- a short page reads to an app as the end of the results. +SELECT * FROM tracks +WHERE title ILIKE '%' || sqlc.arg(query)::text || '%' + AND missing_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = tracks.id + ) +ORDER BY title, id +LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset); + +-- name: CountPlayableTracksByAlbums :many +-- How many of each album's tracks the listener $2 can play: present on +-- disk and not quarantined by them. An album with none is absent. +SELECT album_id, count(*)::int AS track_count +FROM tracks +WHERE album_id = ANY(sqlc.arg(album_ids)::uuid[]) + AND missing_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = tracks.id + ) +GROUP BY album_id; + -- name: CountTracksMatching :one -- $1 = title query, $2 = user_id (NULL to skip quarantine filter). SELECT COUNT(*) FROM tracks @@ -128,12 +158,6 @@ WHERE NOT EXISTS ( ORDER BY random() LIMIT $2; --- name: CountTracksByArtist :one --- Used by request-progress reporting to count tracks ingested under a --- matched artist (sum across all the artist's albums) while a request --- is still in flight. -SELECT COUNT(*) FROM tracks WHERE artist_id = $1; - -- name: DeleteTrack :one -- Hard delete with FK cascade. The CASCADE on track_id from -- play_events / general_likes_tracks / quarantine / @@ -188,9 +212,12 @@ SELECT t.id, t.file_path -- -- `missing_since IS NOT NULL` again, this time as a race guard: two files can't -- both adopt the same row, and :execrows reports 0 to whichever loses. +-- A removal's reason goes with the mark: the track has its file again. UPDATE tracks SET file_path = sqlc.arg(file_path), - missing_since = NULL + missing_since = NULL, + removed_reason = NULL, + removed_by = NULL WHERE id = sqlc.arg(id) AND missing_since IS NOT NULL; @@ -216,6 +243,18 @@ UPDATE tracks WHERE id = ANY(sqlc.arg(ids)::uuid[]) AND missing_since IS NULL; +-- name: MarkTracksRemoved :execrows +-- Marks rows whose file an admin, or the duplicate resolver, removed on +-- purpose: missing, like a file the walk did not see, with the queue it was +-- removed from and who removed it (NULL for the resolver). The row keeps its +-- likes, plays and playlist places, and a good copy that lands later is +-- adopted or folded into it. A row already missing keeps the time it went. +UPDATE tracks + SET missing_since = COALESCE(missing_since, now()), + removed_reason = sqlc.arg(reason)::text, + removed_by = sqlc.narg(removed_by)::uuid + WHERE id = ANY(sqlc.arg(ids)::uuid[]); + -- name: ClearTrackMbids :exec -- Forgets the recording MBID of rows whose file was another song's (the -- duplicate resolver's wrong-slot removal). The MBID came from that file, so it @@ -228,7 +267,7 @@ UPDATE tracks -- name: MarkTracksEmptied :exec -- Stamps rows the duplicate resolver emptied, whose song the album holds no --- other copy of, with the time they went missing (migration 0095): missing-pair +-- other copy of, with the time they went missing (emptied_at): missing-pair -- folding then waits for a copy fetched again. UPDATE tracks SET emptied_at = missing_since @@ -240,10 +279,23 @@ UPDATE tracks -- skip check, so a file that reappears unchanged is un-marked even though the -- scanner skips re-reading its tags. UPDATE tracks - SET missing_since = NULL + SET missing_since = NULL, + removed_reason = NULL, + removed_by = NULL WHERE id = ANY(sqlc.arg(ids)::uuid[]) AND missing_since IS NOT NULL; +-- name: LockTracksForForget :many +-- Locks the tracks an admin asked to forget, for the forget's transaction, +-- and returns what it re-checks: every one must still exist and still be +-- missing. A track whose file came back since the page was read is playing +-- again and is not forgotten. +SELECT id, album_id, title, file_path, missing_since + FROM tracks + WHERE id = ANY(sqlc.arg(ids)::uuid[]) + ORDER BY id + FOR UPDATE; + -- name: ListMissingTracks :many -- The admin review surface for files the scan could not find. -- @@ -267,12 +319,21 @@ SELECT t.id, albums.title AS album_title, artists.id AS artist_id, artists.name AS artist_name, + t.disc_number, + t.track_number, + t.mbid, + albums.release_group_mbid, + -- Why the track waits: the Collection queue its file was removed from, + -- and who removed it. NULL reason means the scan found the file gone. + t.removed_reason, + remover.username AS removed_by_name, -- Cast is load-bearing: without it sqlc infers the correlated -- subquery as interface{} and the Go layer loses the timestamp type. (SELECT MAX(pe.started_at) FROM play_events pe WHERE pe.track_id = t.id)::timestamptz AS last_played_at FROM tracks t JOIN albums ON albums.id = t.album_id JOIN artists ON artists.id = t.artist_id + LEFT JOIN users remover ON remover.id = t.removed_by WHERE t.missing_since IS NOT NULL ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title LIMIT sqlc.arg(page_limit) OFFSET sqlc.arg(page_offset); @@ -305,18 +366,10 @@ SELECT t.id, artists.id AS artist_id, artists.name AS artist_name, t.source_verdict, - t.source_verdict_at, - -- The album's place on the wanted list: wanted for a clean copy, and - -- when that was last searched for. - COALESCE(w.upgrade, '')::text AS want_upgrade, - w.searched_at AS searched_at + t.source_verdict_at FROM tracks t JOIN albums ON albums.id = t.album_id JOIN artists ON artists.id = t.artist_id - LEFT JOIN LATERAL ( - SELECT x.upgrade, x.searched_at FROM wants x - WHERE x.album_id = albums.id AND x.fulfilled_at IS NOT NULL LIMIT 1 - ) w ON true WHERE t.missing_since IS NULL AND regexp_replace(t.file_path, '^.*/', '') ~* sqlc.arg(pattern)::text ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title @@ -364,3 +417,53 @@ SELECT ar.name AS artist_name, t.title WHERE t.id = ANY(sqlc.arg(ids)::uuid[]) AND t.missing_since IS NOT NULL ORDER BY ar.name, t.title; + +-- name: ListTopTracksForArtistName :many +-- An artist's top songs for the Subsonic getTopSongs, which names the artist +-- rather than giving an id; the name matches regardless of case. "Top" is +-- this server's own listening: the songs played through most often (skips +-- not counted) by everyone on it, then the most liked. Songs nobody has +-- played or liked follow in album order, so an artist with no history still +-- has songs to play. Missing files and the listener's quarantined songs are +-- left out. +SELECT sqlc.embed(t) +FROM tracks t +JOIN artists ar ON ar.id = t.artist_id +JOIN albums al ON al.id = t.album_id +LEFT JOIN LATERAL ( + SELECT count(*) AS plays FROM play_events pe + WHERE pe.track_id = t.id AND pe.was_skipped = false +) p ON true +LEFT JOIN LATERAL ( + SELECT count(*) AS likes FROM general_likes gl WHERE gl.track_id = t.id +) l ON true +WHERE lower(ar.name) = lower(sqlc.arg(artist_name)::text) + AND t.missing_since IS NULL + AND NOT EXISTS ( + SELECT 1 FROM quarantine q + WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = t.id + ) +ORDER BY p.plays DESC, l.likes DESC, + al.release_date NULLS LAST, al.sort_title, al.id, + t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.id +LIMIT sqlc.arg(lim); + +-- name: ListTracksByArtistAndTitle :many +-- Songs matching a title, and an artist when one is given, both regardless +-- of case, for the Subsonic getLyrics, which names the song rather than +-- giving an id. The artist matches the filing artist or the song's own +-- credit ("Low Tide Choir feat. Ruby Calloway"). +SELECT sqlc.embed(t) +FROM tracks t +JOIN artists ar ON ar.id = t.artist_id +WHERE lower(t.title) = lower(sqlc.arg(title)::text) + AND (sqlc.arg(artist_name)::text = '' + OR lower(ar.name) = lower(sqlc.arg(artist_name)::text) + OR lower(coalesce(t.artist_credit, '')) = lower(sqlc.arg(artist_name)::text)) + AND t.missing_since IS NULL +ORDER BY t.id +LIMIT 20; + +-- name: CountPlayableTracks :one +-- The songs whose files are present, for the Subsonic getScanStatus count. +SELECT count(*) FROM tracks WHERE missing_since IS NULL; diff --git a/internal/db/queries/users.sql b/internal/db/queries/users.sql index 71e6400a..abddfda3 100644 --- a/internal/db/queries/users.sql +++ b/internal/db/queries/users.sql @@ -36,18 +36,13 @@ SELECT count(*) FROM users; -- name: SetSubsonicPassword :exec -- Stores (or clears with NULL) the per-user Subsonic legacy credential used --- for t/s and p auth on /rest/*. Must be plaintext; see migration 0003. Only +-- for t/s and p auth on /rest/*. Must be plaintext: t/s auth hashes it with a salt. Only -- ever a server-generated value, never the login password. UPDATE users SET subsonic_password = $2 WHERE id = $1; -- name: GetUserByID :one SELECT * FROM users WHERE id = $1; --- name: ListUsernamesByIDs :many --- Names a list's people in one round trip, e.g. who made each request on --- /admin/requests. -SELECT id, username FROM users WHERE id = ANY($1::uuid[]); - -- name: SetListenBrainzToken :exec UPDATE users SET listenbrainz_token = $2, @@ -61,7 +56,7 @@ WHERE id = $1; -- name: ListUsers :many -- Admin user-management list. Sort newest-first. -SELECT id, username, display_name, is_admin, auto_approve_requests, +SELECT id, username, display_name, is_admin, debug_mode_enabled, created_at FROM users ORDER BY created_at DESC; @@ -115,13 +110,6 @@ UPDATE users SET password_hash = $2 WHERE id = $1; --- name: UpdateUserAutoApprove :one --- Toggle the per-user auto_approve_requests flag. -UPDATE users - SET auto_approve_requests = $2 - WHERE id = $1 -RETURNING *; - -- name: SetDebugMode :one -- Toggle the per-account diagnostics/debug-reporting opt-in. Admin-driven -- from /admin (flip remotely while a bug is live) or self-driven OFF from diff --git a/internal/db/queries/wanted.sql b/internal/db/queries/wanted.sql deleted file mode 100644 index 11b49a98..00000000 --- a/internal/db/queries/wanted.sql +++ /dev/null @@ -1,501 +0,0 @@ --- The wanted list: release-type profiles, follows and wants. - --- name: ListReleaseTypeProfiles :many -SELECT p.*, - (SELECT COUNT(*) FROM follows f WHERE f.profile_id = p.id)::bigint AS follow_count - FROM release_type_profiles p - ORDER BY p.is_default DESC, p.name; - --- name: GetReleaseTypeProfile :one -SELECT * FROM release_type_profiles WHERE id = $1; - --- name: GetDefaultReleaseTypeProfile :one -SELECT * FROM release_type_profiles WHERE is_default; - --- name: CreateReleaseTypeProfile :one -INSERT INTO release_type_profiles (name, primary_types, secondary_types) -VALUES ($1, $2, $3) -RETURNING *; - --- name: UpdateReleaseTypeProfile :one -UPDATE release_type_profiles - SET name = $2, - primary_types = $3, - secondary_types = $4, - updated_at = now() - WHERE id = $1 -RETURNING *; - --- name: ClearDefaultReleaseTypeProfile :exec -UPDATE release_type_profiles SET is_default = false, updated_at = now() WHERE is_default; - --- name: SetDefaultReleaseTypeProfile :execrows -UPDATE release_type_profiles SET is_default = true, updated_at = now() WHERE id = $1; - --- name: DeleteReleaseTypeProfile :execrows --- The default stays; one in use is refused by the follows foreign key. -DELETE FROM release_type_profiles WHERE id = $1 AND NOT is_default; - --- name: UpsertFollow :one --- Following an artist already followed changes its profile. want_existing --- only ever turns on here; the worker turns it off once applied, and turning --- it on again re-reads the baseline so the existing releases are judged. -INSERT INTO follows (artist_mbid, artist_name, profile_id, followed_by, want_existing) -VALUES (sqlc.arg(artist_mbid), sqlc.arg(artist_name), sqlc.arg(profile_id), - sqlc.narg(followed_by), sqlc.arg(want_existing)) -ON CONFLICT (artist_mbid) DO UPDATE - SET artist_name = EXCLUDED.artist_name, - profile_id = EXCLUDED.profile_id, - want_existing = follows.want_existing OR EXCLUDED.want_existing, - baseline_at = CASE WHEN EXCLUDED.want_existing THEN NULL ELSE follows.baseline_at END, - updated_at = now() -RETURNING *; - --- name: GetFollow :one -SELECT f.*, p.name AS profile_name - FROM follows f - JOIN release_type_profiles p ON p.id = f.profile_id - WHERE f.artist_mbid = $1; - --- name: DeleteFollow :execrows -DELETE FROM follows WHERE artist_mbid = $1; - --- name: ListFollows :many -SELECT f.artist_mbid, f.artist_name, f.profile_id, f.followed_at, f.baseline_at, f.checked_at, - p.name AS profile_name, - (SELECT a.id FROM artists a WHERE a.mbid = f.artist_mbid) AS artist_id, - (SELECT COUNT(*) FROM wants w - WHERE w.artist_mbid = f.artist_mbid AND w.fulfilled_at IS NULL)::bigint AS open_wants - FROM follows f - JOIN release_type_profiles p ON p.id = f.profile_id - ORDER BY lower(f.artist_name), f.artist_mbid; - --- name: ListFollowsDue :many --- Follows whose discography has not been applied since @before, never-read --- first, so a new follow's baseline is not stuck behind daily re-checks. -SELECT f.* - FROM follows f - WHERE f.baseline_at IS NULL OR f.checked_at IS NULL OR f.checked_at < sqlc.arg(before) - ORDER BY f.baseline_at NULLS FIRST, f.checked_at NULLS FIRST, f.artist_mbid - LIMIT sqlc.arg(max_rows); - --- name: MarkFollowChecked :exec -UPDATE follows - SET checked_at = now(), - baseline_at = COALESCE(baseline_at, now()), - want_existing = false, - updated_at = now() - WHERE artist_mbid = $1; - --- name: ListFollowGroups :many --- An artist's release groups from the catalogue, each with whether the --- follow has judged it before. -SELECT g.mbid, g.title, g.primary_type, g.secondary_types, g.first_release_date, - EXISTS (SELECT 1 FROM follow_seen_groups s - WHERE s.artist_mbid = sqlc.arg(artist_mbid) AND s.release_group_mbid = g.mbid) AS seen - FROM mb_artist_release_groups ag - JOIN mb_release_groups g ON g.mbid = ag.release_group_mbid - WHERE ag.artist_mbid = sqlc.arg(artist_mbid) - ORDER BY g.first_release_date, g.title; - --- name: MarkGroupSeen :exec -INSERT INTO follow_seen_groups (artist_mbid, release_group_mbid) -VALUES ($1, $2) -ON CONFLICT DO NOTHING; - --- name: LibraryHoldsReleaseGroup :one --- Whether the library already has the group: an album tagged with it or --- with one of its releases, or failing that an album of the artist's with --- the same title. Only albums with a track on disk count. -SELECT EXISTS ( - SELECT 1 FROM albums a - WHERE (a.release_group_mbid = sqlc.arg(group_mbid)::text - OR a.mbid = sqlc.arg(group_mbid) - OR a.mbid IN (SELECT r.mbid FROM mb_releases r WHERE r.release_group_mbid = sqlc.arg(group_mbid)) - OR (lower(a.title) = lower(sqlc.arg(title)::text) - AND a.artist_id IN (SELECT ar.id FROM artists ar WHERE ar.mbid = sqlc.arg(artist_mbid)::text))) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL) -); - --- name: WantReleaseGroup :one --- Wants a release group, or returns the want already recorded for it. A --- held want is not reopened here: the library has it. -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, primary_type, - first_release_date, reason, created_by) -VALUES (sqlc.arg(release_group_mbid), sqlc.arg(artist_mbid), sqlc.arg(artist_name), sqlc.arg(title), - sqlc.arg(primary_type), sqlc.arg(first_release_date), sqlc.arg(reason), sqlc.narg(created_by)) -ON CONFLICT (release_group_mbid) DO UPDATE SET updated_at = wants.updated_at -RETURNING *; - --- name: GetWantByReleaseGroup :one -SELECT * FROM wants WHERE release_group_mbid = $1; - --- name: ListOpenWants :many -SELECT * FROM wants - WHERE fulfilled_at IS NULL - ORDER BY wanted_at, id - LIMIT $1; - --- name: WantHoldings :many --- Each library album that may answer a want, with what it has on disk: --- tracks present, whether one arrived since the want, and whether a track --- missing before the want is still missing. -SELECT a.id AS album_id, - COUNT(*) FILTER (WHERE t.missing_since IS NULL)::int AS present, - COALESCE(bool_or(t.missing_since IS NULL AND t.added_at > sqlc.arg(since)::timestamptz), false)::bool AS arrived_since, - COALESCE(bool_or(t.missing_since IS NOT NULL AND t.missing_since < sqlc.arg(since)::timestamptz), false)::bool AS missing_before, - -- Missing tracks no track on disk stands in for, by position or - -- title. A missing row whose song is back at a new path is - -- covered; a lost bonus track is not. A track with no disc number is - -- on disc 1, so a missing track 6 with no disc beside a present 1/6 - -- does not keep the album wanted. - COUNT(*) FILTER (WHERE t.missing_since IS NOT NULL AND NOT EXISTS ( - SELECT 1 FROM tracks p - WHERE p.album_id = a.id AND p.missing_since IS NULL - AND ((p.track_number = t.track_number AND COALESCE(p.disc_number, 1) = COALESCE(t.disc_number, 1)) - OR lower(p.title) = lower(t.title))))::int AS uncovered_missing - FROM albums a - JOIN tracks t ON t.album_id = a.id - WHERE a.release_group_mbid = sqlc.arg(group_mbid)::text - OR a.mbid = sqlc.arg(group_mbid) - OR a.id = sqlc.narg(album_id) - OR a.mbid IN (SELECT r.mbid FROM mb_releases r WHERE r.release_group_mbid = sqlc.arg(group_mbid)) - GROUP BY a.id - ORDER BY present DESC, a.id; - --- name: FulfillWant :exec -UPDATE wants - SET fulfilled_at = now(), - album_id = sqlc.arg(album_id), - updated_at = now() - WHERE id = sqlc.arg(id) AND fulfilled_at IS NULL; - --- name: RepointWant :exec --- A want recorded under a release id is moved to its group. -UPDATE wants SET release_group_mbid = $2, updated_at = now() WHERE id = $1; - --- name: DeleteWant :execrows -DELETE FROM wants WHERE id = $1; - --- name: ListWants :many --- The Wanted page: open wants (all but missing ones, or only missing ones), --- the held ones, or all of them; artist_mbid narrows to one artist's page, --- want_ids to given wants. Ordered like the library: artists A–Z by the --- library's sort name when it holds the artist, each artist's albums by --- release date, so the page groups them as they arrive. q narrows to an --- artist or album title; total counts every match, past the page. -SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.reason, - w.album_id, w.wanted_at, w.fulfilled_at, - -- Why a held album is wanted again, and the copy it has. - w.upgrade, w.held_quality, - -- A request names an album before the catalogue has read it: the - -- catalogue's type and date fill in once it has. - COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type, - COALESCE(g.secondary_types, '{}')::text[] AS secondary_types, - COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date, - u.username AS requested_by, - la.id AS library_artist_id, - COUNT(*) OVER () AS total, - -- The search schedule's last look, and the download running. - w.searched_at, w.search_outcome, w.search_considered, w.best_release, w.best_verdict, w.search_error, - -- Its latest download, running or ended, and what the import made of - -- it. - gr.id AS grab_id, gr.name AS grab_name, gr.grabbed_at, gr.origin AS grab_origin, - gr.quality AS grab_quality, gr.ended_at AS grab_ended_at, gr.end_reason AS grab_end_reason, - gr.progress AS grab_progress, gr.import_state AS grab_import_state, - gr.import_reason AS grab_import_reason, gr.end_detail AS grab_end_detail, gr.imported_at AS grab_imported_at, - gr.imported_files AS grab_imported_files - FROM wants w - LEFT JOIN users u ON u.id = w.created_by - LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid - LEFT JOIN LATERAL (SELECT ar.id, ar.sort_name FROM artists ar WHERE ar.mbid = w.artist_mbid LIMIT 1) la ON true - LEFT JOIN grabs gr ON gr.id = (SELECT x.id FROM grabs x WHERE x.want_id = w.id - ORDER BY x.ended_at IS NULL DESC, x.grabbed_at DESC LIMIT 1) - WHERE CASE sqlc.arg(state)::text - WHEN 'all' THEN true - WHEN 'held' THEN w.fulfilled_at IS NOT NULL - WHEN 'upgrade' THEN w.fulfilled_at IS NOT NULL AND w.upgrade <> '' - WHEN 'missing' THEN w.fulfilled_at IS NULL AND w.reason = 'missing' - ELSE w.fulfilled_at IS NULL AND w.reason <> 'missing' - END - AND (sqlc.arg(artist_mbid)::text = '' OR w.artist_mbid = sqlc.arg(artist_mbid)::text) - -- want_ids narrows to given wants: the Missing page's folders. - AND (COALESCE(cardinality(sqlc.arg(want_ids)::uuid[]), 0) = 0 OR w.id = ANY(sqlc.arg(want_ids)::uuid[])) - AND (sqlc.arg(q)::text = '' - OR strpos(lower(w.artist_name), lower(sqlc.arg(q)::text)) > 0 - OR strpos(lower(w.title), lower(sqlc.arg(q)::text)) > 0) - ORDER BY lower(COALESCE(NULLIF(la.sort_name, ''), w.artist_name)), w.artist_mbid, - NULLIF(COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, ''), '') NULLS LAST, - lower(w.title), w.id - LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip); - --- name: ListWantArtists :many --- The Wanted view's main page: every artist on the list, A–Z like --- the library, with how many of their albums are held of how many are on --- the list. q matches the artist's name or any of their albums' titles; --- artist_mbid narrows to one artist, for their page's header. -WITH a AS ( - SELECT w.artist_mbid, - (array_agg(w.artist_name ORDER BY w.wanted_at DESC))[1] AS artist_name, - COUNT(*) FILTER (WHERE w.fulfilled_at IS NOT NULL)::int AS held, - COUNT(*) FILTER (WHERE w.fulfilled_at IS NULL AND w.reason <> 'missing')::int AS wanted, - COUNT(*) FILTER (WHERE w.fulfilled_at IS NULL AND w.reason = 'missing')::int AS missing, - COUNT(*)::int AS albums, - bool_or(sqlc.arg(q)::text <> '' AND strpos(lower(w.title), lower(sqlc.arg(q)::text)) > 0) AS title_match - FROM wants w - WHERE sqlc.arg(artist_mbid)::text = '' OR w.artist_mbid = sqlc.arg(artist_mbid)::text - GROUP BY w.artist_mbid -) -SELECT a.artist_mbid, a.artist_name::text AS artist_name, a.held, a.wanted, a.missing, a.albums, - COALESCE(NULLIF(la.sort_name, ''), a.artist_name)::text AS sort_name, - la.id AS library_artist_id, - (f.artist_mbid IS NOT NULL)::bool AS following, - (SELECT COUNT(*) FROM grabs g JOIN wants x ON x.id = g.want_id - WHERE x.artist_mbid = a.artist_mbid AND g.ended_at IS NULL)::int AS downloading, - COUNT(*) OVER () AS total - FROM a - LEFT JOIN LATERAL (SELECT ar.id, ar.sort_name FROM artists ar WHERE ar.mbid = a.artist_mbid LIMIT 1) la ON true - LEFT JOIN follows f ON f.artist_mbid = a.artist_mbid - WHERE sqlc.arg(q)::text = '' - OR strpos(lower(a.artist_name), lower(sqlc.arg(q)::text)) > 0 - OR a.title_match - ORDER BY lower(COALESCE(NULLIF(la.sort_name, ''), a.artist_name)), a.artist_mbid - LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip); - --- name: GetWantAlbum :one --- What the Wanted view's track list needs of a want. -SELECT id, release_group_mbid, album_id FROM wants WHERE id = $1; - --- name: ListLibraryAlbumTracks :many --- A held or missing album's own tracks, for the Wanted view's track list; --- missing says its file is gone. -SELECT title, disc_number, track_number, duration_ms, (missing_since IS NOT NULL)::bool AS missing - FROM tracks - WHERE album_id = $1 - ORDER BY disc_number NULLS FIRST, track_number NULLS LAST, title; - --- name: CountWants :one -SELECT COUNT(*) FILTER (WHERE fulfilled_at IS NULL AND reason <> 'missing')::bigint AS wanted, - COUNT(*) FILTER (WHERE fulfilled_at IS NULL AND reason = 'missing')::bigint AS missing, - COUNT(*) FILTER (WHERE fulfilled_at IS NOT NULL)::bigint AS held, - -- Held albums wanted for a better copy. - COUNT(*) FILTER (WHERE fulfilled_at IS NOT NULL AND upgrade <> '')::bigint AS upgrades, - COUNT(DISTINCT artist_mbid)::bigint AS artists, - -- Library albums waiting to be matched by hand. - (SELECT COUNT(*) FROM library_album_matches m - WHERE m.outcome = 'unmatched' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id))::bigint AS unmatched, - (SELECT COUNT(*) FROM follows)::bigint AS following, - -- The Wanted view's other tabs: downloads running, those - -- waiting on a person, and releases set aside. - (SELECT COUNT(*) FROM grabs WHERE ended_at IS NULL)::bigint AS activity, - (SELECT COUNT(*) FROM grabs - WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::bigint AS attention, - (SELECT COUNT(*) FROM release_blocks b - WHERE b.expires_at IS NULL OR b.expires_at > now())::bigint AS blocked - FROM wants; - --- The one-time listing of the library. --------------------------- - --- name: GetLibraryListing :one -SELECT library_listing_started_at, library_listed_at, library_unlisted - FROM acquisition_settings WHERE id = true; - --- name: StartLibraryListing :one --- Marks the listing begun, once; its time is the cutoff for which albums --- count as the library's. -UPDATE acquisition_settings - SET library_listing_started_at = COALESCE(library_listing_started_at, now()) - WHERE id = true -RETURNING library_listing_started_at; - --- name: ListLibraryAlbums :execrows --- Puts library albums on the list as held: each release group once, by the --- album holding the most tracks. Only albums the library had at the cutoff, --- and with album_id given only that album. A group already on the list is --- left as it is. An album with tracks already missing is held from just --- before the first loss, so re-acquisition still fetches it back. -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id, wanted_at, fulfilled_at) -SELECT DISTINCT ON (a.release_group_mbid) - a.release_group_mbid, ar.mbid, ar.name, a.title, 'library', a.id, now(), - COALESCE((SELECT MIN(t.missing_since) FROM tracks t WHERE t.album_id = a.id) - interval '1 second', now()) - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - WHERE a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> '' - AND ar.mbid IS NOT NULL AND ar.mbid <> '' - AND a.created_at <= sqlc.arg(cutoff)::timestamptz - AND (sqlc.narg(album_id)::uuid IS NULL OR a.id = sqlc.narg(album_id)::uuid) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) - ORDER BY a.release_group_mbid, - (SELECT COUNT(*) FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL) DESC, a.id -ON CONFLICT (release_group_mbid) DO NOTHING; - --- name: RecordListedAlbums :exec --- The albums ListLibraryAlbums takes are decided as listed by their tags, --- so the matching that follows leaves them alone. -INSERT INTO library_album_matches (album_id, outcome, method, release_group_mbid) -SELECT a.id, 'listed', 'tags', a.release_group_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - WHERE a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> '' - AND ar.mbid IS NOT NULL AND ar.mbid <> '' - AND a.created_at <= sqlc.arg(cutoff)::timestamptz - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) -ON CONFLICT (album_id) DO NOTHING; - --- name: ListAlbumsToMatch :many --- Library albums the listing has not decided, or that an older matcher --- refused, or whose tracks changed since they were refused: each is matched --- to MusicBrainz. A library album is one from before the cutoff, or --- one whose tracks were: a re-tag files a track under a new album row but --- keeps the track. An album row with no tracks is not an album in --- the library; one a person left off stays off. -SELECT a.id, a.title, a.mbid, a.release_group_mbid, ar.name AS artist_name, ar.mbid AS artist_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - WHERE (a.created_at <= sqlc.arg(cutoff)::timestamptz - OR EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.added_at <= sqlc.arg(cutoff)::timestamptz)) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) - AND NOT EXISTS (SELECT 1 FROM library_album_matches m - WHERE m.album_id = a.id - AND (m.outcome IN ('listed', 'dismissed') - OR (m.matcher >= sqlc.arg(matcher)::int - AND NOT EXISTS (SELECT 1 FROM tracks t - WHERE t.album_id = a.id AND t.updated_at > m.decided_at)))) - ORDER BY a.created_at, a.id - LIMIT sqlc.arg(max_rows); - --- name: CountAlbumsToMatch :one --- Whether a finished listing has albums to go back to: those --- ListAlbumsToMatch would hand it. -SELECT COUNT(*) - FROM albums a - WHERE (a.created_at <= sqlc.arg(cutoff)::timestamptz - OR EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.added_at <= sqlc.arg(cutoff)::timestamptz)) - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id) - AND NOT EXISTS (SELECT 1 FROM library_album_matches m - WHERE m.album_id = a.id - AND (m.outcome IN ('listed', 'dismissed') - OR (m.matcher >= sqlc.arg(matcher)::int - AND NOT EXISTS (SELECT 1 FROM tracks t - WHERE t.album_id = a.id AND t.updated_at > m.decided_at)))); - --- name: ListAlbumTracksToMatch :many --- What an album's tracks say about themselves, to check a match against. -SELECT title, disc_number, track_number, duration_ms, mbid - FROM tracks - WHERE album_id = $1 - ORDER BY disc_number NULLS FIRST, track_number NULLS LAST, title; - --- name: SetAlbumReleaseGroup :exec --- Names a matched album's release group, filling only what nothing named. -UPDATE albums SET release_group_mbid = sqlc.arg(release_group_mbid), updated_at = now() - WHERE id = sqlc.arg(id) AND (release_group_mbid IS NULL OR release_group_mbid = ''); - --- name: InsertLibraryWant :execrows --- Puts one matched album on the list as held, from just before its first --- lost track if it has one. A group already on the list is left as it is. -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date, - reason, album_id, wanted_at, fulfilled_at) -VALUES (sqlc.arg(release_group_mbid), sqlc.arg(artist_mbid), sqlc.arg(artist_name), sqlc.arg(title), - sqlc.arg(primary_type), sqlc.arg(first_release_date), 'library', sqlc.arg(album_id)::uuid, now(), - COALESCE((SELECT MIN(t.missing_since) FROM tracks t WHERE t.album_id = sqlc.arg(album_id)::uuid) - - interval '1 second', now())) -ON CONFLICT (release_group_mbid) DO NOTHING; - --- name: RecordAlbumMatch :exec -INSERT INTO library_album_matches (album_id, outcome, method, release_group_mbid, detail, matcher) -VALUES (sqlc.arg(album_id), sqlc.arg(outcome), sqlc.arg(method), sqlc.arg(release_group_mbid), sqlc.arg(detail), - sqlc.arg(matcher)) -ON CONFLICT (album_id) DO UPDATE - SET outcome = EXCLUDED.outcome, method = EXCLUDED.method, release_group_mbid = EXCLUDED.release_group_mbid, - detail = EXCLUDED.detail, matcher = EXCLUDED.matcher, decided_at = now(); - --- name: FinishLibraryListing :one --- The listing is done, or done again after a newer matcher's retries: --- count the albums no match was found for. The first finish is kept. -UPDATE acquisition_settings - SET library_listed_at = COALESCE(library_listed_at, now()), - library_unlisted = (SELECT COUNT(*) FROM library_album_matches m - WHERE m.outcome = 'unmatched' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id)) - WHERE id = true -RETURNING library_listed_at, library_unlisted; - --- name: ListUnmatchedLibraryAlbums :many --- The Collection's Unmatched section: the albums the listing could --- not match, and below them the ones a person left off. An album whose --- tracks have all moved to another row is gone, not unmatched. -SELECT m.album_id, a.title, ar.name AS artist_name, m.detail, m.outcome, m.decided_at, - (SELECT COUNT(*) FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL)::int AS tracks - FROM library_album_matches m - JOIN albums a ON a.id = m.album_id - JOIN artists ar ON ar.id = a.artist_id - WHERE m.outcome IN ('unmatched', 'dismissed') - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id) - ORDER BY m.outcome DESC, lower(ar.name), lower(a.title) - LIMIT sqlc.arg(max_rows); - --- name: RecountLibraryUnlisted :exec --- After a person matches or leaves off an album, the count the catalogue --- shows. -UPDATE acquisition_settings - SET library_unlisted = (SELECT COUNT(*) FROM library_album_matches m - WHERE m.outcome = 'unmatched' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id)) - WHERE id = true; - --- name: GetAlbumToMatch :one --- One album a person is matching by hand, as the matcher reads albums. -SELECT a.id, a.title, a.mbid, a.release_group_mbid, ar.name AS artist_name, ar.mbid AS artist_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - JOIN library_album_matches m ON m.album_id = a.id AND m.outcome IN ('unmatched', 'dismissed') - WHERE a.id = $1; - --- name: SetAlbumMatchOutcome :execrows --- Leave an unmatched album off the list, or put a left-off one back. -UPDATE library_album_matches SET outcome = sqlc.arg(outcome), decided_at = now() - WHERE album_id = sqlc.arg(album_id) AND outcome = sqlc.arg(was); - - --- Upgrades. ------------------------------------------------------- - --- name: ListHeldWantFormats :many --- What each held album's copy is made of, for judging whether it is worth --- upgrading: its present tracks grouped by format, with their bytes and --- length summed, and how many are held back as video rips. A held want whose --- album has no track with a length yet has no rows. -SELECT w.id AS want_id, w.upgrade, w.held_tier, w.held_quality, - lower(t.file_format)::text AS file_format, - SUM(t.file_size)::bigint AS bytes, - SUM(t.duration_ms)::bigint AS duration_ms, - COUNT(*)::int AS tracks, - COUNT(*) FILTER (WHERE t.source_verdict = 'suspect')::int AS rips - FROM wants w - JOIN tracks t ON t.album_id = w.album_id - WHERE w.fulfilled_at IS NOT NULL - AND t.missing_since IS NULL AND t.duration_ms > 0 - GROUP BY w.id, lower(t.file_format) - ORDER BY w.id; - --- name: SetWantUpgrades :exec --- Writes the upgrade check's verdicts, one row per want. -UPDATE wants w - SET upgrade = v.upgrade, - held_tier = v.held_tier, - held_quality = v.held_quality, - upgrade_checked_at = now(), - updated_at = CASE WHEN w.upgrade <> v.upgrade THEN now() ELSE w.updated_at END - FROM (SELECT unnest(sqlc.arg(ids)::uuid[]) AS id, - unnest(sqlc.arg(upgrades)::text[]) AS upgrade, - unnest(sqlc.arg(held_tiers)::text[]) AS held_tier, - unnest(sqlc.arg(held_qualities)::text[]) AS held_quality) v - WHERE w.id = v.id; - --- name: ClearHeldUpgrades :execrows --- A held want whose album has no track left to judge is not wanted again. -UPDATE wants SET upgrade = '', held_tier = '', held_quality = '', upgrade_checked_at = now() - WHERE fulfilled_at IS NOT NULL AND upgrade <> '' - AND NOT EXISTS (SELECT 1 FROM tracks t - WHERE t.album_id = wants.album_id AND t.missing_since IS NULL AND t.duration_ms > 0); diff --git a/internal/db/wait.go b/internal/db/wait.go new file mode 100644 index 00000000..6f663100 --- /dev/null +++ b/internal/db/wait.go @@ -0,0 +1,70 @@ +package db + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/jackc/pgx/v5" +) + +// A database started alongside Minstrel (one compose file, one stack) is +// often still initialising when Minstrel starts, and a first start of the +// official Postgres image takes several seconds before it accepts +// connections. Minstrel waits for it rather than exiting, so no healthcheck +// or restart policy is needed to bring the pair up. Two minutes covers a slow +// first initialisation; past that the address or credentials are wrong and +// the last error says which. +const ( + readyEvery = 2 * time.Second + readyLimit = 2 * time.Minute + readyAttemptTimeout = 5 * time.Second +) + +// WaitReady blocks until the database at dsn accepts a connection, retrying +// while it is unreachable and logging each failed attempt. It returns the last +// connection error once readyLimit has passed, or ctx's error if ctx ends +// first. +func WaitReady(ctx context.Context, dsn string, logger *slog.Logger) error { + if dsn == "" { + return errors.New("db: database URL is empty") + } + return waitFor(ctx, logger, readyEvery, readyLimit, func(ctx context.Context) error { + actx, cancel := context.WithTimeout(ctx, readyAttemptTimeout) + defer cancel() + conn, err := pgx.Connect(actx, dsn) + if err != nil { + return err + } + defer func() { _ = conn.Close(context.WithoutCancel(ctx)) }() + return conn.Ping(actx) + }) +} + +// waitFor calls try until it succeeds, every `every`, for at most `limit`. +func waitFor(ctx context.Context, logger *slog.Logger, every, limit time.Duration, try func(context.Context) error) error { + deadline := time.Now().Add(limit) + for attempt := 1; ; attempt++ { + err := try(ctx) + if err == nil { + if attempt > 1 { + logger.Info("database is ready", "attempts", attempt) + } + return nil + } + if ctx.Err() != nil { + return ctx.Err() + } + if !time.Now().Add(every).Before(deadline) { + return fmt.Errorf("db: not reachable after %s: %w", limit, err) + } + logger.Info("waiting for the database", "attempt", attempt, "err", err) + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(every): + } + } +} diff --git a/internal/db/wait_test.go b/internal/db/wait_test.go new file mode 100644 index 00000000..1fa3bd53 --- /dev/null +++ b/internal/db/wait_test.go @@ -0,0 +1,60 @@ +package db + +import ( + "context" + "errors" + "io" + "log/slog" + "testing" + "time" +) + +var quietLogger = slog.New(slog.NewTextHandler(io.Discard, nil)) + +func TestWaitFor_RetriesUntilTheDatabaseAnswers(t *testing.T) { + calls := 0 + err := waitFor(context.Background(), quietLogger, time.Millisecond, time.Second, func(context.Context) error { + calls++ + if calls < 3 { + return errors.New("connection refused") + } + return nil + }) + if err != nil { + t.Fatalf("waitFor = %v, want nil once the third attempt connects", err) + } + if calls != 3 { + t.Errorf("attempts = %d, want 3 (two refusals, then success)", calls) + } +} + +func TestWaitFor_GivesUpWithTheLastError(t *testing.T) { + refused := errors.New("password authentication failed") + err := waitFor(context.Background(), quietLogger, time.Millisecond, 20*time.Millisecond, func(context.Context) error { + return refused + }) + if !errors.Is(err, refused) { + t.Fatalf("waitFor = %v, want it to carry the last connection error", err) + } +} + +func TestWaitFor_StopsWhenShutdownBegins(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + start := time.Now() + err := waitFor(ctx, quietLogger, time.Hour, time.Hour, func(context.Context) error { + return errors.New("connection refused") + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("waitFor = %v, want context.Canceled", err) + } + if time.Since(start) > time.Second { + t.Errorf("waitFor took %s after cancel, want an immediate return", time.Since(start)) + } +} + +func TestWaitReady_EmptyURLIsAnErrorNotAWait(t *testing.T) { + if err := WaitReady(context.Background(), "", quietLogger); err == nil { + t.Fatal("WaitReady(\"\") = nil, want an error") + } +} diff --git a/internal/dbtest/pool.go b/internal/dbtest/pool.go new file mode 100644 index 00000000..097db417 --- /dev/null +++ b/internal/dbtest/pool.go @@ -0,0 +1,60 @@ +package dbtest + +import ( + "context" + "io" + "log/slog" + "os" + "sync" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/db" +) + +// EnvDatabaseURL names the variable holding the Postgres DSN integration +// tests run against. Without it, every test that asks for a pool skips. +const EnvDatabaseURL = "MINSTREL_TEST_DATABASE_URL" + +var ( + migrateOnce sync.Once + errMigrate error +) + +// Open returns a pool on the test database with the schema migrated to the +// latest version, closed when t ends. It skips t under -short or when +// MINSTREL_TEST_DATABASE_URL is unset. It does not clear any data: use Pool +// for that, unless the test manages its own rows. +func Open(t *testing.T) *pgxpool.Pool { + t.Helper() + if testing.Short() { + t.Skip("skipping integration test in -short mode") + } + dsn := os.Getenv(EnvDatabaseURL) + if dsn == "" { + t.Skip(EnvDatabaseURL + " not set") + } + // Migrating is idempotent but not free; once per test binary is enough. + migrateOnce.Do(func() { + errMigrate = db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))) + }) + if errMigrate != nil { + t.Fatalf("migrate: %v", errMigrate) + } + pool, err := pgxpool.New(context.Background(), dsn) + if err != nil { + t.Fatalf("connect to test database: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// Pool is Open followed by ResetDB: a migrated pool with every data table +// empty and only non-test users left. +func Pool(t *testing.T) *pgxpool.Pool { + t.Helper() + pool := Open(t) + ResetDB(t, pool) + return pool +} diff --git a/internal/dbtest/reset.go b/internal/dbtest/reset.go index de71db8d..92a16a6b 100644 --- a/internal/dbtest/reset.go +++ b/internal/dbtest/reset.go @@ -11,11 +11,6 @@ // 2. Always create test user rows with a username that begins with // TestUserPrefix; otherwise those rows survive across runs and // leak into other tests. -// -// One test legitimately needs to wipe the entire users table: -// internal/auth/bootstrap_test.go, which exercises first-time admin -// bootstrap. That file does its own TRUNCATE and does not use this -// helper. package dbtest import ( @@ -39,7 +34,6 @@ const TestUserPrefix = "test-" var dataTables = []string{ "artist_similarity", "track_similarity", - "artist_similarity_unmatched", "listenbrainz_similar_recordings", "track_similarity_fetches", "artist_similarity_fetches", @@ -59,21 +53,20 @@ var dataTables = []string{ // does NOT reach it for a leftover row whose user survived. Truncate // explicitly or a stale snooze silently hides a candidate from the // next test's suggestion assertions. - "suggestion_snoozes", // Same reasoning: keyed by candidate MBID with no FK anywhere, // so nothing cascades to them. A leftover tag row would make a // candidate look enriched to the next test, and a leftover state row // would make it look already-settled and thus ineligible. - "candidate_artist_tags", - "candidate_artist_tag_state", + "playlist_append_requests", "playlist_tracks", "playlists", + "play_queues", "library_changes", // reset so each test's sync cursor starts clean // SettingsService.reconcile() idempotently re-UpsertProviderSettings // for every registered provider at boot, so truncating this is the // correct per-test reset (clears test-modified enabled/api_key rows). // cover_art_sources_meta is NOT truncated — boot only READS it - // (never recreates the singleton, seeded once by 0018); ResetDB + // (never recreates the singleton, seeded once by the schema); ResetDB // resets its counter via UPDATE below instead. "cover_art_provider_settings", // Same reasoning for the tag-enrichment settings: truncate the @@ -87,7 +80,6 @@ var dataTables = []string{ // Same reasoning as taste_tuning above: recsettings.New re-seeds // shipped defaults on every construction, so truncating gives each test // pristine Discover knobs rather than whatever a previous test tuned. - "discover_tuning", "recommendation_tuning_audit", "duplicate_group_members", "duplicate_groups", @@ -101,21 +93,9 @@ var dataTables = []string{ "user_notifications", "user_notification_prefs", "user_notification_email_state", - "acquisition_services", "mb_release_tracks", "mb_releases", - "mb_artist_release_groups", "mb_release_groups", - "mb_artists", - "requests", - "download_interventions", - "library_album_matches", - "release_blocks", - "grabs", - "want_candidates", - "wants", - "follow_seen_groups", - "follows", "tracks", "albums", "artists", @@ -173,28 +153,27 @@ func ResetDB(t *testing.T, pool *pgxpool.Pool) { ); err != nil { t.Fatalf("dbtest.ResetDB reset loudness settings: %v", err) } - // Release-type profiles: migration 0081 seeds "Standard" as - // the default. Tests add and edit profiles, so put back exactly the - // seeded row rather than truncating it away. + // The outside-lookup switches, back to on. if _, err := pool.Exec(ctx, ` - DELETE FROM release_type_profiles WHERE name <> 'Standard'; - UPDATE release_type_profiles - SET primary_types = ARRAY['Album', 'EP', 'Single'], secondary_types = '{}', is_default = true - WHERE name = 'Standard'`, + UPDATE lookup_settings + SET listenbrainz_similarity = DEFAULT, musicbrainz_track_lists = DEFAULT, updated_at = DEFAULT`, ); err != nil { - t.Fatalf("dbtest.ResetDB reset release-type profiles: %v", err) + t.Fatalf("dbtest.ResetDB reset lookup settings: %v", err) } - // Search and grab settings, a singleton reset the same way. - // The library listing reads as done, so a test's albums are not - // put on the wanted list behind its back; its own tests clear it. + // The change log's trimmed mark, a singleton: nothing has been trimmed. + if _, err := pool.Exec(ctx, "UPDATE library_changes_trimmed SET through = 0"); err != nil { + t.Fatalf("dbtest.ResetDB reset library_changes_trimmed: %v", err) + } + // The server's own backup: no runs, and settings back to off. if _, err := pool.Exec(ctx, ` - UPDATE acquisition_settings - SET auto_grab = DEFAULT, search_interval_hours = DEFAULT, allowed_qualities = DEFAULT, import_root = DEFAULT, - seed_ratio = DEFAULT, seed_days = DEFAULT, stall_hours = DEFAULT, upgrade_until = DEFAULT, - library_listing_started_at = now(), library_listed_at = now(), library_unlisted = 0, - last_pass_at = NULL, last_pass = DEFAULT, updated_at = DEFAULT`, + DELETE FROM backup_runs; + DELETE FROM backup_music_files; + UPDATE backup_settings + SET enabled = DEFAULT, destination = DEFAULT, folder = DEFAULT, endpoint = DEFAULT, + bucket = DEFAULT, access_key = DEFAULT, secret_key = DEFAULT, run_hour = DEFAULT, + upload_limit_kib = DEFAULT, include_music = DEFAULT, updated_at = DEFAULT`, ); err != nil { - t.Fatalf("dbtest.ResetDB reset acquisition settings: %v", err) + t.Fatalf("dbtest.ResetDB reset backup settings: %v", err) } // Notification email settings, reset the same way. if _, err := pool.Exec(ctx, ` diff --git a/internal/dbtest/secret.go b/internal/dbtest/secret.go new file mode 100644 index 00000000..4d505c60 --- /dev/null +++ b/internal/dbtest/secret.go @@ -0,0 +1,10 @@ +package dbtest + +import "github.com/Fabled-Sword/minstrel/internal/secret" + +// Integration tests run with a master key installed, as the server runs +// after startup, so code that seals or opens a stored credential behaves as +// it does in production. +func init() { + secret.Install([]byte("minstrel integration tests: not a deployment key")) +} diff --git a/internal/downloader/downloader_test.go b/internal/downloader/downloader_test.go deleted file mode 100644 index 5af62b57..00000000 --- a/internal/downloader/downloader_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package downloader - -import ( - "context" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "sync/atomic" - "testing" -) - -func TestPathMap(t *testing.T) { - m := PathMap{Local: "/downloads", Remote: "/data/torrents/"} - for in, want := range map[string]string{ - "/downloads": "/data/torrents", - "/downloads/abc/x.mp3": "/data/torrents/abc/x.mp3", - "/downloads2/abc": "/downloads2/abc", - "/music/a": "/music/a", - "": "", - } { - if got := m.ToRemote(in); got != want { - t.Errorf("ToRemote(%q) = %q, want %q", in, got, want) - } - } - if got := m.ToLocal("/data/torrents/abc"); got != "/downloads/abc" { - t.Errorf("ToLocal = %q", got) - } - if (PathMap{Local: "/downloads", Remote: "/downloads/"}).Active() { - t.Error("the same folder under one name is not a mapping") - } -} - -// fakeQbit is a qBittorrent WebUI that wants a login, and that expires the -// session once to make the client log in again. -func fakeQbit(t *testing.T, expireOnce bool) (*httptest.Server, *atomic.Int32) { - t.Helper() - var logins atomic.Int32 - var expired atomic.Bool - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Referer") == "" { - w.WriteHeader(http.StatusForbidden) - return - } - switch r.URL.Path { - case "/api/v2/auth/login": - _ = r.ParseForm() - if r.Form.Get("password") != "pw" { - _, _ = w.Write([]byte("Fails.")) - return - } - logins.Add(1) - http.SetCookie(w, &http.Cookie{Name: "SID", Value: "s", Path: "/"}) - _, _ = w.Write([]byte("Ok.")) - case "/api/v2/torrents/info": - if _, err := r.Cookie("SID"); err != nil { - w.WriteHeader(http.StatusForbidden) - return - } - if expireOnce && !expired.Swap(true) { - w.WriteHeader(http.StatusForbidden) - return - } - if r.URL.Query().Get("category") != "minstrel" { - t.Errorf("category = %q", r.URL.Query().Get("category")) - } - _, _ = w.Write([]byte(`[{"hash": "ABC", "name": "x", "save_path": "/data/torrents/abc", "progress": 1}]`)) - case "/api/v2/torrents/add": - body, _ := io.ReadAll(r.Body) - if !strings.Contains(string(body), "/data/torrents/new") { - t.Errorf("add body has no translated save path: %s", body) - } - _, _ = w.Write([]byte("Ok.")) - default: - w.WriteHeader(http.StatusNotFound) - } - })) - t.Cleanup(srv.Close) - return srv, &logins -} - -func TestQBittorrent_LogsInAndLogsInAgainWhenTheSessionExpires(t *testing.T) { - srv, logins := fakeQbit(t, true) - d := Mapped(&Client{Config: Config{BaseURL: srv.URL, Username: "u", Password: "pw", Category: "minstrel"}}, - PathMap{Local: "/downloads", Remote: "/data/torrents"}) - ts, err := d.Torrents(context.Background()) - if err != nil { - t.Fatalf("torrents: %v", err) - } - if logins.Load() != 2 { - t.Errorf("logins = %d, want 2 (the second after the 403)", logins.Load()) - } - if len(ts) != 1 || ts[0].Hash != "abc" || ts[0].SavePath != "/downloads/abc" || !ts[0].Done() { - t.Errorf("torrents = %+v, want one, hash lowercased, path in Minstrel's terms", ts) - } - if err := d.AddTorrent(context.Background(), Add{Magnet: "magnet:?xt=urn:btih:abc", SavePath: "/downloads/new"}); err != nil { - t.Errorf("add: %v", err) - } -} - -func TestQBittorrent_AWrongPasswordIsAuth(t *testing.T) { - srv, _ := fakeQbit(t, false) - c := &Client{Config: Config{BaseURL: srv.URL, Password: "nope"}} - if _, err := c.Torrents(context.Background()); !errors.Is(err, ErrAuth) { - t.Fatalf("err = %v, want ErrAuth", err) - } -} - -func TestExchange_MapsDownloadsAndRefusesWhileRestoring(t *testing.T) { - var restoring, sentKey atomic.Bool - restoring.Store(true) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "" { - sentKey.Store(true) - } - pending := "0" - if restoring.Load() { - pending = "3" - } - _, _ = io.WriteString(w, `{"enabled": true, "running": false, "held_reason": "disk full", "restore_pending": `+pending+`, "downloads": [ - {"infohash": "ABC", "name": "Album", "save_path": "/dl", "state": "seeding", "progress": 1, "length": 10, "bytes": 10, "category": "minstrel"}, - {"infohash": "DEF", "name": "Other", "save_path": "/dl", "state": "fast", "category": "someone-else"}, - {"infohash": "123", "name": "Broken", "save_path": "/dl", "failed": true, "fail_reason": "tracker gone", "category": "minstrel"} - ]}`) - })) - defer srv.Close() - - c := &Exchange{Config: Config{BaseURL: srv.URL, Category: "minstrel"}} - if _, err := c.Torrents(context.Background()); !errors.Is(err, ErrRestoring) { - t.Fatalf("while restoring: err = %v, want ErrRestoring", err) - } - if sentKey.Load() { - t.Error("an Authorization header was sent with no key set") - } - restoring.Store(false) - ts, err := c.Torrents(context.Background()) - if err != nil { - t.Fatalf("torrents: %v", err) - } - if len(ts) != 2 { - t.Fatalf("torrents = %+v, want the two in Minstrel's category", ts) - } - if ts[0].Hash != "abc" || ts[0].State != "uploading" || ts[0].ContentPath != "/dl/Album" || !strings.Contains(ts[0].EngineDown, "disk full") { - t.Errorf("first = %+v", ts[0]) - } - if !ts[1].Failed() || ts[1].FailReason != "tracker gone" { - t.Errorf("second = %+v, want failed with Exchange's reason", ts[1]) - } -} - -func TestFor_RefusesAnUnknownProtocol(t *testing.T) { - if _, err := For("transmission", Config{}); err == nil { - t.Fatal("want an error for a client Minstrel cannot drive") - } -} diff --git a/internal/downloader/driver.go b/internal/downloader/driver.go deleted file mode 100644 index 2b1d8d99..00000000 --- a/internal/downloader/driver.go +++ /dev/null @@ -1,197 +0,0 @@ -// Package downloader drives the download clients Minstrel hands a grab to: -// qBittorrent's WebUI v2, and FabledExchange's native /api/downloads. -// -// Both answer through one Driver, and Torrent is qBittorrent's shape: the -// Exchange driver maps its own downloads onto it, so the grab, the importer -// and the stall watchdog read one kind of record whichever client holds the -// torrent. -package downloader - -import ( - "context" - "errors" - "fmt" - "time" -) - -// Protocols a download client row may name. -const ( - KindQBittorrent = "qbittorrent" - KindExchange = "exchange" -) - -// ErrUnconfigured is a client with no address. -var ErrUnconfigured = errors.New("download client is not configured") - -// ErrUnreachable is a call that could not be made, or a refusal that is not -// about credentials. -var ErrUnreachable = errors.New("download client unreachable") - -// ErrAuth is credentials the client refused. -var ErrAuth = errors.New("download client refused the credentials") - -// ErrRestoring is an Exchange still bringing its downloads back after a -// restart: its list is incomplete, so nothing may be concluded from it. -var ErrRestoring = errors.New("download client is still restoring its downloads after a restart") - -// ErrDuplicate is a torrent the client already holds. -var ErrDuplicate = errors.New("download client already holds this torrent") - -// ErrUnsupported is a call this client has no equivalent for. -var ErrUnsupported = errors.New("download client cannot do that") - -// UserAgent names Minstrel in the client's logs. -const UserAgent = "Minstrel (self-hosted music server; download client)" - -// DefaultTimeout is what an unset Timeout means: a download client answers -// from its own state. -const DefaultTimeout = 15 * time.Second - -// Config is one download client. -type Config struct { - BaseURL string - // Username and Password are qBittorrent's. Both may be empty for a WebUI - // that bypasses auth for local addresses. - Username string - Password string - // APIKey is Exchange's, sent as a bearer only when set. - APIKey string - // Category files everything Minstrel adds, so its torrents can be told - // from anything else in the client. - Category string - Timeout time.Duration -} - -// Driver is what Minstrel needs from a download client. -type Driver interface { - AddTorrent(ctx context.Context, a Add) error - // Torrents lists this client's torrents in Config.Category, or only the - // given hashes. - Torrents(ctx context.Context, hashes ...string) ([]Torrent, error) - // Connected says whether the client can reach any peer at all. - Connected(ctx context.Context) (bool, error) - Stop(ctx context.Context, hashes ...string) error - Start(ctx context.Context, hashes ...string) error - Reannounce(ctx context.Context, hashes ...string) error - Recheck(ctx context.Context, hashes ...string) error - Delete(ctx context.Context, deleteFiles bool, hashes ...string) error -} - -// FileSkipper sets which files of a torrent are downloaded. -type FileSkipper interface { - SkipFiles(ctx context.Context, hash string, indices []int) error - KeepFiles(ctx context.Context, hash string, indices []int) error -} - -// File is one file inside a torrent. -type File struct { - Index int - Path string - Size int64 -} - -// FileLister lists a torrent's files. -type FileLister interface { - Files(ctx context.Context, hash string) ([]File, error) -} - -// FileState is one file's progress. -type FileState struct { - Path string - Size int64 - Done int64 - Skipped bool -} - -// Unfinished says whether the file is wanted and not yet whole. -func (f FileState) Unfinished() bool { return !f.Skipped && f.Done < f.Size } - -// FileProgress reports per-file progress. -type FileProgress interface { - FileStates(ctx context.Context, hash string) ([]FileState, error) -} - -var ( - _ Driver = (*Client)(nil) - _ Driver = (*Exchange)(nil) - _ FileSkipper = (*Client)(nil) - _ FileSkipper = (*Exchange)(nil) - _ FileSkipper = (*mapped)(nil) - _ FileLister = (*Client)(nil) - _ FileLister = (*Exchange)(nil) - _ FileLister = (*mapped)(nil) - _ FileProgress = (*Client)(nil) - _ FileProgress = (*Exchange)(nil) - _ FileProgress = (*mapped)(nil) -) - -// For builds the driver a protocol names. -func For(protocol string, cfg Config) (Driver, error) { - switch protocol { - case KindQBittorrent: - return &Client{Config: cfg}, nil - case KindExchange: - return &Exchange{Config: cfg}, nil - } - return nil, fmt.Errorf("download client %q is not one Minstrel can drive", protocol) -} - -// Torrent is one torrent in qBittorrent's JSON shape. -type Torrent struct { - Hash string `json:"hash"` - Name string `json:"name"` - Size int64 `json:"size"` - Progress float64 `json:"progress"` - State string `json:"state"` - Category string `json:"category"` - Tags string `json:"tags"` - SavePath string `json:"save_path"` - ContentPath string `json:"content_path"` - AddedOn int64 `json:"added_on"` - NumSeeds int `json:"num_seeds"` - NumLeechs int `json:"num_leechs"` - AmountLeft int64 `json:"amount_left"` - Ratio float64 `json:"ratio"` - DLSpeed int64 `json:"dlspeed"` - ETA int64 `json:"eta"` - // EngineDown is why the client's whole engine is not moving anything, in - // words; empty when it is running. Exchange says so; qBittorrent does not. - EngineDown string `json:"-"` - // FailReason is the client's own reason for a failed torrent. - FailReason string `json:"-"` -} - -// Done says the torrent is whole. -func (t Torrent) Done() bool { return t.Progress >= 1 } - -// Failed says the client gave up on it. -func (t Torrent) Failed() bool { return t.State == "error" || t.State == "missingFiles" } - -// Fetching says it is still fetching metadata. -func (t Torrent) Fetching() bool { return t.State == "metaDL" || t.State == "forcedMetaDL" } - -// Alone says nobody is sharing an unfinished torrent. -func (t Torrent) Alone() bool { return !t.Done() && t.NumSeeds == 0 && t.NumLeechs == 0 } - -// Added is when the client took it. -func (t Torrent) Added() time.Time { - if t.AddedOn <= 0 { - return time.Time{} - } - return time.Unix(t.AddedOn, 0) -} - -// Add is one torrent to hand a client: a magnet or the .torrent bytes. -type Add struct { - Magnet string - Torrent []byte - // SavePath is where it lands, as Minstrel sees it; Mapped translates it. - // Required: a download with no save path lands outside the folder - // Minstrel imports from. - SavePath string - Tags []string - Paused bool - // StopAtMetadata asks qBittorrent to stop once it has the file list, so - // unwanted files can be skipped before any data moves. - StopAtMetadata bool -} diff --git a/internal/downloader/exchange.go b/internal/downloader/exchange.go deleted file mode 100644 index e1b04fd0..00000000 --- a/internal/downloader/exchange.go +++ /dev/null @@ -1,340 +0,0 @@ -package downloader - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path" - "strings" - "time" -) - -// Exchange drives FabledExchange's native /api/downloads: not its qBittorrent -// facade, so its own states, failure reasons and engine status come through. -type Exchange struct { - Config Config - // HTTP is injectable for tests. Nil takes a plain client. - HTTP *http.Client -} - -type exchangeItem struct { - InfoHash string `json:"infohash"` - Name string `json:"name"` - Bytes int64 `json:"bytes"` - Length int64 `json:"length"` - Progress float64 `json:"progress"` - State string `json:"state"` - Peers int `json:"peers"` - Category string `json:"category"` - Tags []string `json:"tags"` - SavePath string `json:"save_path"` - AddedAt time.Time `json:"added_at"` - Failed bool `json:"failed"` - FailReason string `json:"fail_reason"` - Ratio float64 `json:"ratio"` -} - -type exchangeSnapshot struct { - Enabled bool `json:"enabled"` - Running bool `json:"running"` - HeldReason string `json:"held_reason"` - InboundConns int64 `json:"inbound_conns"` - RestorePending int `json:"restore_pending"` - Downloads []exchangeItem `json:"downloads"` -} - -func (c *Exchange) AddTorrent(ctx context.Context, a Add) error { - if a.Magnet == "" && len(a.Torrent) == 0 { - return fmt.Errorf("add: neither a magnet nor torrent bytes") - } - if a.SavePath == "" { - return fmt.Errorf("add: no save path, which would land the download outside the folder Minstrel imports from") - } - if len(a.Torrent) > 0 { - q := url.Values{"save_path": {a.SavePath}} - if c.Config.Category != "" { - q.Set("category", c.Config.Category) - } - for _, t := range a.Tags { - q.Add("tag", t) - } - if a.Paused { - q.Set("paused", "true") - } - _, err := c.call(ctx, http.MethodPost, "/api/downloads/torrent?"+q.Encode(), "application/x-bittorrent", a.Torrent) - return err - } - body, err := json.Marshal(map[string]any{ - "magnet": a.Magnet, "category": c.Config.Category, "save_path": a.SavePath, - "tags": a.Tags, "paused": a.Paused, - }) - if err != nil { - return fmt.Errorf("add: %w", err) - } - _, err = c.call(ctx, http.MethodPost, "/api/downloads", "application/json", body) - return err -} - -// Torrents maps Exchange's downloads onto qBittorrent's shape. While Exchange -// is still restoring after a restart its list is incomplete, so it answers -// ErrRestoring rather than a list that looks like downloads vanished. -func (c *Exchange) Torrents(ctx context.Context, hashes ...string) ([]Torrent, error) { - snap, err := c.snapshot(ctx) - if err != nil { - return nil, err - } - if snap.RestorePending > 0 { - return nil, fmt.Errorf("%w (%d still to come back)", ErrRestoring, snap.RestorePending) - } - want := map[string]bool{} - for _, h := range hashes { - want[strings.ToLower(strings.TrimSpace(h))] = true - } - down := "" - switch { - case snap.Running: - case !snap.Enabled: - down = "the download engine is switched off in FabledExchange" - case snap.HeldReason != "": - down = "the download engine is held (" + snap.HeldReason + ") and resumes by itself" - default: - down = "the download engine is enabled but not running; FabledExchange is retrying it" - } - out := make([]Torrent, 0, len(snap.Downloads)) - for _, it := range snap.Downloads { - if c.Config.Category != "" && it.Category != c.Config.Category { - continue - } - t := asTorrent(it) - t.EngineDown = down - if len(want) > 0 && !want[t.Hash] { - continue - } - out = append(out, t) - } - return out, nil -} - -func asTorrent(it exchangeItem) Torrent { - content := it.SavePath - if it.Name != "" { - content = path.Join(it.SavePath, it.Name) - } - left := max(it.Length-it.Bytes, 0) - state := exchangeState(it.State, it.Progress) - if it.Failed { - state = "error" - } - var added int64 - if !it.AddedAt.IsZero() { - added = it.AddedAt.Unix() - } - return Torrent{ - Hash: strings.ToLower(it.InfoHash), Name: it.Name, Size: it.Length, - Progress: it.Progress, State: state, Category: it.Category, - Tags: strings.Join(it.Tags, ","), SavePath: it.SavePath, ContentPath: content, - AddedOn: added, NumLeechs: it.Peers, AmountLeft: left, - FailReason: it.FailReason, Ratio: it.Ratio, - } -} - -// exchangeState names Exchange's state in qBittorrent's vocabulary. -func exchangeState(tier string, progress float64) string { - switch tier { - case "fast", "slow": - return "downloading" - case "metadata": - return "metaDL" - case "stalled": - return "stalledDL" - case "queued": - return "queuedDL" - case "seeding": - return "uploading" - case "relocating": - return "moving" - case "paused": - if progress >= 1 { - return "pausedUP" - } - return "pausedDL" - } - return "unknown" -} - -// Connected is a running engine that has had an inbound connection: the -// nearest Exchange comes to qBittorrent's "connected". -func (c *Exchange) Connected(ctx context.Context) (bool, error) { - snap, err := c.snapshot(ctx) - if err != nil { - return false, err - } - return snap.Running && snap.InboundConns > 0, nil -} - -func (c *Exchange) Stop(ctx context.Context, hashes ...string) error { - return c.each(ctx, hashes, func(h string) error { - _, err := c.call(ctx, http.MethodPost, "/api/downloads/"+url.PathEscape(h)+"/pause", "", nil) - return err - }) -} - -func (c *Exchange) Start(ctx context.Context, hashes ...string) error { - return c.each(ctx, hashes, func(h string) error { - _, err := c.call(ctx, http.MethodPost, "/api/downloads/"+url.PathEscape(h)+"/resume", "", nil) - return err - }) -} - -func (c *Exchange) SkipFiles(ctx context.Context, hash string, indices []int) error { - return c.filePriority(ctx, hash, indices, "skip") -} - -func (c *Exchange) KeepFiles(ctx context.Context, hash string, indices []int) error { - return c.filePriority(ctx, hash, indices, "normal") -} - -func (c *Exchange) filePriority(ctx context.Context, hash string, indices []int, priority string) error { - if len(indices) == 0 { - return nil - } - body, err := json.Marshal(map[string]any{"indices": indices, "priority": priority}) - if err != nil { - return err - } - _, err = c.call(ctx, http.MethodPatch, "/api/downloads/"+url.PathEscape(hash)+"/files", "application/json", body) - return err -} - -func (c *Exchange) Files(ctx context.Context, hash string) ([]File, error) { - raw, err := c.files(ctx, hash) - if err != nil { - return nil, err - } - out := make([]File, len(raw)) - for i, f := range raw { - out[i] = File{Index: f.Index, Path: f.Path, Size: f.Length} - } - return out, nil -} - -func (c *Exchange) FileStates(ctx context.Context, hash string) ([]FileState, error) { - raw, err := c.files(ctx, hash) - if err != nil { - return nil, err - } - out := make([]FileState, len(raw)) - for i, f := range raw { - if f.Bytes == nil { - return nil, fmt.Errorf("%w: FabledExchange does not say how much of each file it has", ErrUnsupported) - } - out[i] = FileState{Path: f.Path, Size: f.Length, Done: *f.Bytes, Skipped: f.Priority == "skip"} - } - return out, nil -} - -type exchangeFile struct { - Index int `json:"index"` - Path string `json:"path"` - Length int64 `json:"length"` - Bytes *int64 `json:"bytes"` - Priority string `json:"priority"` -} - -func (c *Exchange) files(ctx context.Context, hash string) ([]exchangeFile, error) { - body, err := c.call(ctx, http.MethodGet, "/api/downloads/"+url.PathEscape(hash), "", nil) - if err != nil { - return nil, err - } - var detail struct { - Files []exchangeFile `json:"files"` - } - if err := json.Unmarshal(body, &detail); err != nil { - return nil, fmt.Errorf("%w: parse download detail: %v", ErrUnreachable, err) - } - return detail.Files, nil -} - -func (c *Exchange) Reannounce(context.Context, ...string) error { - return fmt.Errorf("%w: FabledExchange schedules its own announces", ErrUnsupported) -} - -func (c *Exchange) Recheck(context.Context, ...string) error { - return fmt.Errorf("%w: FabledExchange has no recheck", ErrUnsupported) -} - -func (c *Exchange) Delete(ctx context.Context, deleteFiles bool, hashes ...string) error { - return c.each(ctx, hashes, func(h string) error { - p := "/api/downloads/" + url.PathEscape(h) - if deleteFiles { - p += "?delete_files=true" - } - _, err := c.call(ctx, http.MethodDelete, p, "", nil) - return err - }) -} - -func (c *Exchange) each(ctx context.Context, hashes []string, do func(string) error) error { - for _, h := range hashes { - if ctx.Err() != nil { - return ctx.Err() - } - if err := do(strings.ToLower(strings.TrimSpace(h))); err != nil { - return err - } - } - return nil -} - -func (c *Exchange) snapshot(ctx context.Context) (exchangeSnapshot, error) { - var snap exchangeSnapshot - body, err := c.call(ctx, http.MethodGet, "/api/downloads", "", nil) - if err != nil { - return snap, err - } - if err := json.Unmarshal(body, &snap); err != nil { - return snap, fmt.Errorf("%w: parse download list: %v", ErrUnreachable, err) - } - return snap, nil -} - -func (c *Exchange) call(ctx context.Context, method, p, contentType string, body []byte) ([]byte, error) { - if c.Config.BaseURL == "" { - return nil, ErrUnconfigured - } - httpc := c.HTTP - if httpc == nil { - httpc = &http.Client{} - } - status, out, err := send(ctx, httpc, c.Config.Timeout, method, - strings.TrimRight(c.Config.BaseURL, "/")+p, contentType, body, func(h http.Header) { - h.Set("Accept", "application/json") - if c.Config.APIKey != "" { - h.Set("Authorization", "Bearer "+c.Config.APIKey) - } - }) - if err != nil { - return nil, err - } - if status >= 200 && status < 300 { - return out, nil - } - var e struct { - Error string `json:"error"` - Reason string `json:"reason"` - } - _ = json.Unmarshal(out, &e) - said := strings.TrimSpace(e.Error) - if said == "" { - said = fmt.Sprintf("HTTP %d", status) - } - switch { - case status == http.StatusUnauthorized || status == http.StatusForbidden: - return nil, fmt.Errorf("%w: FabledExchange refused the API key (%s)", ErrAuth, said) - case status == http.StatusConflict && e.Reason == "duplicate": - return nil, fmt.Errorf("%w: %s", ErrDuplicate, said) - } - return nil, fmt.Errorf("%w: %s", ErrUnreachable, said) -} diff --git a/internal/downloader/pathmap.go b/internal/downloader/pathmap.go deleted file mode 100644 index be43772e..00000000 --- a/internal/downloader/pathmap.go +++ /dev/null @@ -1,107 +0,0 @@ -package downloader - -import ( - "context" - "path" - "strings" -) - -// PathMap is one downloads folder under two names: where Minstrel has it -// mounted (Local) and where the client sees it (Remote). The two usually run -// in different containers. Every path crossing between them swaps one prefix -// for the other. -type PathMap struct { - Local string - Remote string -} - -// Active says the two names differ, so there is something to translate. -func (m PathMap) Active() bool { - return m.Remote != "" && m.Local != "" && path.Clean(m.Remote) != path.Clean(m.Local) -} - -// ToRemote is a Minstrel path as the client names it. -func (m PathMap) ToRemote(p string) string { return swap(p, m.Local, m.Remote) } - -// ToLocal is a client's path as Minstrel names it. -func (m PathMap) ToLocal(p string) string { return swap(p, m.Remote, m.Local) } - -// swap replaces the prefix from with to on segment boundaries -// (/downloads2 is not inside /downloads). A path outside from is unchanged. -func swap(p, from, to string) string { - if p == "" || from == "" || to == "" { - return p - } - from, to = path.Clean(from), path.Clean(to) - clean := path.Clean(p) - if clean == from { - return to - } - if from == "/" { - return path.Join(to, clean) - } - if rest, ok := strings.CutPrefix(clean, from+"/"); ok { - return path.Join(to, rest) - } - return p -} - -// Mapped wraps d so every path it is given or answers with is translated. -// File indices and in-torrent paths need no translation. -func Mapped(d Driver, m PathMap) Driver { - if !m.Active() { - return d - } - return &mapped{Driver: d, m: m} -} - -type mapped struct { - Driver - m PathMap -} - -func (c *mapped) AddTorrent(ctx context.Context, a Add) error { - a.SavePath = c.m.ToRemote(a.SavePath) - return c.Driver.AddTorrent(ctx, a) -} - -func (c *mapped) Torrents(ctx context.Context, hashes ...string) ([]Torrent, error) { - ts, err := c.Driver.Torrents(ctx, hashes...) - for i := range ts { - ts[i].SavePath = c.m.ToLocal(ts[i].SavePath) - ts[i].ContentPath = c.m.ToLocal(ts[i].ContentPath) - } - return ts, err -} - -func (c *mapped) SkipFiles(ctx context.Context, hash string, indices []int) error { - fs, ok := c.Driver.(FileSkipper) - if !ok { - return ErrUnsupported - } - return fs.SkipFiles(ctx, hash, indices) -} - -func (c *mapped) KeepFiles(ctx context.Context, hash string, indices []int) error { - fs, ok := c.Driver.(FileSkipper) - if !ok { - return ErrUnsupported - } - return fs.KeepFiles(ctx, hash, indices) -} - -func (c *mapped) Files(ctx context.Context, hash string) ([]File, error) { - fl, ok := c.Driver.(FileLister) - if !ok { - return nil, ErrUnsupported - } - return fl.Files(ctx, hash) -} - -func (c *mapped) FileStates(ctx context.Context, hash string) ([]FileState, error) { - fp, ok := c.Driver.(FileProgress) - if !ok { - return nil, ErrUnsupported - } - return fp.FileStates(ctx, hash) -} diff --git a/internal/downloader/qbittorrent.go b/internal/downloader/qbittorrent.go deleted file mode 100644 index 73d1eb6b..00000000 --- a/internal/downloader/qbittorrent.go +++ /dev/null @@ -1,367 +0,0 @@ -package downloader - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "mime/multipart" - "net/http" - "net/http/cookiejar" - "net/url" - "strconv" - "strings" - "sync" - "time" -) - -// Client drives one qBittorrent through its WebUI API v2. -type Client struct { - Config Config - - mu sync.Mutex - // http carries the SID cookie once logged in; nil until then. - http *http.Client -} - -// AddTorrent hands qBittorrent a magnet or .torrent bytes, filed under the -// configured category with the save path already set. -func (c *Client) AddTorrent(ctx context.Context, a Add) error { - if a.Magnet == "" && len(a.Torrent) == 0 { - return fmt.Errorf("add: neither a magnet nor torrent bytes") - } - if a.SavePath == "" { - return fmt.Errorf("add: no save path, which would land the download outside the folder Minstrel imports from") - } - body := &bytes.Buffer{} - form := multipart.NewWriter(body) - fields := map[string]string{ - "savepath": a.SavePath, - "category": c.Config.Category, - // Both, because qBittorrent 5 renamed paused to stopped and an older - // one ignores the field it does not know. - "paused": strconv.FormatBool(a.Paused), - "stopped": strconv.FormatBool(a.Paused), - } - if len(a.Tags) > 0 { - fields["tags"] = strings.Join(a.Tags, ",") - } - if a.StopAtMetadata && !a.Paused { - fields["stopCondition"] = "MetadataReceived" - } - if a.Magnet != "" { - fields["urls"] = a.Magnet - } - for k, v := range fields { - if v == "" { - continue - } - if err := form.WriteField(k, v); err != nil { - return fmt.Errorf("add: build form: %w", err) - } - } - if len(a.Torrent) > 0 { - part, err := form.CreateFormFile("torrents", "release.torrent") - if err != nil { - return fmt.Errorf("add: build form: %w", err) - } - if _, err := part.Write(a.Torrent); err != nil { - return fmt.Errorf("add: build form: %w", err) - } - } - if err := form.Close(); err != nil { - return fmt.Errorf("add: build form: %w", err) - } - resp, err := c.post(ctx, "/api/v2/torrents/add", form.FormDataContentType(), body.Bytes()) - if err != nil { - return err - } - // qBittorrent refuses with HTTP 200 and the body "Fails.". - if strings.HasPrefix(strings.TrimSpace(string(resp)), "Fails") { - return fmt.Errorf("%w: the client refused the torrent", ErrUnreachable) - } - return nil -} - -// Torrents lists the configured category's torrents, or the given hashes. -func (c *Client) Torrents(ctx context.Context, hashes ...string) ([]Torrent, error) { - params := url.Values{} - if c.Config.Category != "" { - params.Set("category", c.Config.Category) - } - if len(hashes) > 0 { - params.Set("hashes", strings.Join(hashes, "|")) - } - body, err := c.get(ctx, "/api/v2/torrents/info", params) - if err != nil { - return nil, err - } - var out []Torrent - if err := json.Unmarshal(body, &out); err != nil { - return nil, fmt.Errorf("%w: parse torrent list: %v", ErrUnreachable, err) - } - for i := range out { - out[i].Hash = strings.ToLower(out[i].Hash) - } - return out, nil -} - -// Connected reads qBittorrent's own connection status. -func (c *Client) Connected(ctx context.Context) (bool, error) { - body, err := c.get(ctx, "/api/v2/transfer/info", nil) - if err != nil { - return false, err - } - var info struct { - ConnectionStatus string `json:"connection_status"` - } - if err := json.Unmarshal(body, &info); err != nil { - return false, fmt.Errorf("%w: parse transfer info: %v", ErrUnreachable, err) - } - return info.ConnectionStatus == "connected", nil -} - -// Stop and Start try qBittorrent 5's names first and fall back to 4's. -func (c *Client) Stop(ctx context.Context, hashes ...string) error { - return c.command(ctx, hashes, "/api/v2/torrents/stop", "/api/v2/torrents/pause") -} - -func (c *Client) Start(ctx context.Context, hashes ...string) error { - return c.command(ctx, hashes, "/api/v2/torrents/start", "/api/v2/torrents/resume") -} - -func (c *Client) Reannounce(ctx context.Context, hashes ...string) error { - return c.command(ctx, hashes, "/api/v2/torrents/reannounce", "/api/v2/torrents/reannounce") -} - -func (c *Client) Recheck(ctx context.Context, hashes ...string) error { - return c.command(ctx, hashes, "/api/v2/torrents/recheck", "/api/v2/torrents/recheck") -} - -func (c *Client) Delete(ctx context.Context, deleteFiles bool, hashes ...string) error { - if len(hashes) == 0 { - return nil - } - params := url.Values{ - "hashes": {strings.Join(hashes, "|")}, - "deleteFiles": {strconv.FormatBool(deleteFiles)}, - } - _, err := c.post(ctx, "/api/v2/torrents/delete", "application/x-www-form-urlencoded", []byte(params.Encode())) - return err -} - -func (c *Client) SkipFiles(ctx context.Context, hash string, indices []int) error { - return c.filePriority(ctx, hash, indices, "0") -} - -func (c *Client) KeepFiles(ctx context.Context, hash string, indices []int) error { - return c.filePriority(ctx, hash, indices, "1") -} - -func (c *Client) filePriority(ctx context.Context, hash string, indices []int, priority string) error { - if len(indices) == 0 { - return nil - } - ids := make([]string, len(indices)) - for i, n := range indices { - ids[i] = strconv.Itoa(n) - } - params := url.Values{"hash": {hash}, "id": {strings.Join(ids, "|")}, "priority": {priority}} - _, err := c.post(ctx, "/api/v2/torrents/filePrio", "application/x-www-form-urlencoded", []byte(params.Encode())) - return err -} - -func (c *Client) Files(ctx context.Context, hash string) ([]File, error) { - raw, err := c.files(ctx, hash) - if err != nil { - return nil, err - } - out := make([]File, len(raw)) - for i, f := range raw { - out[i] = File{Index: f.Index, Path: f.Name, Size: f.Size} - } - return out, nil -} - -func (c *Client) FileStates(ctx context.Context, hash string) ([]FileState, error) { - raw, err := c.files(ctx, hash) - if err != nil { - return nil, err - } - out := make([]FileState, len(raw)) - for i, f := range raw { - done := f.Size - if f.Progress < 1 { - // Progress is a float; never round an unfinished file up to whole. - done = min(int64(f.Progress*float64(f.Size)), f.Size-1) - } - out[i] = FileState{Path: f.Name, Size: f.Size, Done: max(done, 0), Skipped: f.Priority == 0} - } - return out, nil -} - -type qbitFile struct { - Index int `json:"index"` - Name string `json:"name"` - Size int64 `json:"size"` - Progress float64 `json:"progress"` - Priority int `json:"priority"` -} - -func (c *Client) files(ctx context.Context, hash string) ([]qbitFile, error) { - body, err := c.get(ctx, "/api/v2/torrents/files", url.Values{"hash": {hash}}) - if err != nil { - return nil, err - } - var raw []qbitFile - if err := json.Unmarshal(body, &raw); err != nil { - return nil, fmt.Errorf("%w: parse file list: %v", ErrUnreachable, err) - } - return raw, nil -} - -func (c *Client) command(ctx context.Context, hashes []string, primary, fallback string) error { - if len(hashes) == 0 { - return nil - } - params := []byte(url.Values{"hashes": {strings.Join(hashes, "|")}}.Encode()) - _, err := c.post(ctx, primary, "application/x-www-form-urlencoded", params) - var status statusError - if errors.As(err, &status) && (status.code == http.StatusNotFound || status.code == http.StatusMethodNotAllowed) { - _, err = c.post(ctx, fallback, "application/x-www-form-urlencoded", params) - } - return err -} - -type statusError struct { - code int - what string -} - -func (e statusError) Error() string { return fmt.Sprintf("%s: HTTP %d", e.what, e.code) } - -func (e statusError) Unwrap() error { return ErrUnreachable } - -func (c *Client) get(ctx context.Context, path string, params url.Values) ([]byte, error) { - endpoint := path - if len(params) > 0 { - endpoint += "?" + params.Encode() - } - return c.do(ctx, http.MethodGet, endpoint, "", nil) -} - -func (c *Client) post(ctx context.Context, path, contentType string, body []byte) ([]byte, error) { - return c.do(ctx, http.MethodPost, path, contentType, body) -} - -// do logs in when there is no session, and once more on a 403, which is how -// qBittorrent says a session expired. -func (c *Client) do(ctx context.Context, method, path, contentType string, body []byte) ([]byte, error) { - if c.Config.BaseURL == "" { - return nil, ErrUnconfigured - } - if err := c.ensureSession(ctx, false); err != nil { - return nil, err - } - out, err := c.call(ctx, method, path, contentType, body) - var status statusError - if errors.As(err, &status) && status.code == http.StatusForbidden { - if err := c.ensureSession(ctx, true); err != nil { - return nil, err - } - return c.call(ctx, method, path, contentType, body) - } - return out, err -} - -func (c *Client) ensureSession(ctx context.Context, force bool) error { - c.mu.Lock() - defer c.mu.Unlock() - if c.http != nil && !force { - return nil - } - jar, err := cookiejar.New(nil) - if err != nil { - return fmt.Errorf("cookie jar: %w", err) - } - httpc := &http.Client{Jar: jar} - params := url.Values{"username": {c.Config.Username}, "password": {c.Config.Password}} - out, err := c.callWith(ctx, httpc, http.MethodPost, "/api/v2/auth/login", - "application/x-www-form-urlencoded", []byte(params.Encode())) - if err != nil { - var status statusError - if errors.As(err, &status) && status.code == http.StatusForbidden { - return fmt.Errorf("%w: too many failed attempts, or this address is banned", ErrAuth) - } - return err - } - if strings.HasPrefix(strings.TrimSpace(string(out)), "Fails") { - return fmt.Errorf("%w: wrong username or password", ErrAuth) - } - c.http = httpc - return nil -} - -func (c *Client) call(ctx context.Context, method, path, contentType string, body []byte) ([]byte, error) { - c.mu.Lock() - httpc := c.http - c.mu.Unlock() - if httpc == nil { - httpc = &http.Client{} - } - return c.callWith(ctx, httpc, method, path, contentType, body) -} - -func (c *Client) callWith(ctx context.Context, httpc *http.Client, method, path, contentType string, body []byte) ([]byte, error) { - base := strings.TrimRight(c.Config.BaseURL, "/") - status, out, err := send(ctx, httpc, c.Config.Timeout, method, base+path, contentType, body, func(h http.Header) { - // qBittorrent's CSRF check refuses a request without a matching - // Referer. - h.Set("Referer", base) - }) - if err != nil { - return nil, err - } - if status < 200 || status >= 300 { - return nil, statusError{code: status, what: path} - } - return out, nil -} - -// send makes one request to a download client under its timeout, lets the -// caller add headers, and reads at most 16 MB. It returns the status for the -// caller to read, because each client's refusals are its own. -func send(ctx context.Context, httpc *http.Client, timeout time.Duration, method, target, contentType string, body []byte, set func(http.Header)) (int, []byte, error) { - if timeout <= 0 { - timeout = DefaultTimeout - } - ctx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - var reader io.Reader - if body != nil { - reader = bytes.NewReader(body) - } - req, err := http.NewRequestWithContext(ctx, method, target, reader) - if err != nil { - return 0, nil, fmt.Errorf("%w: build request: %v", ErrUnreachable, err) - } - req.Header.Set("User-Agent", UserAgent) - if contentType != "" { - req.Header.Set("Content-Type", contentType) - } - if set != nil { - set(req.Header) - } - resp, err := httpc.Do(req) - if err != nil { - return 0, nil, fmt.Errorf("%w: %v", ErrUnreachable, err) - } - defer func() { _ = resp.Body.Close() }() - out, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) - if err != nil { - return 0, nil, fmt.Errorf("%w: read body: %v", ErrUnreachable, err) - } - return resp.StatusCode, out, nil -} diff --git a/internal/eventbus/eventbus.go b/internal/eventbus/eventbus.go index d9b42eda..fb133dad 100644 --- a/internal/eventbus/eventbus.go +++ b/internal/eventbus/eventbus.go @@ -24,7 +24,7 @@ import ( ) // Event is a single broadcast message. Kind names follow a "domain.action" -// convention (e.g. "track.liked", "request.status_changed"). UserID, when +// convention (e.g. "track.liked", "playlist.system_rebuilt"). UserID, when // non-empty, scopes the event to a specific user — subscribers receive // only events with UserID == their auth user OR with empty UserID (which // means "broadcast to everyone subscribed"). @@ -118,3 +118,36 @@ func (b *Bus) SubscriberCount() int { defer b.mu.RUnlock() return len(b.subscribers) } + +// LikeChanged is the event every surface publishes when a like changes, so +// the web and Android apps hear about a like made anywhere, a Subsonic app +// included. entityType is "track", "album" or "artist"; the kind is +// ".liked" or ".unliked". +func LikeChanged(userID, entityType, entityID string, liked bool) Event { + action := "liked" + if !liked { + action = "unliked" + } + return Event{ + Kind: entityType + "." + action, + UserID: userID, + Data: map[string]any{ + "entity_type": entityType, + "entity_id": entityID, + }, + } +} + +// LedBy is the entities a like or unlike reports: every one it changed, led +// by the one asked for, which is reported even when it was already in that +// state (so the asking client always hears back). A like is on the song, so +// it can change several copies at once. +func LedBy[T comparable](asked T, changed []T) []T { + out := []T{asked} + for _, c := range changed { + if c != asked { + out = append(out, c) + } + } + return out +} diff --git a/internal/exchange/exchange.go b/internal/exchange/exchange.go deleted file mode 100644 index 987c90bc..00000000 --- a/internal/exchange/exchange.go +++ /dev/null @@ -1,181 +0,0 @@ -// Package exchange talks to FabledExchange's native API for the two jobs that -// are not downloading: searching its DHT index (/api/search) and describing -// one torrent (/api/torrents/{infohash}). Downloading is internal/downloader's. -// -// The native search rather than Exchange's Torznab feed, because it reports -// whether a swarm was measured and how many files a torrent holds, which the -// feed cannot say. -package exchange - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "log/slog" - "net/http" - "strings" - "time" - - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -// ErrUnconfigured is an Exchange with no address. -var ErrUnconfigured = errors.New("exchange is not configured") - -// ErrUnreachable is a call that could not be made or was not understood. -var ErrUnreachable = errors.New("exchange unreachable") - -// ErrAuth is an API key Exchange refused, or a secured Exchange asked with -// none. -var ErrAuth = errors.New("exchange refused the API key") - -// ErrUnknown is a torrent Exchange has not crawled: a JSON 404, which is an -// answer and not a fault. -var ErrUnknown = errors.New("exchange has not crawled this torrent") - -// UserAgent names Minstrel in Exchange's logs. -const UserAgent = "Minstrel (self-hosted music server; release search)" - -// DefaultTimeout is what an unset Timeout means. Exchange answers from its -// own database. -const DefaultTimeout = 20 * time.Second - -// Config is one Exchange. -type Config struct { - BaseURL string - // APIKey is optional and sent only when set: an empty bearer makes a - // secured Exchange answer 401. - APIKey string - Timeout time.Duration -} - -// Client asks one Exchange. -type Client struct { - Config Config - // HTTP is injectable for tests. Nil takes http.DefaultClient. - HTTP *http.Client - // Code is the acquisition_services row, stamped onto search results. - Code string - Logger *slog.Logger -} - -func (c *Client) log() *slog.Logger { - if c == nil || c.Logger == nil { - return slog.Default() - } - return c.Logger -} - -// Detail is what Exchange knows about one torrent. -type Detail struct { - InfoHash string `json:"infohash"` - Name string `json:"name"` - Size int64 `json:"size"` - FilesCount int `json:"files_count"` - Seeders int `json:"seeders"` - SwarmKnown bool `json:"swarm_known"` - Leechers int `json:"leechers"` - LeechersKnown bool `json:"leechers_known"` - ContentType string `json:"content_type"` - Files []DetailFile `json:"files"` -} - -// DetailFile is one file inside a torrent. -type DetailFile struct { - Index int `json:"index"` - Path string `json:"path"` - Size int64 `json:"size"` -} - -// Torrent asks Exchange about one v1 infohash. -func (c *Client) Torrent(ctx context.Context, infohash string) (Detail, error) { - if strings.TrimSpace(c.Config.BaseURL) == "" { - return Detail{}, ErrUnconfigured - } - hash := indexer.NormalizeHash(infohash) - if len(hash) != 40 || !indexer.IsInfoHash(hash) { - return Detail{}, fmt.Errorf("%w: %q is not a 40-character infohash", ErrUnreachable, infohash) - } - body, err := c.get(ctx, "/api/torrents/"+hash) - if err != nil { - return Detail{}, err - } - var out Detail - if err := json.Unmarshal(body, &out); err != nil { - return Detail{}, fmt.Errorf("%w: parse torrent detail: %v", ErrUnreachable, err) - } - if out.InfoHash == "" { - return Detail{}, ErrUnknown - } - return out, nil -} - -func (c *Client) get(ctx context.Context, path string) ([]byte, error) { - timeout := c.Config.Timeout - if timeout <= 0 { - timeout = DefaultTimeout - } - ctx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - - target := strings.TrimRight(c.Config.BaseURL, "/") + path - req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) - if err != nil { - return nil, fmt.Errorf("%w: %v", ErrUnreachable, err) - } - req.Header.Set("User-Agent", UserAgent) - req.Header.Set("Accept", "application/json") - if key := strings.TrimSpace(c.Config.APIKey); key != "" { - req.Header.Set("Authorization", "Bearer "+key) - } - client := c.HTTP - if client == nil { - client = http.DefaultClient - } - res, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("%w: %v", ErrUnreachable, err) - } - defer func() { _ = res.Body.Close() }() - body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - if err != nil { - return nil, fmt.Errorf("%w: read answer: %v", ErrUnreachable, err) - } - switch { - case res.StatusCode == http.StatusNotFound: - // A 404 that is not JSON came from something else at this address, - // which must not look like a healthy Exchange that lacks a torrent. - if !looksLikeJSON(body) { - return nil, fmt.Errorf("%w: something at this address answered 404, "+ - "but it was not FabledExchange", ErrUnreachable) - } - return nil, ErrUnknown - case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden: - return nil, fmt.Errorf("%w: %s", ErrAuth, - message(body, "set this FabledExchange's API key in Minstrel's settings")) - case res.StatusCode == http.StatusServiceUnavailable: - return nil, fmt.Errorf("%w: %s", ErrUnreachable, message(body, "no index is configured")) - case res.StatusCode < 200 || res.StatusCode >= 300: - return nil, fmt.Errorf("%w: %s", ErrUnreachable, - message(body, fmt.Sprintf("returned %d", res.StatusCode))) - } - return body, nil -} - -// message is Exchange's own {"error": "..."} text, or fallback. -func message(body []byte, fallback string) string { - var env struct { - Error string `json:"error"` - } - if err := json.Unmarshal(body, &env); err == nil && strings.TrimSpace(env.Error) != "" { - return strings.TrimSpace(env.Error) - } - return fallback -} - -func looksLikeJSON(body []byte) bool { - t := strings.TrimSpace(string(body)) - return strings.HasPrefix(t, "{") || strings.HasPrefix(t, "[") -} diff --git a/internal/exchange/exchange_test.go b/internal/exchange/exchange_test.go deleted file mode 100644 index bfd5aa92..00000000 --- a/internal/exchange/exchange_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package exchange - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -func TestTorrent_SendsTheKeyOnlyWhenSet(t *testing.T) { - auth := make(chan string, 2) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - auth <- r.Header.Get("Authorization") - _, _ = w.Write([]byte(`{"infohash": "` + strings.Repeat("a", 40) + `", "files_count": 12}`)) - })) - defer srv.Close() - - for _, key := range []string{"", "k"} { - c := &Client{Config: Config{BaseURL: srv.URL, APIKey: key}} - d, err := c.Torrent(context.Background(), strings.Repeat("A", 40)) - if err != nil || d.FilesCount != 12 { - t.Fatalf("key %q: detail %+v err %v", key, d, err) - } - } - if without, with := <-auth, <-auth; without != "" || with != "Bearer k" { - t.Errorf("Authorization = %q then %q, want none without a key and a bearer with one", without, with) - } -} - -func TestTorrent_TellsAnUncrawledTorrentFromAnotherService(t *testing.T) { - for name, tc := range map[string]struct { - status int - body string - want error - }{ - "Exchange has not crawled it": {http.StatusNotFound, `{"error": "unknown torrent"}`, ErrUnknown}, - "not FabledExchange": {http.StatusNotFound, `404`, ErrUnreachable}, - "a refused key": {http.StatusUnauthorized, `{"error": "bad key"}`, ErrAuth}, - } { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(tc.status) - _, _ = w.Write([]byte(tc.body)) - })) - _, err := (&Client{Config: Config{BaseURL: srv.URL}}).Torrent(context.Background(), strings.Repeat("0", 40)) - srv.Close() - if !errors.Is(err, tc.want) { - t.Errorf("%s: err = %v, want %v", name, err, tc.want) - } - } -} - -func TestSearch_PagesAndKeepsMeasuredSwarmsOnly(t *testing.T) { - queries := make(chan string, 4) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - queries <- r.URL.RawQuery - offset := r.URL.Query().Get("offset") - var rows []string - if offset == "0" { - for i := 0; i < SearchLimit; i++ { - rows = append(rows, fmt.Sprintf(`{"infohash": "%040x", "name": "r%d", "content_type": "music", "seeders": 5, "swarm_known": %t}`, i, i, i == 0)) - } - } else { - // A repeat of page one's first hash, which must not be listed twice. - rows = append(rows, fmt.Sprintf(`{"infohash": "%040x", "name": "again"}`, 0)) - } - _, _ = fmt.Fprintf(w, `{"total": %d, "results": [%s]}`, SearchLimit+1, strings.Join(rows, ",")) - })) - defer srv.Close() - - c := &Client{Code: "exchange", Config: Config{BaseURL: srv.URL}} - results, err := c.Search(context.Background(), indexer.Query{Text: "x", Categories: indexer.MusicCategories}) - if err != nil { - t.Fatalf("search: %v", err) - } - close(queries) - var asked []string - for q := range queries { - asked = append(asked, q) - } - if len(asked) != 2 || !strings.Contains(asked[0], "type=music") { - t.Errorf("queries = %v, want two pages asking for music", asked) - } - if len(results) != SearchLimit { - t.Errorf("results = %d, want %d (the repeat dropped)", len(results), SearchLimit) - } - if r := results[0]; !r.SwarmKnown || r.Seeders != 5 || r.Category != 3000 || r.Source != "exchange" || !strings.HasPrefix(r.Magnet, "magnet:") { - t.Errorf("first = %+v", r) - } - if r := results[1]; r.SwarmKnown || r.Seeders != 0 { - t.Errorf("an unmeasured swarm reported seeders: %+v", r) - } -} - -func TestSearch_ARefusedKeyReadsAsAuth(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusForbidden) - })) - defer srv.Close() - _, err := (&Client{Config: Config{BaseURL: srv.URL}}).Search(context.Background(), indexer.Query{Text: "x"}) - if !errors.Is(err, indexer.ErrAuth) { - t.Fatalf("err = %v, want indexer.ErrAuth", err) - } -} diff --git a/internal/exchange/search.go b/internal/exchange/search.go deleted file mode 100644 index d2fc8724..00000000 --- a/internal/exchange/search.go +++ /dev/null @@ -1,169 +0,0 @@ -package exchange - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/url" - "strings" - - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -// SearchLimit is one page of /api/search; SearchDepth is the most read across -// pages. A query matching more than SearchDepth is too broad to judge anyway. -const ( - SearchLimit = 100 - SearchDepth = 300 -) - -type searchResult struct { - InfoHash string `json:"infohash"` - Name string `json:"name"` - Size int64 `json:"size"` - FilesCount int `json:"files_count"` - ContentType string `json:"content_type"` - Seeders int `json:"seeders"` - SwarmKnown bool `json:"swarm_known"` - Leechers int `json:"leechers"` - LeechersKnown bool `json:"leechers_known"` -} - -type searchPage struct { - Total int `json:"total"` - Results []searchResult `json:"results"` -} - -// Search asks Exchange's DHT index. Every result is a magnet, so there is no -// .torrent to fetch through it. A later page that fails keeps the earlier -// ones; a first page that fails is the search failing. -func (c *Client) Search(ctx context.Context, q indexer.Query) ([]indexer.Result, error) { - if strings.TrimSpace(c.Config.BaseURL) == "" { - return nil, indexer.ErrUnconfigured - } - params := url.Values{"q": {q.Text}, "limit": {fmt.Sprint(SearchLimit)}} - if t := contentType(q.Categories); t != "" { - params.Set("type", t) - } - var ( - out []indexer.Result - seen = map[string]bool{} - ) - for offset := 0; offset < SearchDepth; offset += SearchLimit { - params.Set("offset", fmt.Sprint(offset)) - page, err := c.searchPage(ctx, params) - if err != nil { - if offset == 0 { - return nil, err - } - c.log().Warn("exchange: a later page of a search could not be read; keeping the pages before it", - "q", q.Text, "offset", offset, "err", err) - break - } - for _, r := range page.Results { - res, ok := c.result(r) - if !ok || seen[res.InfoHash] { - continue - } - seen[res.InfoHash] = true - out = append(out, res) - } - if len(page.Results) < SearchLimit || offset+SearchLimit >= page.Total { - break - } - } - return out, nil -} - -func (c *Client) searchPage(ctx context.Context, params url.Values) (searchPage, error) { - var page searchPage - body, err := c.get(ctx, "/api/search?"+params.Encode()) - if err != nil { - return page, searchError(err) - } - if err := json.Unmarshal(body, &page); err != nil { - return page, fmt.Errorf("%w: parse search results: %v", indexer.ErrUnreachable, err) - } - return page, nil -} - -func (c *Client) result(r searchResult) (indexer.Result, bool) { - hash := indexer.NormalizeHash(r.InfoHash) - if hash == "" || strings.TrimSpace(r.Name) == "" { - return indexer.Result{}, false - } - res := indexer.Result{ - Title: r.Name, - InfoHash: hash, - Magnet: magnet(hash, r.Name), - SizeBytes: r.Size, - Category: category(r.ContentType), - Source: c.Code, - FilesCount: r.FilesCount, - SwarmKnown: r.SwarmKnown, - } - // Seeders only when measured: an unmeasured count is not health. - if r.SwarmKnown { - res.Seeders, res.Peers = r.Seeders, r.Seeders - if r.LeechersKnown { - res.Peers = r.Seeders + r.Leechers - } - } - return res, true -} - -// searchError puts Exchange's errors in the vocabulary every search source -// shares, so a refused key reads the same whichever source refused it. -func searchError(err error) error { - switch { - case errors.Is(err, ErrAuth): - return fmt.Errorf("%w: %v", indexer.ErrAuth, err) - case errors.Is(err, ErrUnknown): - return fmt.Errorf("%w: this FabledExchange has no search API", indexer.ErrUnreachable) - } - return fmt.Errorf("%w: %v", indexer.ErrUnreachable, err) -} - -// contentType narrows Exchange's search to music when the query asks only -// for music categories (3000s, not 3030 audiobooks). -func contentType(cats []int) string { - music := false - for _, c := range cats { - if c < 3000 || c >= 4000 || c == 3030 { - return "" - } - music = true - } - if music { - return "music" - } - return "" -} - -func category(contentType string) int { - switch contentType { - case "music": - return 3000 - case "audiobook": - return 3030 - case "ebook": - return 7020 - case "comic": - return 7030 - case "movie": - return 2000 - case "tv": - return 5000 - } - return 8000 -} - -// magnet is a trackerless magnet for a hash Exchange found on the DHT. -func magnet(hash, name string) string { - m := "magnet:?xt=urn:btih:" + hash - if name != "" { - m += "&dn=" + url.QueryEscape(name) - } - return m -} diff --git a/internal/gc/worker.go b/internal/gc/worker.go index c88ad965..2bdccc35 100644 --- a/internal/gc/worker.go +++ b/internal/gc/worker.go @@ -16,9 +16,6 @@ // - GcDeleteExpiredPasswordResets // - GcDeleteExpiredSessions (idle 30d / absolute 1y) // - GcPruneDiagnostics (30d retention) -// - GcDeleteExpiredSuggestionSnoozes (snoozes expire, then go) -// - GcDeleteOrphanedCandidateArtistTags(+State) (the similarity feed -// churns, so cached candidate tags outlive their candidates) package gc import ( @@ -28,7 +25,8 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // defaultTick is the production sweep cadence. 1 hour is generous @@ -62,17 +60,7 @@ func (w *Worker) Run(ctx context.Context) { // Fire once at start so a freshly-deployed server doesn't wait a // full tick before doing the initial sweep. Matches the scrobble // + similarity workers' "sweep then tick" pattern. - w.tickOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.tickOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "gc", w.tick, w.tickOnce) } // tickOnce runs each sweep once, logging the affected-row count. @@ -87,14 +75,6 @@ func (w *Worker) tickOnce(ctx context.Context) { w.runSweep(ctx, "delete_expired_password_resets", q.GcDeleteExpiredPasswordResets) w.runSweep(ctx, "delete_expired_sessions", q.GcDeleteExpiredSessions) w.runSweep(ctx, "prune_diagnostics", q.GcPruneDiagnostics) - w.runSweep(ctx, "delete_expired_suggestion_snoozes", q.GcDeleteExpiredSuggestionSnoozes) - // Tags before state: if the process dies between the two, a candidate left - // with a state row and no tags simply reads as "settled, nothing found", - // which is already a valid state. The reverse order could leave tags with - // no state row, which the drainer would treat as never-processed and - // re-fetch on top of rows that are already there. - w.runSweep(ctx, "orphaned_candidate_artist_tags", q.GcDeleteOrphanedCandidateArtistTags) - w.runSweep(ctx, "orphaned_candidate_artist_tag_state", q.GcDeleteOrphanedCandidateArtistTagState) } // runSweep is a small adapter so each sweep call site is a one-liner diff --git a/internal/gc/worker_test.go b/internal/gc/worker_test.go index 19868cb7..039ddd35 100644 --- a/internal/gc/worker_test.go +++ b/internal/gc/worker_test.go @@ -4,16 +4,14 @@ import ( "context" "io" "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // testWorker constructs a Worker against MINSTREL_TEST_DATABASE_URL. @@ -22,23 +20,8 @@ import ( // to seed. func testWorker(t *testing.T) (*Worker, *pgxpool.Pool) { t.Helper() - if testing.Short() { - t.Skip("skipping gc integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) return NewWorker(pool, logger), pool } diff --git a/internal/genretag/genretag.go b/internal/genretag/genretag.go new file mode 100644 index 00000000..d53ca163 --- /dev/null +++ b/internal/genretag/genretag.go @@ -0,0 +1,23 @@ +// Package genretag reads a track's stored genre, one string that can name +// several genres. +package genretag + +import "strings" + +// Split returns the genres a track's genre string names. Tag editors join +// several genres with ";" or ","; each piece is trimmed and empty pieces are +// dropped, so a nil or blank genre gives none. A genre without either +// separator comes back whole. +func Split(genre *string) []string { + if genre == nil { + return nil + } + parts := strings.FieldsFunc(*genre, func(r rune) bool { return r == ';' || r == ',' }) + out := make([]string, 0, len(parts)) + for _, p := range parts { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return out +} diff --git a/internal/genretag/genretag_test.go b/internal/genretag/genretag_test.go new file mode 100644 index 00000000..1938dd7f --- /dev/null +++ b/internal/genretag/genretag_test.go @@ -0,0 +1,27 @@ +package genretag + +import ( + "slices" + "testing" +) + +func TestSplit(t *testing.T) { + for _, tc := range []struct { + in *string + want []string + }{ + {nil, nil}, + {ptr(""), nil}, + {ptr("Pop"), []string{"Pop"}}, + {ptr("Pop; Rock, Jazz"), []string{"Pop", "Rock", "Jazz"}}, + {ptr(" Pop ; Rock "), []string{"Pop", "Rock"}}, + {ptr(";; Pop ;;"), []string{"Pop"}}, + {ptr("Jazz Fusion"), []string{"Jazz Fusion"}}, + } { + if got := Split(tc.in); len(got)+len(tc.want) > 0 && !slices.Equal(got, tc.want) { + t.Errorf("Split(%v) = %q, want %q", tc.in, got, tc.want) + } + } +} + +func ptr(s string) *string { return &s } diff --git a/internal/importer/importer.go b/internal/importer/importer.go deleted file mode 100644 index 024c96c4..00000000 --- a/internal/importer/importer.go +++ /dev/null @@ -1,610 +0,0 @@ -package importer - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "log/slog" - "os" - "path/filepath" - "slices" - "strconv" - "sync" - "time" - - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -// Import states, as grabs.import_state holds them. -const ( - StateDownloading = "downloading" - StateWaiting = "waiting" - StateImporting = "importing" - StateImported = "imported" - StateRefused = "refused" - StateReview = "review" - StateHeld = "held" - StateFailed = "failed" -) - -const ( - // interval: a finished download is noticed within a minute. One - // Torrents call per download client, so the client barely notices. - interval = time.Minute - // passTimeout bounds a pass: fingerprinting a long album against - // AcoustID's pace takes a minute or two, so half an hour is a hang. - passTimeout = 30 * time.Minute - // staleMinutes: an import still "importing" after this was cut short - // (a restart mid-copy) and is tried again. - staleMinutes = 30 -) - -// Scanner reads new files into the library. -type Scanner interface { - ScanFiles(ctx context.Context, paths []string) ([]pgtype.UUID, error) -} - -// Catalogue lists a release group's editions. -type Catalogue interface { - Releases(ctx context.Context, groupMBID string) (catalogue.Editions, error) -} - -// Importer watches every live grab's download and imports it once finished. -type Importer struct { - pool *pgxpool.Pool - Scanner Scanner - Catalogue Catalogue - Printer Printer - // Roots are the library's folders (the scan paths), read on every use - // because they change in Settings. New music is filed under the - // one the settings name, or the first. - Roots func() []string - // DataDir is where cached art lives, for tidying an artist an upgrade - // leaves with nothing. Empty skips it. - DataDir string - // ClientFor builds the download client a grab went to. Defaults to - // acquire.DownloadClientFor. - ClientFor func(ctx context.Context, code string) (downloader.Driver, error) - logger *slog.Logger - wake chan struct{} - mu sync.Mutex // one pass at a time -} - -// New returns an Importer. printer may be nil: the check then rests on -// lengths and tags. -func New(pool *pgxpool.Pool, scanner Scanner, cat Catalogue, printer Printer, roots func() []string, logger *slog.Logger) *Importer { - if logger == nil { - logger = slog.Default() - } - im := &Importer{pool: pool, Scanner: scanner, Catalogue: cat, Printer: printer, Roots: roots, - logger: logger, wake: make(chan struct{}, 1)} - im.ClientFor = func(ctx context.Context, code string) (downloader.Driver, error) { - return acquire.DownloadClientFor(ctx, pool, code) - } - return im -} - -// Wake asks for a pass now: after a grab, or a person's decision. -func (im *Importer) Wake() { - select { - case im.wake <- struct{}{}: - default: - } -} - -// Run passes every minute, and when woken, until ctx ends. -func (im *Importer) Run(ctx context.Context) { - t := time.NewTicker(interval) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - case <-im.wake: - } - rep := im.Pass(ctx) - if rep.Imported+rep.Refused+rep.Review+rep.Held+rep.Failed > 0 || rep.Error != "" { - im.logger.Info("import: pass", "imported", rep.Imported, "refused", rep.Refused, - "review", rep.Review, "held", rep.Held, "failed", rep.Failed, - "downloading", rep.Downloading, "error", rep.Error) - } - } -} - -// Report is one pass. -type Report struct { - Downloading, Imported, Refused, Review, Held, Failed, Waiting int - Error string -} - -// Pass looks at every live grab once. -func (im *Importer) Pass(ctx context.Context) Report { - im.mu.Lock() - defer im.mu.Unlock() - ctx, cancel := context.WithTimeout(ctx, passTimeout) - defer cancel() - var rep Report - q := dbq.New(im.pool) - if _, err := q.ReclaimStaleImports(ctx, staleMinutes); err != nil { - rep.Error = err.Error() - return rep - } - grabs, err := q.ListLiveGrabs(ctx) - if err != nil { - rep.Error = err.Error() - return rep - } - byClient := map[string][]dbq.ListLiveGrabsRow{} - var order []string - for _, g := range grabs { - if _, ok := byClient[g.Client]; !ok { - order = append(order, g.Client) - } - byClient[g.Client] = append(byClient[g.Client], g) - } - for _, code := range order { - im.passClient(ctx, q, code, byClient[code], &rep) - } - return rep -} - -func (im *Importer) passClient(ctx context.Context, q *dbq.Queries, code string, gs []dbq.ListLiveGrabsRow, rep *Report) { - wait := func(g dbq.ListLiveGrabsRow, why string) { - rep.Waiting++ - _ = q.SetGrabProgress(ctx, dbq.SetGrabProgressParams{ - ID: g.ID, Progress: g.Progress, ImportState: StateWaiting, ImportReason: why}) - } - d, err := im.ClientFor(ctx, code) - if err != nil { - for _, g := range gs { - wait(g, fmt.Sprintf("Can't reach its download client: %v.", err)) - } - return - } - hashes := make([]string, 0, len(gs)) - for _, g := range gs { - hashes = append(hashes, g.InfoHash) - } - ts, err := d.Torrents(ctx, hashes...) - if err != nil { - for _, g := range gs { - wait(g, fmt.Sprintf("Can't reach its download client %s: %s", code, indexer.FirstLine(err.Error()))) - } - return - } - byHash := map[string]downloader.Torrent{} - for _, t := range ts { - byHash[indexer.NormalizeHash(t.Hash)] = t - } - for _, g := range gs { - if ctx.Err() != nil { - return - } - switch g.ImportState { - case StateReview, StateFailed, StateImporting: - continue - } - t, ok := byHash[indexer.NormalizeHash(g.InfoHash)] - if !ok { - continue // gone from the client: the lifecycle settles it - } - if !g.WantID.Valid { - wait(g, "Its album is no longer wanted.") - continue - } - if !finished(ctx, d, t) { - rep.Downloading++ - _ = q.SetGrabProgress(ctx, dbq.SetGrabProgressParams{ - ID: g.ID, Progress: float32(min(t.Progress, 0.999)), ImportState: StateDownloading}) - continue - } - claimed, err := q.ClaimGrabImport(ctx, g.ID) - if err != nil { - continue // claimed by a pass racing this one, or ended - } - switch out := im.importOne(ctx, q, claimed, d, t); out { - case StateImported: - rep.Imported++ - case StateRefused: - rep.Refused++ - case StateReview: - rep.Review++ - case StateHeld: - rep.Held++ - case StateFailed: - rep.Failed++ - case StateWaiting: - rep.Waiting++ - } - } -} - -// upStates are qBittorrent's states for a torrent that has every byte and -// is seeding, paused or queued to seed. Exchange's states arrive in the same -// vocabulary. -var upStates = map[string]bool{ - "uploading": true, "stalledUP": true, "pausedUP": true, "stoppedUP": true, - "queuedUP": true, "forcedUP": true, "checkingUP": true, -} - -// finished: whole, in a seeding state, and no wanted file short of bytes. -func finished(ctx context.Context, d downloader.Driver, t downloader.Torrent) bool { - if !t.Done() || !upStates[t.State] { - return false - } - if fp, ok := d.(downloader.FileProgress); ok { - if states, err := fp.FileStates(ctx, t.Hash); err == nil { - for _, f := range states { - if f.Unfinished() { - return false - } - } - } - } - return true -} - -// Detail is what grabs.import_detail keeps: the verdict and what it rested -// on, the edition chosen, and what happened to the files. -type Detail struct { - Verdict Verdict `json:"verdict"` - Edition string `json:"edition,omitempty"` - EditionMBID string `json:"edition_mbid,omitempty"` - Files []string `json:"files,omitempty"` - Placed int `json:"placed,omitempty"` - Skipped int `json:"skipped,omitempty"` - Untagged int `json:"untagged,omitempty"` - // RehomedFrom: the album it was grabbed for, when it turned out to be - // another wanted album. - RehomedFrom string `json:"rehomed_from,omitempty"` -} - -// importOne checks and files one finished download and records the outcome. -func (im *Importer) importOne(ctx context.Context, q *dbq.Queries, g dbq.Grab, d downloader.Driver, t downloader.Torrent) string { - record := func(state, reason, end string, det Detail, files int, dest string) string { - body, _ := json.Marshal(det) - // The outcome is written even when the pass's context is ending: - // a claimed grab left "importing" waits half an hour to be retried. - wctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) - defer cancel() - if _, err := q.RecordImport(wctx, dbq.RecordImportParams{ - ID: g.ID, ImportState: state, ImportReason: reason, ImportDetail: body, - ImportedFiles: int32(files), Destination: dest, EndReason: end, - }); err != nil { - im.logger.Warn("import: record outcome", "grab", g.Name, "state", state, "err", err) - } - im.logger.Info("import: "+state, "grab", g.Name, "reason", reason) - return state - } - - w, err := im.want(ctx, q, g.WantID) - if err != nil { - return record(StateWaiting, "Its album could not be read: "+err.Error(), "", Detail{}, 0, "") - } - editions, err := im.editions(ctx, w.GroupMBID) - if err != nil { - return record(StateWaiting, "MusicBrainz could not be reached to check it against the album; trying again shortly.", - "", Detail{}, 0, "") - } - src := t.ContentPath - if src == "" { - src = filepath.Join(g.SavePath, t.Name) - } - files, printed, err := inspect(ctx, src, im.Printer) - if err != nil { - return record(StateFailed, fmt.Sprintf("Couldn't read the download at %s: %v", src, err), "", Detail{}, 0, "") - } - v := Verify(w, editions, files, printed, g.ImportForced) - det := Detail{Verdict: v} - for _, f := range files { - det.Files = append(det.Files, f.Rel) - } - if v.Edition >= 0 { - det.Edition, det.EditionMBID = describe(editions[v.Edition]), editions[v.Edition].MBID - } - - switch v.Outcome { - case Review: - return record(StateReview, v.Reason, "", det, 0, "") - case Refuse: - if v.Code == CodeWrongAlbum { - if out, ok := im.rehome(ctx, q, g, d, w, files, printed, record); ok { - return out - } - } - im.refuse(ctx, q, g, d, w, v.Reason, pgtype.UUID{}) - return record(StateRefused, v.Reason, StateRefused, det, 0, "") - } - return im.place(ctx, q, g, d, w, editions, files, v, det, record) -} - -type recordFunc func(state, reason, end string, det Detail, files int, dest string) string - -// place files an accepted download and records it imported, or held when -// the library already had every track. -func (im *Importer) place(ctx context.Context, q *dbq.Queries, g dbq.Grab, d downloader.Driver, w Want, - editions []Edition, files []File, v Verdict, det Detail, record recordFunc) string { - root, err := im.root(ctx, q) - if err != nil { - return record(StateFailed, "Not imported: "+err.Error()+".", "", det, 0, "") - } - var e *Edition - if v.Edition >= 0 { - e = &editions[v.Edition] - } - plan := Plan(root, w, e, files, v.Pairs) - if w.Upgrade != "" { - return im.placeUpgrade(ctx, q, g, d, w, e, files, plan, v, det, record) - } - heldRec, heldPos, err := im.held(ctx, q, w, plan) - if err != nil { - return record(StateWaiting, "Couldn't read what the library holds: "+err.Error(), "", det, 0, "") - } - - var placed []string - for _, pl := range plan { - if (pl.Recording != "" && heldRec[pl.Recording]) || heldPos[[2]int{pl.Disc, pl.Track}] { - det.Skipped++ - continue - } - tags := Tags{Title: pl.Title, Artist: w.Artist, Album: w.Title, AlbumArtist: w.Artist, Year: w.Year, - Disc: pl.Disc, Discs: pl.Discs, Track: pl.Track, Tracks: pl.Tracks, - GroupMBID: w.GroupMBID, RecordingMBID: pl.Recording, ArtistMBID: w.ArtistMBID} - if e != nil { - tags.ReleaseMBID = e.MBID - } - tagged, err := Place(ctx, files[pl.File].Path, pl.Dest, tags) - if errors.Is(err, ErrOccupied) { - det.Skipped++ - continue - } - if err != nil { - for _, p := range placed { - _ = os.Remove(p) - } - return record(StateFailed, fmt.Sprintf("Copying into the library failed, and nothing was left behind: %v", err), - "", det, 0, "") - } - placed = append(placed, pl.Dest) - if !tagged { - det.Untagged++ - } - } - det.Placed = len(placed) - if len(placed) == 0 { - im.removeFromClient(ctx, d, g) - return record(StateHeld, fmt.Sprintf("The library already holds every track of %s, so nothing was imported.", w.Title), - StateHeld, det, 0, "") - } - - if _, err := im.Scanner.ScanFiles(ctx, placed); err != nil { - // The watcher and the next scan find the files anyway. - im.logger.Warn("import: scan the new files", "grab", g.Name, "err", err) - } - if err := q.MarkWantSearched(ctx, g.WantID); err != nil { - im.logger.Warn("import: mark the want searched", "grab", g.Name, "err", err) - } - dest := filepath.Dir(placed[0]) - if e != nil && e.Media() > 1 { - dest = filepath.Dir(dest) - } - reason := fmt.Sprintf("Imported %s into %s. %s", tracks(len(placed)), dest, v.Reason) - if det.Skipped > 0 { - reason += fmt.Sprintf(" %s already in the library left as they were.", tracks(det.Skipped)) - } - if det.Untagged > 0 { - reason += fmt.Sprintf(" %s copied with their own tags: ffmpeg could not rewrite them.", tracks(det.Untagged)) - } - return record(StateImported, reason, StateImported, det, len(placed), dest) -} - -// rehome imports a download that turned out to be another wanted album, -// named by its tags, for that album, when its own grab is not running. -func (im *Importer) rehome(ctx context.Context, q *dbq.Queries, g dbq.Grab, d downloader.Driver, - from Want, files []File, printed bool, record recordFunc) (string, bool) { - group := majority(files, func(f File) string { return f.GroupMBID }) - if group == "" { - return "", false - } - others, err := q.OpenWantsForGroups(ctx, []string{group}) - if err != nil || len(others) == 0 { - return "", false - } - other := others[0] - w, err := im.want(ctx, q, other.ID) - if err != nil { - return "", false - } - editions, err := im.editions(ctx, w.GroupMBID) - if err != nil { - return "", false - } - v := Verify(w, editions, files, printed, false) - if v.Outcome != Accept { - return "", false - } - moved, err := q.RehomeGrab(ctx, dbq.RehomeGrabParams{ID: g.ID, WantID: other.ID}) - if err != nil { - return "", false - } - if err := q.SearchWantAgain(ctx, g.WantID); err != nil { - im.logger.Warn("import: search the first album again", "want", from.Title, "err", err) - } - det := Detail{Verdict: v, RehomedFrom: from.Title} - for _, f := range files { - det.Files = append(det.Files, f.Rel) - } - if v.Edition >= 0 { - det.Edition, det.EditionMBID = describe(editions[v.Edition]), editions[v.Edition].MBID - } - v.Reason = fmt.Sprintf("Grabbed for %s, it is %s, which is wanted too. %s", from.Title, w.Title, v.Reason) - det.Verdict = v - return im.place(ctx, q, moved, d, w, editions, files, v, det, record), true -} - -// refuse blocks the release, asks for the album to be searched again and -// removes the download with its files: it is not the album. -func (im *Importer) refuse(ctx context.Context, q *dbq.Queries, g dbq.Grab, d downloader.Driver, w Want, why string, by pgtype.UUID) { - if err := acquire.NewMemory(im.pool).Block(ctx, dbq.BlockReleaseParams{ - InfoHash: g.InfoHash, Name: g.Name, Reason: acquire.BlockImport, Detail: why, WantID: g.WantID, BlockedBy: by, - }); err != nil { - im.logger.Warn("import: block the release", "grab", g.Name, "err", err) - } - if err := q.SearchWantAgain(ctx, g.WantID); err != nil { - im.logger.Warn("import: search again", "want", w.Title, "err", err) - } - im.removeFromClient(ctx, d, g) -} - -func (im *Importer) removeFromClient(ctx context.Context, d downloader.Driver, g dbq.Grab) { - if d == nil || g.InfoHash == "" { - return - } - if err := d.Delete(ctx, true, g.InfoHash); err != nil { - im.logger.Warn("import: remove the download", "grab", g.Name, "err", err) - } -} - -// Refuse is a person's "refuse" on a download the check held for them, or -// one that failed: it is refused as the check would have. -func (im *Importer) Refuse(ctx context.Context, grabID, by pgtype.UUID) (dbq.Grab, error) { - q := dbq.New(im.pool) - g, err := q.GetGrab(ctx, grabID) - if err != nil { - return dbq.Grab{}, err - } - if g.EndedAt.Valid || (g.ImportState != StateReview && g.ImportState != StateFailed) { - return dbq.Grab{}, ErrNotDecidable - } - var w Want - if g.WantID.Valid { - w, _ = im.want(ctx, q, g.WantID) - } - d, err := im.ClientFor(ctx, g.Client) - if err != nil { - d = nil - } - why := "A person refused it: it is not the album." - im.refuse(ctx, q, g, d, w, why, by) - out, err := q.RecordImport(ctx, dbq.RecordImportParams{ - ID: g.ID, ImportState: StateRefused, ImportReason: why, ImportDetail: g.ImportDetail, - EndReason: StateRefused, - }) - im.Wake() - return out, err -} - -// ErrNotDecidable: the grab is not waiting on a person. -var ErrNotDecidable = errors.New("importer: that download is not waiting on a decision") - -func (im *Importer) want(ctx context.Context, q *dbq.Queries, id pgtype.UUID) (Want, error) { - row, err := q.GetWantForSearch(ctx, id) - if err != nil { - return Want{}, err - } - w := Want{ - GroupMBID: row.ReleaseGroupMbid, ArtistMBID: row.ArtistMbid, Artist: row.ArtistName, Title: row.Title, - Year: yearOf(row.FirstReleaseDate), PrimaryType: row.PrimaryType, SecondaryTypes: row.SecondaryTypes, - } - if row.FulfilledAt.Valid && row.Upgrade != "" && row.AlbumID.Valid { - w.Upgrade, w.AlbumID = row.Upgrade, row.AlbumID - } - return w, nil -} - -func (im *Importer) editions(ctx context.Context, group string) ([]Edition, error) { - if im.Catalogue == nil { - return nil, errors.New("no catalogue") - } - eds, err := im.Catalogue.Releases(ctx, group) - if err != nil { - return nil, err - } - out := make([]Edition, 0, len(eds.Editions)) - for _, e := range eds.Editions { - ed := Edition{MBID: e.Release.Mbid, Title: e.Release.Title, Status: e.Release.Status, - Date: e.Release.ReleaseDate, Country: e.Release.Country} - for _, t := range e.Tracks { - ed.Tracks = append(ed.Tracks, Track{Medium: int(t.MediumPosition), Format: t.MediumFormat, - Position: int(t.Position), Title: t.Title, RecordingMBID: t.RecordingMbid, LengthMs: int(t.LengthMs)}) - } - slices.SortStableFunc(ed.Tracks, func(a, b Track) int { - if a.Medium != b.Medium { - return a.Medium - b.Medium - } - return a.Position - b.Position - }) - out = append(out, ed) - } - return out, nil -} - -// root is the library folder new music is filed into. -func (im *Importer) root(ctx context.Context, q *dbq.Queries) (string, error) { - roots := im.Roots() - if len(roots) == 0 { - return "", errors.New("there is no library folder to file new music into; add one in Settings → Library") - } - s, err := q.GetAcquisitionSettings(ctx) - if err == nil && s.ImportRoot != "" && slices.Contains(roots, s.ImportRoot) { - return s.ImportRoot, nil - } - return roots[0], nil -} - -// held reads which of the planned tracks the library already has: by -// recording, and by disc and track of an album of the same group. -func (im *Importer) held(ctx context.Context, q *dbq.Queries, w Want, plan []Placement) (map[string]bool, map[[2]int]bool, error) { - var recs []string - for _, pl := range plan { - if pl.Recording != "" { - recs = append(recs, pl.Recording) - } - } - rec := map[string]bool{} - if len(recs) > 0 { - got, err := q.HeldRecordings(ctx, recs) - if err != nil { - return nil, nil, err - } - for _, r := range got { - rec[r] = true - } - } - pos := map[[2]int]bool{} - got, err := q.HeldPositions(ctx, &w.GroupMBID) - if err != nil { - return nil, nil, err - } - for _, p := range got { - pos[[2]int{int(p.Disc), int(p.Track)}] = true - } - return rec, pos, nil -} - -func yearOf(date string) int { - if len(date) < 4 { - return 0 - } - y, err := strconv.Atoi(date[:4]) - if err != nil { - return 0 - } - return y -} - -func tracks(n int) string { - if n == 1 { - return "1 track" - } - return strconv.Itoa(n) + " tracks" -} diff --git a/internal/importer/importer_test.go b/internal/importer/importer_test.go deleted file mode 100644 index dd442f1e..00000000 --- a/internal/importer/importer_test.go +++ /dev/null @@ -1,268 +0,0 @@ -package importer - -import ( - "context" - "io" - "log/slog" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/catalogue" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" -) - -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - -const hash = "0123456789abcdef0123456789abcdef01234567" - -// fakeClient is a download client holding one finished torrent. -type fakeClient struct { - downloader.Driver - content string - deleted []string -} - -func (c *fakeClient) Torrents(_ context.Context, _ ...string) ([]downloader.Torrent, error) { - return []downloader.Torrent{{Hash: hash, Name: "Daft Punk - RAM [FLAC]", Progress: 1, State: "uploading", - ContentPath: c.content}}, nil -} - -func (c *fakeClient) Delete(_ context.Context, _ bool, hashes ...string) error { - c.deleted = append(c.deleted, hashes...) - return nil -} - -// fakeCatalogue knows RAM as one three-track edition. -type fakeCatalogue struct{} - -func (fakeCatalogue) Releases(_ context.Context, _ string) (catalogue.Editions, error) { - return catalogue.Editions{Editions: []catalogue.Edition{{ - Release: dbq.MbRelease{Mbid: "rel-ram", Title: "Random Access Memories", Status: "Official", ReleaseDate: "2013-05-17"}, - Tracks: []dbq.MbReleaseTrack{ - {MediumPosition: 1, MediumFormat: "CD", Position: 1, Title: "Give Life Back to Music", RecordingMbid: "rec-01"}, - {MediumPosition: 1, MediumFormat: "CD", Position: 2, Title: "The Game of Love", RecordingMbid: "rec-02"}, - {MediumPosition: 1, MediumFormat: "CD", Position: 3, Title: "Giorgio by Moroder", RecordingMbid: "rec-03"}, - }, - }}}, nil -} - -// fakePrinter names each file's recording by its file name: 01.flac is -// rec-01, unless wrong is set. -type fakePrinter struct{ wrong bool } - -func (p fakePrinter) Recordings(_ context.Context, path string) ([]string, error) { - if p.wrong { - return []string{"rec-other"}, nil - } - return []string{"rec-" + strings.TrimSuffix(filepath.Base(path), ".flac")}, nil -} - -type fakeScanner struct{ scanned []string } - -func (s *fakeScanner) ScanFiles(_ context.Context, paths []string) ([]pgtype.UUID, error) { - s.scanned = append(s.scanned, paths...) - return nil, nil -} - -type stack struct { - pool *pgxpool.Pool - q *dbq.Queries - im *Importer - client *fakeClient - scanner *fakeScanner - library string - want dbq.Want - grab dbq.Grab -} - -// newStack wants RAM, has a finished download of it waiting in a fake -// client, and an importer filing into a temp library. -func newStack(t *testing.T, printer Printer) *stack { - t.Helper() - ctx := context.Background() - pool := newPool(t) - q := dbq.New(pool) - content := t.TempDir() - for _, n := range []string{"01", "02", "03"} { - if err := os.WriteFile(filepath.Join(content, n+".flac"), []byte("not really flac "+n), 0o644); err != nil { - t.Fatal(err) - } - } - w, err := wanted.WantWith(ctx, q, wanted.WantParams{GroupMBID: "rg-ram", ArtistMBID: "mb-dp", ArtistName: "Daft Punk", - Title: "Random Access Memories", PrimaryType: "Album", FirstReleaseDate: "2013-05-17", Reason: wanted.ReasonRequest}) - if err != nil { - t.Fatal(err) - } - g, err := acquire.NewMemory(pool).Grabbed(ctx, dbq.InsertGrabParams{WantID: w.ID, InfoHash: hash, - Name: "Daft Punk - RAM [FLAC]", Key: hash, Client: "qbittorrent", SavePath: content, Origin: acquire.OriginSchedule}, - pgtype.UUID{}, "") - if err != nil { - t.Fatal(err) - } - s := &stack{pool: pool, q: q, client: &fakeClient{content: content}, scanner: &fakeScanner{}, - library: t.TempDir(), want: w, grab: g} - s.im = New(pool, s.scanner, fakeCatalogue{}, printer, func() []string { return []string{s.library} }, slog.New(slog.NewTextHandler(io.Discard, nil))) - s.im.ClientFor = func(context.Context, string) (downloader.Driver, error) { return s.client, nil } - return s -} - -func (s *stack) grabNow(t *testing.T) dbq.Grab { - t.Helper() - g, err := s.q.GetGrab(context.Background(), s.grab.ID) - if err != nil { - t.Fatal(err) - } - return g -} - -func TestImport_AFinishedDownloadOfTheAlbumIsFiled_Integration(t *testing.T) { - s := newStack(t, fakePrinter{}) - rep := s.im.Pass(context.Background()) - if rep.Imported != 1 { - t.Fatalf("pass = %+v", rep) - } - g := s.grabNow(t) - if g.ImportState != StateImported || g.EndReason != StateImported || !g.EndedAt.Valid || g.ImportedFiles != 3 { - t.Fatalf("grab = %s %s ended=%v files=%d: %s", g.ImportState, g.EndReason, g.EndedAt.Valid, g.ImportedFiles, g.ImportReason) - } - dir := filepath.Join(s.library, "Daft Punk", "Random Access Memories (2013)") - if g.Destination != dir { - t.Errorf("destination %q", g.Destination) - } - got, err := os.ReadFile(filepath.Join(dir, "Daft Punk - Random Access Memories - 02 - The Game of Love.flac")) - if err != nil || string(got) != "not really flac 02" { - t.Errorf("filed copy: %q %v", got, err) - } - if _, err := os.Stat(filepath.Join(s.client.content, "02.flac")); err != nil { - t.Errorf("the download's own file went: %v", err) - } - if len(s.scanner.scanned) != 3 || len(s.client.deleted) != 0 { - t.Errorf("scanned %v, deleted %v", s.scanner.scanned, s.client.deleted) - } - w, _ := s.q.GetWantByReleaseGroup(context.Background(), "rg-ram") - if !w.SearchedAt.Valid { - t.Error("an imported want is due for search again") - } - if s.im.Pass(context.Background()).Imported != 0 { - t.Error("imported twice") - } -} - -func TestImport_TheWrongAlbumIsRefusedBlockedAndSearchedAgain_Integration(t *testing.T) { - s := newStack(t, fakePrinter{wrong: true}) - ctx := context.Background() - if err := s.q.MarkWantSearched(ctx, s.want.ID); err != nil { - t.Fatal(err) - } - if rep := s.im.Pass(ctx); rep.Refused != 1 { - t.Fatalf("pass = %+v", rep) - } - g := s.grabNow(t) - if g.ImportState != StateRefused || g.EndReason != StateRefused || !strings.Contains(g.ImportReason, "recordings") { - t.Fatalf("grab = %s %s: %s", g.ImportState, g.EndReason, g.ImportReason) - } - blocks, err := s.q.ListReleaseBlocks(ctx) - if err != nil || len(blocks) != 1 || blocks[0].InfoHash != hash || blocks[0].Reason != acquire.BlockImport { - t.Errorf("blocks = %+v %v", blocks, err) - } - if len(s.client.deleted) != 1 { - t.Errorf("the refused download was not removed: %v", s.client.deleted) - } - w, _ := s.q.GetWantByReleaseGroup(ctx, "rg-ram") - if w.SearchedAt.Valid { - t.Error("a refused want is not due for search") - } - entries, _ := os.ReadDir(s.library) - if len(entries) != 0 { - t.Errorf("the library got %d entries", len(entries)) - } -} - -func TestImport_ADoubtfulDownloadWaitsForAPersonThenImportsAnyway_Integration(t *testing.T) { - s := newStack(t, nil) // no AcoustID; untagged files: nothing but lengths - ctx := context.Background() - if rep := s.im.Pass(ctx); rep.Review != 1 { - t.Fatalf("pass = %+v", rep) - } - g := s.grabNow(t) - if g.ImportState != StateReview || g.EndedAt.Valid || !strings.Contains(g.ImportReason, "A person decides") { - t.Fatalf("grab = %s ended=%v: %s", g.ImportState, g.EndedAt.Valid, g.ImportReason) - } - if rep := s.im.Pass(ctx); rep.Review+rep.Imported != 0 { - t.Errorf("a held download was looked at again: %+v", rep) - } - if _, err := s.q.ForceGrabImport(ctx, g.ID); err != nil { - t.Fatal(err) - } - if rep := s.im.Pass(ctx); rep.Imported != 1 { - t.Fatalf("after import anyway: %+v", rep) - } - if g := s.grabNow(t); g.ImportState != StateImported || !strings.Contains(g.ImportReason, "anyway") { - t.Errorf("grab = %s: %s", g.ImportState, g.ImportReason) - } -} - -func TestImport_APersonRefusesADoubtfulDownload_Integration(t *testing.T) { - s := newStack(t, nil) - ctx := context.Background() - s.im.Pass(ctx) - g, err := s.im.Refuse(ctx, s.grab.ID, pgtype.UUID{}) - if err != nil { - t.Fatal(err) - } - if g.ImportState != StateRefused || !g.EndedAt.Valid || len(s.client.deleted) != 1 { - t.Errorf("grab = %s ended=%v deleted=%v", g.ImportState, g.EndedAt.Valid, s.client.deleted) - } - if _, err := s.im.Refuse(ctx, s.grab.ID, pgtype.UUID{}); err == nil { - t.Error("refused twice") - } -} - -func TestImport_AnUnfinishedDownloadIsOnlyWatched_Integration(t *testing.T) { - s := newStack(t, fakePrinter{}) - s.im.ClientFor = func(context.Context, string) (downloader.Driver, error) { return &halfClient{s.client}, nil } - if rep := s.im.Pass(context.Background()); rep.Downloading != 1 { - t.Fatalf("pass = %+v", rep) - } - g := s.grabNow(t) - if g.ImportState != StateDownloading || g.Progress < 0.49 || g.Progress > 0.51 { - t.Errorf("grab = %s %.2f", g.ImportState, g.Progress) - } -} - -type halfClient struct{ *fakeClient } - -func (c *halfClient) Torrents(ctx context.Context, h ...string) ([]downloader.Torrent, error) { - ts, _ := c.fakeClient.Torrents(ctx, h...) - ts[0].Progress, ts[0].State = 0.5, "downloading" - return ts, nil -} diff --git a/internal/importer/inspect.go b/internal/importer/inspect.go deleted file mode 100644 index e727b4cb..00000000 --- a/internal/importer/inspect.go +++ /dev/null @@ -1,176 +0,0 @@ -package importer - -import ( - "context" - "errors" - "io/fs" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/dhowden/tag" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acoustid" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" -) - -// Printer says which MusicBrainz recordings a file's audio is. ErrNoPrints: -// it cannot say for any file (AcoustID is not set up, or not answering), so -// the check rests on lengths and tags. -type Printer interface { - Recordings(ctx context.Context, path string) ([]string, error) -} - -// ErrNoPrints: fingerprints are not available for this download. -var ErrNoPrints = errors.New("importer: fingerprints are not available") - -// AcoustIDPrinter fingerprints with fpcalc and asks AcoustID, under the -// AcoustID settings (key, minimum score). Each call reads the settings, so -// a change takes effect on the next file. -type AcoustIDPrinter struct { - Settings interface { - Get() library.AcoustIDSettings - } - Client *acoustid.Client -} - -// Recordings is every recording AcoustID gives at or above the minimum score: -// one audio can be several recordings (the album track and the single). -func (p *AcoustIDPrinter) Recordings(ctx context.Context, path string) ([]string, error) { - s := p.Settings.Get() - if !s.Ready() || p.Client == nil { - return nil, ErrNoPrints - } - fp, dur, err := library.LookupFingerprint(ctx, path) - if err != nil { - if library.IsInconclusive(err) { - return nil, ErrNoPrints - } - return nil, nil // fpcalc rejected the file: no evidence either way - } - cands, err := p.Client.Lookup(ctx, s.APIKey, fp, dur) - switch { - case errors.Is(err, acoustid.ErrInvalidKey), errors.Is(err, acoustid.ErrUnavailable): - return nil, ErrNoPrints - case err != nil: - return nil, nil - } - var out []string - for _, c := range cands { - if c.Score >= float64(s.MinScore) && c.ID != "" { - out = append(out, c.ID) - } - } - return out, nil -} - -// formatRank picks which format's files are the album when a download holds -// more than one (a FLAC folder and an MP3 folder): the most files, then the -// better format. -var formatRank = map[string]int{".flac": 6, ".wav": 5, ".m4a": 4, ".opus": 3, ".ogg": 2, ".mp3": 1, ".aac": 0} - -// audioFiles lists the audio files under root (a folder, or one file), in -// the one format that is the album. Dot-named files and folders are skipped: -// they are partial downloads, OS litter or Minstrel's own temp files. -func audioFiles(root string) ([]string, error) { - info, err := os.Stat(root) - if err != nil { - return nil, err - } - if !info.IsDir() { - if library.IsAudioFile(root) { - return []string{root}, nil - } - return nil, nil - } - byExt := map[string][]string{} - err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - if strings.HasPrefix(d.Name(), ".") && path != root { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - if !d.IsDir() && library.IsAudioFile(path) { - ext := strings.ToLower(filepath.Ext(path)) - byExt[ext] = append(byExt[ext], path) - } - return nil - }) - if err != nil { - return nil, err - } - best := "" - for ext, paths := range byExt { - if best == "" || len(paths) > len(byExt[best]) || - (len(paths) == len(byExt[best]) && formatRank[ext] > formatRank[best]) { - best = ext - } - } - out := byExt[best] - sort.Strings(out) - return out, nil -} - -// readFile reads what one file's tags and length say. A file whose tags -// cannot be read still counts, by its length and name. -func readFile(ctx context.Context, root, path string) File { - f := File{Path: path, Rel: rel(root, path), Video: len(library.SourceMarkersFor(path)) > 0} - if ms, err := library.ProbeDurationMs(ctx, path); err == nil { - f.LengthMs = int(ms) - } - h, err := os.Open(path) - if err != nil { - return f - } - defer func() { _ = h.Close() }() - m, err := tag.ReadFrom(h) - if err != nil { - return f - } - f.Title, f.Artist, f.AlbumArtist, f.Album = m.Title(), m.Artist(), m.AlbumArtist(), m.Album() - f.Track, f.Disc = library.ReadTrackAndDisc(m) - ids := library.ReadTagMBIDs(m) - f.GroupMBID, f.ReleaseMBID, f.RecordingMBID = ids.ReleaseGroup, ids.Release, ids.Recording - return f -} - -func rel(root, path string) string { - if r, err := filepath.Rel(root, path); err == nil && r != "." { - return r - } - return filepath.Base(path) -} - -// inspect reads every audio file under root and asks the printer about each. -// fingerprinted reports whether the printer answered at all. -func inspect(ctx context.Context, root string, p Printer) (files []File, fingerprinted bool, err error) { - paths, err := audioFiles(root) - if err != nil { - return nil, false, err - } - fingerprinted = p != nil - for _, path := range paths { - if ctx.Err() != nil { - return nil, false, ctx.Err() - } - f := readFile(ctx, root, path) - if fingerprinted && len(paths) <= maxFiles { - recs, err := p.Recordings(ctx, path) - if errors.Is(err, ErrNoPrints) { - fingerprinted = false - for i := range files { - files[i].Recordings = nil - } - } else { - f.Recordings = recs - } - } - files = append(files, f) - } - return files, fingerprinted, nil -} diff --git a/internal/importer/name.go b/internal/importer/name.go deleted file mode 100644 index b6a15a5b..00000000 --- a/internal/importer/name.go +++ /dev/null @@ -1,109 +0,0 @@ -package importer - -import ( - "fmt" - "path/filepath" - "strings" - "unicode/utf8" -) - -// Placement is where one file goes and the names written into its tags. -type Placement struct { - File int // index into the files - Dest string // absolute - Title string - Disc int - Discs int - Track int - Tracks int // on its disc - // Recording is the MusicBrainz recording the file was matched to. - Recording string -} - -// Plan names every file's destination under root the way the library is -// conventionally named, so new arrivals sit beside what is there: -// -// {Artist}/{Album} ({Year})/{Artist} - {Album} - {track:00} - {Title}.ext -// -// with a "{Medium Format} {medium:00}" folder between when the edition has -// more than one medium. A file the check paired to a track takes the track's -// name and place; one it did not (an "import anyway" with more files than -// tracks) keeps its own tags. -func Plan(root string, w Want, e *Edition, files []File, pairs []Pair) []Placement { - album := w.Title - if w.Year > 0 { - album = fmt.Sprintf("%s (%d)", w.Title, w.Year) - } - dir := filepath.Join(root, Segment(w.Artist), Segment(album)) - media := 1 - if e != nil { - media = max(e.Media(), 1) - } - perDisc := map[int]int{} - if e != nil { - for _, t := range e.Tracks { - perDisc[t.Medium]++ - } - } - paired := map[int]Pair{} - for _, p := range pairs { - paired[p.File] = p - } - - out := make([]Placement, 0, len(files)) - for i, f := range files { - pl := Placement{File: i, Title: f.Title, Disc: max(f.Disc, 1), Track: f.Track, Discs: media} - format := "" - if p, ok := paired[i]; ok && e != nil { - t := e.Tracks[p.Track] - pl.Title, pl.Disc, pl.Track, pl.Recording, format = t.Title, max(t.Medium, 1), t.Position, t.RecordingMBID, t.Format - pl.Tracks = perDisc[t.Medium] - } - if pl.Title == "" { - pl.Title = strings.TrimSuffix(filepath.Base(f.Path), filepath.Ext(f.Path)) - } - d := dir - if media > 1 { - if format == "" { - format = "Disc" - } - d = filepath.Join(dir, Segment(fmt.Sprintf("%s %02d", format, pl.Disc))) - } - name := fmt.Sprintf("%s - %s - %02d - %s", w.Artist, w.Title, pl.Track, pl.Title) - pl.Dest = filepath.Join(d, Segment(name)+strings.ToLower(filepath.Ext(f.Path))) - out = append(out, pl) - } - return out -} - -// segmentMax keeps a folder or file name inside the 255 bytes most -// filesystems allow, with room for an extension and a temp prefix. -const segmentMax = 200 - -var illegal = strings.NewReplacer( - `\`, "+", "/", "+", "<", "", ">", "", "?", "!", "*", "-", "|", "", `"`, "", - // The "smart" colon: "Title: Subtitle" reads "Title - Subtitle". - ": ", " - ", ":", "-", -) - -// Segment makes a name safe as one path segment, the way the *arr programs -// clean file names: their illegal-character mapping, no leading or trailing -// spaces or dots, at most segmentMax bytes, never "" or "..". -func Segment(s string) string { - s = illegal.Replace(s) - s = strings.Map(func(r rune) rune { - if r < 0x20 || r == 0x7f { - return -1 - } - return r - }, s) - s = strings.Trim(s, " .") - for len(s) > segmentMax { - _, size := utf8.DecodeLastRuneInString(s) - s = strings.TrimRight(s[:len(s)-size], " .") - } - if s == "" { - return "_" - } - return s -} diff --git a/internal/importer/place.go b/internal/importer/place.go deleted file mode 100644 index 090091ea..00000000 --- a/internal/importer/place.go +++ /dev/null @@ -1,210 +0,0 @@ -package importer - -import ( - "context" - "crypto/rand" - "encoding/hex" - "errors" - "fmt" - "io" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "time" -) - -// ErrOccupied: the destination already has a file. Nothing is overwritten. -var ErrOccupied = errors.New("importer: destination already holds a file") - -// tagTimeout bounds one ffmpeg run. A remux copies the audio untouched, so a -// whole album track takes well under a second on local disk; two minutes is -// for a slow network mount, not for ffmpeg. -const tagTimeout = 2 * time.Minute - -// Tags are the names written into an imported file. Empty values are left -// out; the file's own tags stay for everything not named here. -type Tags struct { - Title, Artist, Album, AlbumArtist string - Year int - Disc, Discs, Track, Tracks int - // MusicBrainz ids, written the way Picard writes them. - ReleaseMBID, GroupMBID, RecordingMBID, ArtistMBID string -} - -// args turns the tags into ffmpeg -metadata pairs for a file of this -// extension. Vorbis comments (FLAC, Ogg, Opus) take Picard's key names; -// ID3 takes Picard's TXXX descriptions, which ffmpeg writes for any key it -// has no frame for. MP4's freeform atoms ffmpeg cannot write, so an M4A -// gets the plain names only. -// -// A Vorbis track or disc number is the number alone, its count in -// TRACKTOTAL and DISCTOTAL, as Picard writes them: dhowden/tag reads a -// TRACKNUMBER of "3/20" as 0, which would lose the album's order. ID3 and MP4 -// take "3/20", which their readers parse. -func (t Tags) args(ext string) []string { - vorbis := ext == ".flac" || ext == ".ogg" || ext == ".opus" - track, disc := ofN(t.Track, t.Tracks), ofN(t.Disc, t.Discs) - if vorbis { - track, disc = ofN(t.Track, 0), ofN(t.Disc, 0) - } - kv := [][2]string{ - {"title", t.Title}, {"artist", t.Artist}, {"album", t.Album}, {"album_artist", t.AlbumArtist}, - {"track", track}, {"disc", disc}, - } - if t.Year > 0 { - kv = append(kv, [2]string{"date", strconv.Itoa(t.Year)}) - } - switch ext { - case ".flac", ".ogg", ".opus": - if t.Track > 0 && t.Tracks > 0 { - kv = append(kv, [2]string{"TRACKTOTAL", strconv.Itoa(t.Tracks)}) - } - if t.Disc > 0 && t.Discs > 0 { - kv = append(kv, [2]string{"DISCTOTAL", strconv.Itoa(t.Discs)}) - } - kv = append(kv, - [2]string{"MUSICBRAINZ_ALBUMID", t.ReleaseMBID}, - [2]string{"MUSICBRAINZ_RELEASEGROUPID", t.GroupMBID}, - [2]string{"MUSICBRAINZ_TRACKID", t.RecordingMBID}, - [2]string{"MUSICBRAINZ_ARTISTID", t.ArtistMBID}, - [2]string{"MUSICBRAINZ_ALBUMARTISTID", t.ArtistMBID}) - case ".mp3": - kv = append(kv, - [2]string{"MusicBrainz Album Id", t.ReleaseMBID}, - [2]string{"MusicBrainz Release Group Id", t.GroupMBID}, - [2]string{"MusicBrainz Track Id", t.RecordingMBID}, - [2]string{"MusicBrainz Artist Id", t.ArtistMBID}, - [2]string{"MusicBrainz Album Artist Id", t.ArtistMBID}) - } - var out []string - for _, p := range kv { - if p[1] != "" { - out = append(out, "-metadata", p[0]+"="+p[1]) - } - } - return out -} - -func ofN(n, of int) string { - switch { - case n <= 0: - return "" - case of > 0: - return fmt.Sprintf("%d/%d", n, of) - } - return strconv.Itoa(n) -} - -// taggable: the formats ffmpeg can rewrite tags in by remuxing. -var taggable = map[string]bool{".flac": true, ".ogg": true, ".opus": true, ".mp3": true, ".m4a": true} - -// Place copies src to dst with tags written, leaving src as it was (the -// download keeps seeding). The copy is written to a dot-named temp file -// beside dst, which the scanner skips, and renamed into place, so the -// library never sees half a file. Tags are written by an ffmpeg remux that -// copies the audio untouched; when ffmpeg cannot (it is missing, or the -// container will not take the file's streams) the file is copied as it is -// and tagged reports false. An existing dst is never overwritten. -func Place(ctx context.Context, src, dst string, t Tags) (tagged bool, err error) { - return placeFile(ctx, src, dst, t, false) -} - -// Overwrite is Place onto a file an upgrade replaces: the new copy -// takes the old one's path in one rename, so the library never sees the -// path empty, and the track row at that path, history and all, carries on -// with the new file. -func Overwrite(ctx context.Context, src, dst string, t Tags) (tagged bool, err error) { - return placeFile(ctx, src, dst, t, true) -} - -func placeFile(ctx context.Context, src, dst string, t Tags, overwrite bool) (tagged bool, err error) { - if _, err := os.Lstat(dst); err == nil && !overwrite { - return false, fmt.Errorf("%w: %s", ErrOccupied, dst) - } - dir := filepath.Dir(dst) - if err := os.MkdirAll(dir, 0o755); err != nil { - return false, fmt.Errorf("make %s: %w", dir, err) - } - ext := strings.ToLower(filepath.Ext(dst)) - tmp := filepath.Join(dir, ".minstrel-import-"+randomHex()+ext) - defer func() { _ = os.Remove(tmp) }() // gone already once renamed - - if taggable[ext] { - tagged = remux(ctx, src, tmp, t.args(ext)) == nil - } - if !tagged { - if err := copyFile(src, tmp); err != nil { - return false, err - } - } - if err := os.Chmod(tmp, 0o644); err != nil { - return false, fmt.Errorf("chmod %s: %w", tmp, err) - } - if _, err := os.Lstat(dst); err == nil && !overwrite { - return false, fmt.Errorf("%w: %s", ErrOccupied, dst) - } - if err := os.Rename(tmp, dst); err != nil { - return false, fmt.Errorf("move into place %s: %w", dst, err) - } - return tagged, nil -} - -// remux writes src to dst through ffmpeg with every stream copied as it is -// (the cover art too) and the tags set. Its output is checked against the -// source's size: a remux shifts container bytes, never the audio, so a file -// much smaller than its source lost something on the way. -func remux(ctx context.Context, src, dst string, meta []string) error { - ctx, cancel := context.WithTimeout(ctx, tagTimeout) - defer cancel() - args := append([]string{"-nostdin", "-v", "error", "-y", "-i", src, - "-map", "0", "-c", "copy", "-map_metadata", "0"}, meta...) - args = append(args, dst) - cmd := exec.CommandContext(ctx, "ffmpeg", args...) - if out, err := cmd.CombinedOutput(); err != nil { - _ = os.Remove(dst) - return fmt.Errorf("ffmpeg: %w: %s", err, strings.TrimSpace(string(out))) - } - si, err := os.Stat(src) - if err != nil { - return err - } - di, err := os.Stat(dst) - if err != nil { - return err - } - if di.Size() < si.Size()/2 { - _ = os.Remove(dst) - return fmt.Errorf("ffmpeg wrote %d bytes from %d", di.Size(), si.Size()) - } - return nil -} - -// copyFile copies src to dst byte for byte and syncs it. -func copyFile(src, dst string) error { - in, err := os.Open(src) - if err != nil { - return err - } - defer func() { _ = in.Close() }() - out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) - if err != nil { - return err - } - if _, err := io.Copy(out, in); err != nil { - _ = out.Close() - return fmt.Errorf("copy %s: %w", src, err) - } - if err := out.Sync(); err != nil { - _ = out.Close() - return err - } - return out.Close() -} - -func randomHex() string { - b := make([]byte, 6) - _, _ = rand.Read(b) - return hex.EncodeToString(b) -} diff --git a/internal/importer/upgrade.go b/internal/importer/upgrade.go deleted file mode 100644 index d40f9c08..00000000 --- a/internal/importer/upgrade.go +++ /dev/null @@ -1,304 +0,0 @@ -package importer - -import ( - "context" - "errors" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/library" - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -// Importing an upgrade: a better copy of an album the library -// holds. Each file is matched to the track it would replace, by recording -// and then by disc and track. It replaces that track when the track is a -// video rip or the new file is a better tier; otherwise the old track stays. -// A file with no track to replace fills a gap, as any import does. -// -// The new copy is filed before the old one goes. On the old file's own path -// it takes the path in one rename and the row carries on; at a new path it -// is scanned in as a track of its own and the old track is folded into it -// (library.ReplaceTrack), so likes, plays and playlist entries carry over. - -// OldTrack is a library track an upgrade may replace. -type OldTrack struct { - ID pgtype.UUID - Path string - Recording string - Disc, Track int - Format string - Bytes int64 - Ms int64 - Rip bool -} - -// Tier is the old track's tier, estimated as the upgrade check estimates -// an album's; ok is false for a format the ladder cannot place. -func (o OldTrack) Tier() (release.Tier, bool) { - return release.TierOfFile(o.Format, release.FileKbps(o.Bytes, o.Ms)) -} - -// What an upgrade does with one placement. -const ( - stepPlace = "place" // no track to replace: fills a gap - stepReplace = "replace" // replaces Old from a new path - stepOverwrite = "overwrite" // replaces Old on its own path - stepKeep = "keep" // Old is as good: left as it is -) - -type upgradeStep struct { - Placement int - Action string - Old int // index into olds, or -1 -} - -// planUpgrade matches each placement to the track it would replace and -// decides what to do with it. newTiers is each placement's tier. -func planUpgrade(plan []Placement, newTiers []release.Tier, olds []OldTrack) []upgradeStep { - used := make([]bool, len(olds)) - match := make([]int, len(plan)) - for i := range match { - match[i] = -1 - } - for i, pl := range plan { - if pl.Recording == "" { - continue - } - for j, o := range olds { - if !used[j] && o.Recording == pl.Recording { - match[i], used[j] = j, true - break - } - } - } - for i, pl := range plan { - if match[i] >= 0 || pl.Track <= 0 { - continue - } - for j, o := range olds { - if !used[j] && o.Track == pl.Track && max(o.Disc, 1) == max(pl.Disc, 1) { - match[i], used[j] = j, true - break - } - } - } - steps := make([]upgradeStep, len(plan)) - for i, pl := range plan { - j := match[i] - steps[i] = upgradeStep{Placement: i, Old: j, Action: stepPlace} - if j < 0 { - continue - } - o := olds[j] - oldTier, _ := o.Tier() - better := release.Rank(newTiers[i]) > release.Rank(oldTier) - switch { - case !o.Rip && !better: - steps[i].Action = stepKeep - case filepath.Clean(pl.Dest) == filepath.Clean(o.Path): - steps[i].Action = stepOverwrite - default: - steps[i].Action = stepReplace - } - } - return steps -} - -// fileTier estimates a downloaded file's tier from its size and length, the -// way the library's are estimated, so the two compare like for like. A file -// that cannot be measured takes the release's tier. -func fileTier(f File, fallback release.Tier) release.Tier { - if info, err := os.Stat(f.Path); err == nil && f.LengthMs > 0 { - if t, ok := release.TierOfFile(filepath.Ext(f.Path), release.FileKbps(info.Size(), int64(f.LengthMs))); ok { - return t - } - } - return fallback -} - -func oldTracks(rows []dbq.ListUpgradeTracksRow) []OldTrack { - out := make([]OldTrack, 0, len(rows)) - for _, r := range rows { - o := OldTrack{ID: r.ID, Path: r.FilePath, Disc: int(r.Disc), Format: r.FileFormat, - Bytes: r.FileSize, Ms: int64(r.DurationMs), Rip: r.SourceVerdict != nil && *r.SourceVerdict == "suspect"} - if r.Mbid != nil { - o.Recording = *r.Mbid - } - if r.TrackNumber != nil { - o.Track = int(*r.TrackNumber) - } - out = append(out, o) - } - return out -} - -// placeUpgrade files an accepted upgrade, replacing the tracks it betters. -func (im *Importer) placeUpgrade(ctx context.Context, q *dbq.Queries, g dbq.Grab, d downloader.Driver, w Want, - e *Edition, files []File, plan []Placement, v Verdict, det Detail, record recordFunc) string { - rows, err := q.ListUpgradeTracks(ctx, w.AlbumID) - if err != nil { - return record(StateWaiting, "Couldn't read the album's tracks: "+err.Error(), "", det, 0, "") - } - olds := oldTracks(rows) - grabTier := release.Tier(g.Quality) - newTiers := make([]release.Tier, len(plan)) - for i, pl := range plan { - newTiers[i] = fileTier(files[pl.File], grabTier) - } - steps := planUpgrade(plan, newTiers, olds) - heldRec, heldPos, err := im.held(ctx, q, w, plan) - if err != nil { - return record(StateWaiting, "Couldn't read what the library holds: "+err.Error(), "", det, 0, "") - } - - type swap struct { - old OldTrack - dest string - } - var ( - placed []string // every file written, for the scan - swaps []swap - inPlace []OldTrack - failed []string - ) - for _, st := range steps { - pl := plan[st.Placement] - if st.Action == stepKeep { - det.Skipped++ - continue - } - if st.Action == stepPlace && ((pl.Recording != "" && heldRec[pl.Recording]) || heldPos[[2]int{pl.Disc, pl.Track}]) { - det.Skipped++ - continue - } - tags := Tags{Title: pl.Title, Artist: w.Artist, Album: w.Title, AlbumArtist: w.Artist, Year: w.Year, - Disc: pl.Disc, Discs: pl.Discs, Track: pl.Track, Tracks: pl.Tracks, - GroupMBID: w.GroupMBID, RecordingMBID: pl.Recording, ArtistMBID: w.ArtistMBID} - if e != nil { - tags.ReleaseMBID = e.MBID - } - src := files[pl.File].Path - var tagged bool - if st.Action == stepOverwrite { - tagged, err = Overwrite(ctx, src, pl.Dest, tags) - } else { - tagged, err = Place(ctx, src, pl.Dest, tags) - } - switch { - case errors.Is(err, ErrOccupied): - det.Skipped++ - continue - case err != nil: - // Each replacement stands alone: the old track stays where a - // copy failed, and the rest go ahead. - failed = append(failed, pl.Title) - im.logger.Warn("import: copy an upgrade into the library", "grab", g.Name, "dest", pl.Dest, "err", err) - continue - } - placed = append(placed, pl.Dest) - if !tagged { - det.Untagged++ - } - switch st.Action { - case stepOverwrite: - inPlace = append(inPlace, olds[st.Old]) - case stepReplace: - swaps = append(swaps, swap{old: olds[st.Old], dest: pl.Dest}) - } - } - det.Placed = len(placed) - - if len(placed) == 0 { - why := fmt.Sprintf("Nothing in it is better than the copy of %s you have, so nothing was imported.", w.Title) - if len(failed) > 0 { - return record(StateFailed, fmt.Sprintf("Copying into the library failed for %s.", strings.Join(failed, ", ")), - "", det, 0, "") - } - // Set aside, so the weekly search doesn't take it again. - if err := acquire.NewMemory(im.pool).Block(ctx, dbq.BlockReleaseParams{ - InfoHash: g.InfoHash, Name: g.Name, Reason: acquire.BlockImport, Detail: why, WantID: g.WantID, - }); err != nil { - im.logger.Warn("import: set the release aside", "grab", g.Name, "err", err) - } - if err := q.MarkWantSearched(ctx, g.WantID); err != nil { - im.logger.Warn("import: mark the want searched", "grab", g.Name, "err", err) - } - im.removeFromClient(ctx, d, g) - return record(StateHeld, why, StateHeld, det, 0, "") - } - - if _, err := im.Scanner.ScanFiles(ctx, placed); err != nil { - im.logger.Warn("import: scan the new files", "grab", g.Name, "err", err) - } - for _, o := range inPlace { - if o.Rip { - if err := q.ClearTrackSourceVerdict(ctx, o.ID); err != nil { - im.logger.Warn("import: release a replaced rip", "path", o.Path, "err", err) - } - } - } - replaced, kept := len(inPlace), 0 - for _, s := range swaps { - nt, err := q.GetTrackByPath(ctx, s.dest) - if err != nil { - kept++ - im.logger.Warn("import: find the new track", "path", s.dest, "err", err) - continue - } - moved, err := library.ReplaceTrack(ctx, im.pool, im.logger, im.DataDir, s.old.ID, nt.ID) - if err != nil { - // The old file stays; the duplicate sweep finds the two copies. - kept++ - im.logger.Warn("import: replace the old track", "old", s.old.Path, "new", s.dest, "err", err) - continue - } - replaced++ - im.logger.Info("import: replaced a track with a better copy", "old", s.old.Path, "new", s.dest, - "play_events", moved.PlayEvents, "likes", moved.Likes, "playlist_entries", moved.PlaylistEntries) - } - - // The want holds the album the new tracks are in, once the old album row - // has none left. - var album pgtype.UUID - if left, err := q.ListUpgradeTracks(ctx, w.AlbumID); err == nil && len(left) == 0 { - if nt, err := q.GetTrackByPath(ctx, placed[0]); err == nil { - album = nt.AlbumID - } - } - if err := q.FinishUpgrade(ctx, dbq.FinishUpgradeParams{ID: g.WantID, AlbumID: album}); err != nil { - im.logger.Warn("import: finish the upgrade", "grab", g.Name, "err", err) - } - if err := q.MarkWantSearched(ctx, g.WantID); err != nil { - im.logger.Warn("import: mark the want searched", "grab", g.Name, "err", err) - } - - dest := filepath.Dir(placed[0]) - if e != nil && e.Media() > 1 { - dest = filepath.Dir(dest) - } - reason := fmt.Sprintf("Replaced %s of %s with a better copy.", tracks(replaced), w.Title) - if added := len(placed) - replaced - kept; added > 0 { - reason += fmt.Sprintf(" Added %s it was missing.", tracks(added)) - } - if det.Skipped > 0 { - reason += fmt.Sprintf(" %s already as good left as they were.", tracks(det.Skipped)) - } - if kept > 0 { - reason += fmt.Sprintf(" %s couldn't be removed, so both copies are in the library.", tracks(kept)) - } - if len(failed) > 0 { - reason += fmt.Sprintf(" Copying failed for %s; those stay as they were.", strings.Join(failed, ", ")) - } - if det.Untagged > 0 { - reason += fmt.Sprintf(" %s copied with their own tags: ffmpeg could not rewrite them.", tracks(det.Untagged)) - } - return record(StateImported, reason+" "+v.Reason, StateImported, det, len(placed), dest) -} diff --git a/internal/importer/upgrade_test.go b/internal/importer/upgrade_test.go deleted file mode 100644 index a415fd45..00000000 --- a/internal/importer/upgrade_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package importer - -import ( - "testing" - - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -func TestPlanUpgrade_ReplacesOnlyWhatItBetters(t *testing.T) { - plan := []Placement{ - {File: 0, Dest: "/music/A/B (2001)/A - B - 01 - One.flac", Disc: 1, Track: 1, Recording: "rec-1"}, - {File: 1, Dest: "/music/A/B (2001)/A - B - 02 - Two.mp3", Disc: 1, Track: 2}, - {File: 2, Dest: "/music/A/B (2001)/A - B - 03 - Three.flac", Disc: 1, Track: 3}, - {File: 3, Dest: "/music/A/B (2001)/A - B - 04 - Four.flac", Disc: 1, Track: 4}, - {File: 4, Dest: "/music/A/B (2001)/A - B - 05 - Five.flac", Disc: 1, Track: 5}, - } - newTiers := []release.Tier{release.TierLossless, release.TierLossyHigh, release.TierLossless, - release.TierLossless, release.TierLossyLow} - olds := []OldTrack{ - // Matched by recording though its number is wrong: a 192 MP3. - {Path: "/music/A/B/01 One.mp3", Recording: "rec-1", Disc: 1, Track: 9, Format: "mp3", Bytes: 4_800_000, Ms: 200_000}, - // Same path as the new file, a 320 MP3: the new 320 is no better. - {Path: "/music/A/B (2001)/A - B - 02 - Two.mp3", Disc: 1, Track: 2, Format: "mp3", Bytes: 8_000_000, Ms: 200_000}, - // Already lossless: kept. - {Path: "/music/A/B/03 Three.flac", Disc: 1, Track: 3, Format: "flac", Bytes: 22_000_000, Ms: 200_000}, - // A video rip, even though lossless: replaced. - {Path: "/music/A/B/04 Four (Official Video).flac", Disc: 0, Track: 4, Format: "flac", Bytes: 22_000_000, Ms: 200_000, Rip: true}, - } - steps := planUpgrade(plan, newTiers, olds) - want := []struct { - action string - old int - }{ - {stepReplace, 0}, {stepKeep, 1}, {stepKeep, 2}, {stepReplace, 3}, {stepPlace, -1}, - } - for i, w := range want { - if steps[i].Action != w.action || steps[i].Old != w.old { - t.Errorf("placement %d: %s old %d, want %s old %d", i, steps[i].Action, steps[i].Old, w.action, w.old) - } - } -} - -func TestPlanUpgrade_OverwritesAWorseFileOnItsOwnPath(t *testing.T) { - dest := "/music/A/B (2001)/A - B - 01 - One.mp3" - steps := planUpgrade( - []Placement{{File: 0, Dest: dest, Disc: 1, Track: 1}}, - []release.Tier{release.TierLossyHigh}, - []OldTrack{{Path: dest, Disc: 1, Track: 1, Format: "mp3", Bytes: 3_200_000, Ms: 200_000}}, // 128 - ) - if steps[0].Action != stepOverwrite || steps[0].Old != 0 { - t.Errorf("got %+v", steps[0]) - } -} diff --git a/internal/importer/verify.go b/internal/importer/verify.go deleted file mode 100644 index 9181d46c..00000000 --- a/internal/importer/verify.go +++ /dev/null @@ -1,437 +0,0 @@ -// Package importer checks a finished download against the album it was -// grabbed for and files it into the library. Nothing reaches -// the library before the check says the files are the album: a wrong album, -// another version of it, a video rip or an incomplete copy is refused, its -// release is blocked and the album is searched for again. -// -// The files are matched to one of the album's MusicBrainz editions by -// AcoustID fingerprints, track lengths, titles and the tags they carry. -package importer - -import ( - "fmt" - "slices" - "sort" - "strings" - - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/release" -) - -// Outcome is what the check decided. -type Outcome string - -const ( - Accept Outcome = "accept" - // Review: the files may be the album and the evidence cannot say. A - // person decides. - Review Outcome = "review" - Refuse Outcome = "refuse" -) - -// Codes say why, beside the sentence in Verdict.Reason. -const ( - CodeMatched = "matched" - CodeForced = "forced" - CodeNoAudio = "no_audio" - CodeVideo = "video" - CodeWrongAlbum = "wrong_album" - CodeOtherVersion = release.VetoVersion - CodeWrongTitle = release.VetoTitle - CodeIncomplete = "incomplete" - CodeNoEdition = "no_edition" - CodeWeak = "weak" - CodeTooMany = "too_many" -) - -// maxFiles is the most audio files one album is checked for. More is a box -// set or a discography, which is a person's call, not a fingerprint queue. -const maxFiles = 60 - -// File is what one audio file in a download says about itself. -type File struct { - Path string // absolute, as Minstrel sees it - Rel string // under the download, for the person reading the verdict - // Disc and Track are the tags' positions; 0 when untagged. - Disc, Track int - Title string - Artist string - AlbumArtist string - Album string - // MusicBrainz ids from the tags, when a tagger wrote them. - GroupMBID string - ReleaseMBID string - RecordingMBID string - LengthMs int - // Recordings are the MusicBrainz recordings AcoustID says the audio is, - // at or above the configured minimum score. - Recordings []string - // Video: the file name says it is a music video, a lyric video or the - // like (library.SourceMarkersFor). - Video bool -} - -// Track is one track of an edition. -type Track struct { - Medium int - Format string // the medium's: CD, Digital Media, Vinyl - Position int - Title string - RecordingMBID string - LengthMs int -} - -// Edition is one MusicBrainz release of the wanted release group, its -// tracks in medium and position order. -type Edition struct { - MBID string - Title string - Status string - Date string - Country string - Tracks []Track -} - -// Media is how many media the edition has. -func (e Edition) Media() int { - n := 0 - for _, t := range e.Tracks { - n = max(n, t.Medium) - } - return n -} - -// Want is the album the download was grabbed for. -type Want struct { - GroupMBID string - ArtistMBID string - Artist string - Title string - Year int - PrimaryType string - SecondaryTypes []string - // Upgrade: a held album wanted for a better copy, quality or - // rip; AlbumID is the library album it holds, whose tracks the import - // replaces. - Upgrade string - AlbumID pgtype.UUID -} - -// Pair is a file matched to an edition's track, and what agreed. -type Pair struct { - File int `json:"file"` - Track int `json:"track"` - Recording bool `json:"recording"` - Length bool `json:"length"` - Title bool `json:"title"` -} - -// Evidence is what the check counted, kept with the verdict so a person can -// see what it rested on. -type Evidence struct { - Files int `json:"files"` - Tracks int `json:"tracks"` - // Identified: files with a recording from AcoustID or their tags. - Identified int `json:"identified"` - Recordings int `json:"recordings"` - Lengths int `json:"lengths"` - Titles int `json:"titles"` - // GroupTag: "same" when the tags name this release group, "other" when - // another, "" when they name none. - GroupTag string `json:"group_tag,omitempty"` - AlbumTag string `json:"album_tag,omitempty"` - // Fingerprinted: AcoustID was asked. False when it is not set up or - // could not be reached; the check then rests on lengths and tags. - Fingerprinted bool `json:"fingerprinted"` -} - -// Verdict is the check's answer. -type Verdict struct { - Outcome Outcome `json:"outcome"` - Code string `json:"code"` - Reason string `json:"reason"` - // Edition indexes the editions passed in; -1 when none was chosen. - Edition int `json:"-"` - Pairs []Pair `json:"pairs,omitempty"` - Evidence Evidence `json:"evidence"` -} - -// Verify decides whether files are the wanted album and, if so, which -// edition and which track each file is. force is a person's "import anyway": -// the best edition is taken whatever the evidence, but a download with no -// audio is still refused. -func Verify(w Want, editions []Edition, files []File, fingerprinted, force bool) Verdict { - v := Verdict{Edition: -1, Evidence: Evidence{Files: len(files), Fingerprinted: fingerprinted}} - if len(files) == 0 { - return v.set(Refuse, CodeNoAudio, "The download holds no audio files.") - } - if !force && len(files) > maxFiles { - return v.set(Review, CodeTooMany, fmt.Sprintf( - "The download holds %d audio files, more than one album; a person decides.", len(files))) - } - if video := countIf(files, func(f File) bool { return f.Video }); !force && video*2 > len(files) { - return v.set(Refuse, CodeVideo, fmt.Sprintf( - "%d of its %d audio files are named as music or lyric videos: the sound of a video, not the album.", video, len(files))) - } - - group := majority(files, func(f File) string { return f.GroupMBID }) - switch { - case group == "": - case strings.EqualFold(group, w.GroupMBID): - v.Evidence.GroupTag = "same" - default: - v.Evidence.GroupTag = "other" - } - album := majority(files, func(f File) string { return f.Album }) - v.Evidence.AlbumTag = album - var tagVeto release.Match - albumAgrees := false - if album != "" { - // The want's own artist goes in front: the tags' artist spelling is - // not what this asks. Only the album title and its version words. - m := release.Judge(release.Want{Artist: w.Artist, Title: w.Title, PrimaryType: w.PrimaryType, - SecondaryTypes: w.SecondaryTypes}, release.Parse(w.Artist+" - "+album)) - switch m.Veto { - case release.VetoVersion, release.VetoTitle: - tagVeto = m - case "": - albumAgrees = true - } - } - if !force && v.Evidence.GroupTag == "other" { - return v.set(Refuse, CodeWrongAlbum, fmt.Sprintf( - "Its tags name a different MusicBrainz release group (%s), not %s.", group, w.Title)) - } - - if len(editions) == 0 { - if force { - v.Code, v.Outcome, v.Reason = CodeForced, Accept, "Imported anyway at a person's word; MusicBrainz lists no edition to match it to." - return v - } - return v.set(Review, CodeNoEdition, fmt.Sprintf( - "MusicBrainz lists no edition of %s to check the files against; a person decides.", w.Title)) - } - - best, bestScore := -1, -1 - shortest, longest := len(editions[0].Tracks), 0 - for i, e := range editions { - shortest, longest = min(shortest, len(e.Tracks)), max(longest, len(e.Tracks)) - if len(e.Tracks) != len(files) && !force { - continue - } - pairs := pairUp(files, e.Tracks) - if s := score(pairs); s > bestScore || (s == bestScore && better(e, editions[best])) { - best, bestScore = i, s - } - } - if best < 0 { - if len(files) < shortest { - return v.set(Refuse, CodeIncomplete, fmt.Sprintf( - "It holds %d audio files; the shortest edition of %s has %d tracks.", len(files), w.Title, shortest)) - } - return v.set(Review, CodeNoEdition, fmt.Sprintf( - "It holds %d audio files; no edition of %s has %d tracks (they have %s). A person decides.", - len(files), w.Title, len(files), span(shortest, longest))) - } - - e := editions[best] - v.Edition = best - v.Pairs = pairUp(files, e.Tracks) - n := len(e.Tracks) - ev := &v.Evidence - ev.Tracks = n - for _, p := range v.Pairs { - f := files[p.File] - if f.RecordingMBID != "" || len(f.Recordings) > 0 { - ev.Identified++ - } - ev.Recordings += b2i(p.Recording) - ev.Lengths += b2i(p.Length) - ev.Titles += b2i(p.Title) - } - if force { - v.Outcome, v.Code = Accept, CodeForced - v.Reason = fmt.Sprintf("Imported anyway at a person's word, as %s. %s", describe(e), ev.sentence()) - return v - } - - half := (n + 1) / 2 - strong := ev.GroupTag == "same" || (ev.Identified >= half && ev.Recordings*10 >= ev.Identified*7) - switch { - case ev.Identified >= half && ev.Recordings*10 < ev.Identified*3 && ev.GroupTag != "same": - return v.set(Refuse, CodeWrongAlbum, fmt.Sprintf( - "Only %d of the %d tracks AcoustID knows are recordings on %s.", ev.Recordings, ev.Identified, w.Title)) - case tagVeto.Veto != "" && !strong: - return v.set(Refuse, tagVeto.Veto, fmt.Sprintf("Its tags call it %q. %s", album, tagVeto.Reason)) - case !strong && ev.Identified == 0 && ev.Lengths*2 < n: - return v.set(Refuse, CodeWrongAlbum, fmt.Sprintf( - "Only %d of its %d tracks are the length of %s's, and nothing else says it is the album.", ev.Lengths, n, w.Title)) - case strong && ev.Lengths*10 >= n*6, - !strong && ev.Lengths*10 >= n*8 && (ev.Titles*10 >= n*6 || albumAgrees): - v.Outcome, v.Code = Accept, CodeMatched - v.Reason = fmt.Sprintf("It is %s. %s", describe(e), ev.sentence()) - return v - } - return v.set(Review, CodeWeak, fmt.Sprintf( - "It may be %s, but the evidence is thin: %s A person decides.", describe(e), ev.sentence())) -} - -func (v Verdict) set(o Outcome, code, reason string) Verdict { - v.Outcome, v.Code, v.Reason = o, code, reason - return v -} - -// sentence says what agreed, for the verdict's reason. -func (ev Evidence) sentence() string { - var parts []string - if ev.GroupTag == "same" { - parts = append(parts, "its tags name this album") - } - if ev.Identified > 0 { - parts = append(parts, fmt.Sprintf("%d of %d identified tracks are its recordings", ev.Recordings, ev.Identified)) - } - parts = append(parts, fmt.Sprintf("%d of %d lengths fit", ev.Lengths, ev.Tracks), - fmt.Sprintf("%d of %d titles agree", ev.Titles, ev.Tracks)) - s := strings.Join(parts, ", ") - s = strings.ToUpper(s[:1]) + s[1:] + "." - if !ev.Fingerprinted { - s += " AcoustID was not asked (not set up or unreachable), so lengths and tags decided." - } - return s -} - -// describe names an edition for a person: "the 2013 CD release (13 tracks)". -func describe(e Edition) string { - var b strings.Builder - b.WriteString("the ") - if len(e.Date) >= 4 { - b.WriteString(e.Date[:4] + " ") - } - if f := e.format(); f != "" { - b.WriteString(f + " ") - } - fmt.Fprintf(&b, "edition (%d tracks)", len(e.Tracks)) - return b.String() -} - -func (e Edition) format() string { - if len(e.Tracks) == 0 { - return "" - } - f := e.Tracks[0].Format - for _, t := range e.Tracks { - if t.Format != f { - return "" - } - } - return f -} - -// pairUp matches files to tracks in order: by the tags' disc and track -// numbers when every file has them and no two share a place, by file path -// otherwise. With a person's "import anyway" the counts may differ; pairs -// run to the shorter. -func pairUp(files []File, tracks []Track) []Pair { - order := make([]int, len(files)) - for i := range order { - order[i] = i - } - if numbered(files) { - sort.SliceStable(order, func(a, b int) bool { - fa, fb := files[order[a]], files[order[b]] - if da, db := max(fa.Disc, 1), max(fb.Disc, 1); da != db { - return da < db - } - return fa.Track < fb.Track - }) - } else { - sort.SliceStable(order, func(a, b int) bool { return files[order[a]].Rel < files[order[b]].Rel }) - } - n := min(len(files), len(tracks)) - pairs := make([]Pair, n) - for i := range n { - f, t := files[order[i]], tracks[i] - pairs[i] = Pair{ - File: order[i], - Track: i, - Recording: t.RecordingMBID != "" && (f.RecordingMBID == t.RecordingMBID || slices.Contains(f.Recordings, t.RecordingMBID)), - Length: release.LengthFits(f.LengthMs, t.LengthMs), - Title: release.TitleAgrees(f.Title, t.Title), - } - } - return pairs -} - -// numbered: every file carries a track number and no two share a disc and -// track. -func numbered(files []File) bool { - seen := map[[2]int]bool{} - for _, f := range files { - k := [2]int{max(f.Disc, 1), f.Track} - if f.Track <= 0 || seen[k] { - return false - } - seen[k] = true - } - return true -} - -// score weighs recordings above lengths above titles: a fingerprint is the -// audio itself, a length is the audio's shape, a title is only a name. -func score(pairs []Pair) int { - s := 0 - for _, p := range pairs { - s += 3*b2i(p.Recording) + 2*b2i(p.Length) + b2i(p.Title) - } - return s -} - -// better breaks a tie between equally good editions: an official one, then -// the earlier. -func better(a, b Edition) bool { - if (a.Status == "Official") != (b.Status == "Official") { - return a.Status == "Official" - } - return a.Date != "" && (b.Date == "" || a.Date < b.Date) -} - -func majority(files []File, get func(File) string) string { - counts := map[string]int{} - best, n := "", 0 - for _, f := range files { - v := strings.TrimSpace(get(f)) - if v == "" { - continue - } - counts[strings.ToLower(v)]++ - if c := counts[strings.ToLower(v)]; c > n { - best, n = v, c - } - } - return best -} - -func countIf(files []File, f func(File) bool) int { - n := 0 - for _, x := range files { - if f(x) { - n++ - } - } - return n -} - -func span(a, b int) string { - if a == b { - return fmt.Sprint(a) - } - return fmt.Sprintf("%d to %d", a, b) -} - -func b2i(b bool) int { - if b { - return 1 - } - return 0 -} diff --git a/internal/importer/verify_test.go b/internal/importer/verify_test.go deleted file mode 100644 index e3208fb7..00000000 --- a/internal/importer/verify_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package importer - -import ( - "fmt" - "path/filepath" - "strings" - "testing" -) - -var ram = Want{GroupMBID: "rg-ram", ArtistMBID: "mb-dp", Artist: "Daft Punk", Title: "Random Access Memories", - Year: 2013, PrimaryType: "Album"} - -var ramTitles = []string{"Give Life Back to Music", "The Game of Love", "Giorgio by Moroder", "Within", - "Instant Crush", "Lose Yourself to Dance", "Touch", "Get Lucky", "Beyond", "Motherboard", - "Fragments of Time", "Doin' It Right", "Contact"} - -// edition is RAM's 13-track CD, recordings rec-01.., lengths 4:00 + n seconds. -func edition(mbid string, n int) Edition { - e := Edition{MBID: mbid, Title: "Random Access Memories", Status: "Official", Date: "2013-05-17"} - for i := range n { - e.Tracks = append(e.Tracks, Track{Medium: 1, Format: "CD", Position: i + 1, Title: ramTitles[i%len(ramTitles)], - RecordingMBID: fmt.Sprintf("rec-%02d", i+1), LengthMs: 240000 + i*1000}) - } - return e -} - -// download is n files lined up with the edition: tagged positions, lengths -// within a second, AcoustID naming each file's recording. -func download(n int) []File { - var fs []File - for i := range n { - fs = append(fs, File{Path: fmt.Sprintf("/dl/%02d.flac", i+1), Rel: fmt.Sprintf("%02d.flac", i+1), - Disc: 1, Track: i + 1, Title: ramTitles[i%len(ramTitles)], Album: "Random Access Memories", - LengthMs: 240000 + i*1000 + 400, Recordings: []string{fmt.Sprintf("rec-%02d", i+1)}}) - } - return fs -} - -func TestVerify_TheAlbumAndWhatIsNot(t *testing.T) { - eds := []Edition{edition("rel-cd", 13), edition("rel-deluxe", 15)} - cases := []struct { - name string - files func() []File - printed bool - out Outcome - code string - edition string - }{ - {"the album, fingerprinted", func() []File { return download(13) }, true, Accept, CodeMatched, "rel-cd"}, - {"the deluxe by count", func() []File { return download(15) }, true, Accept, CodeMatched, "rel-deluxe"}, - {"no audio", func() []File { return nil }, true, Refuse, CodeNoAudio, ""}, - {"music videos", func() []File { - fs := download(13) - for i := range fs { - fs[i].Video = i < 10 - } - return fs - }, true, Refuse, CodeVideo, ""}, - {"tags name another group", func() []File { - fs := download(13) - for i := range fs { - fs[i].GroupMBID = "rg-homework" - } - return fs - }, true, Refuse, CodeWrongAlbum, ""}, - {"fingerprints say other recordings", func() []File { - fs := download(13) - for i := range fs { - fs[i].Recordings = []string{"rec-other"} - } - return fs - }, true, Refuse, CodeWrongAlbum, "rel-cd"}, - {"the drumless edition: right lengths, album tag says otherwise", func() []File { - fs := download(13) - for i := range fs { - fs[i].Recordings, fs[i].Album = nil, "Random Access Memories (Drumless Edition)" - } - return fs - }, false, Refuse, CodeOtherVersion, "rel-cd"}, - {"fewer files than any edition", func() []File { return download(9) }, true, Refuse, CodeIncomplete, ""}, - {"no edition this long", func() []File { return download(14) }, true, Review, CodeNoEdition, ""}, - {"no fingerprints, lengths and titles agree", func() []File { - fs := download(13) - for i := range fs { - fs[i].Recordings = nil - } - return fs - }, false, Accept, CodeMatched, "rel-cd"}, - {"no fingerprints, no titles, nothing to go on but lengths", func() []File { - fs := download(13) - for i := range fs { - fs[i].Recordings, fs[i].Title, fs[i].Album = nil, "", "" - } - return fs - }, false, Review, CodeWeak, "rel-cd"}, - {"no fingerprints, lengths all wrong", func() []File { - fs := download(13) - for i := range fs { - fs[i].Recordings, fs[i].LengthMs = nil, 600000 - } - return fs - }, false, Refuse, CodeWrongAlbum, "rel-cd"}, - {"tags name the group: strong even unprinted", func() []File { - fs := download(13) - for i := range fs { - fs[i].Recordings, fs[i].Title, fs[i].GroupMBID = nil, "", "rg-ram" - } - return fs - }, false, Accept, CodeMatched, "rel-cd"}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - v := Verify(ram, eds, c.files(), c.printed, false) - if v.Outcome != c.out || v.Code != c.code { - t.Fatalf("got %s/%s (%s), want %s/%s", v.Outcome, v.Code, v.Reason, c.out, c.code) - } - got := "" - if v.Edition >= 0 { - got = eds[v.Edition].MBID - } - if got != c.edition { - t.Errorf("edition %q, want %q", got, c.edition) - } - if v.Reason == "" { - t.Error("no reason given") - } - }) - } -} - -func TestVerify_UnnumberedFilesPairByPath(t *testing.T) { - fs := download(13) - for i := range fs { - fs[i].Track, fs[i].Disc = 0, 0 - } - fs[0], fs[5] = fs[5], fs[0] // listed out of order; their names sort right - v := Verify(ram, []Edition{edition("rel-cd", 13)}, fs, true, false) - if v.Outcome != Accept || v.Evidence.Recordings != 13 { - t.Fatalf("got %+v", v) - } -} - -func TestVerify_ImportAnywayTakesTheBestEdition(t *testing.T) { - v := Verify(ram, []Edition{edition("rel-cd", 13)}, download(14), true, true) - if v.Outcome != Accept || v.Code != CodeForced || v.Edition != 0 || len(v.Pairs) != 13 { - t.Fatalf("got %+v", v) - } - if v := Verify(ram, nil, nil, true, true); v.Outcome != Refuse { - t.Errorf("forced with no audio: %+v", v) - } -} - -func TestVerify_WithoutAcoustIDTheReasonSaysSo(t *testing.T) { - fs := download(13) - for i := range fs { - fs[i].Recordings = nil - } - v := Verify(ram, []Edition{edition("rel-cd", 13)}, fs, false, false) - if !strings.Contains(v.Reason, "AcoustID was not asked") { - t.Errorf("reason %q", v.Reason) - } -} - -func TestPlan_LibraryNaming(t *testing.T) { - e := edition("rel-cd", 2) - e.Tracks[1].Title = "Within: Part 2/3?" - pl := Plan("/music", ram, &e, download(2), Verify(ram, []Edition{e}, download(2), true, false).Pairs) - want := []string{ - "/music/Daft Punk/Random Access Memories (2013)/Daft Punk - Random Access Memories - 01 - Give Life Back to Music.flac", - "/music/Daft Punk/Random Access Memories (2013)/Daft Punk - Random Access Memories - 02 - Within - Part 2+3!.flac", - } - for i, p := range pl { - if p.Dest != want[i] { - t.Errorf("dest %d = %q, want %q", i, p.Dest, want[i]) - } - } - if pl[0].Recording != "rec-01" || pl[0].Tracks != 2 { - t.Errorf("placement %+v", pl[0]) - } -} - -func TestPlan_MultiDiscGetsAMediumFolder(t *testing.T) { - e := edition("rel-2cd", 4) - e.Tracks[2].Medium, e.Tracks[2].Position = 2, 1 - e.Tracks[3].Medium, e.Tracks[3].Position = 2, 2 - fs := download(4) - fs[2].Disc, fs[2].Track, fs[3].Disc, fs[3].Track = 2, 1, 2, 2 - pl := Plan("/music", ram, &e, fs, Verify(ram, []Edition{e}, fs, true, false).Pairs) - if got := filepath.Dir(pl[3].Dest); got != "/music/Daft Punk/Random Access Memories (2013)/CD 02" { - t.Errorf("disc folder %q", got) - } - if !strings.HasSuffix(pl[3].Dest, " - 02 - Get Lucky.flac") && !strings.Contains(pl[3].Dest, " - 02 - ") { - t.Errorf("dest %q", pl[3].Dest) - } -} - -func TestSegment(t *testing.T) { - for in, want := range map[string]string{ - "AC/DC": "AC+DC", `What?`: "What!", "Title: Sub": "Title - Sub", "a:b": "a-b", " ..x.. ": "x", - "": "_", "..": "_", `"Quoted" *y* |z|`: "Quoted x -y- z", - } { - if got := Segment(in); got != want { - t.Errorf("Segment(%q) = %q, want %q", in, got, want) - } - } - if long := Segment(strings.Repeat("é", 200)); len(long) > segmentMax { - t.Errorf("long segment is %d bytes", len(long)) - } -} - -func TestTagsArgs(t *testing.T) { - tg := Tags{Title: "Get Lucky", Artist: "Daft Punk", Track: 8, Tracks: 13, Disc: 1, Discs: 1, Year: 2013, - RecordingMBID: "rec-08", GroupMBID: "rg-ram"} - flac := strings.Join(tg.args(".flac"), " ") - for _, s := range []string{ - "title=Get Lucky", "track=8 ", "TRACKTOTAL=13", "disc=1 ", "DISCTOTAL=1", "date=2013", - "MUSICBRAINZ_TRACKID=rec-08", "MUSICBRAINZ_RELEASEGROUPID=rg-ram", - } { - if !strings.Contains(flac, s) { - t.Errorf("flac args lack %q: %s", s, flac) - } - } - // dhowden/tag reads a Vorbis TRACKNUMBER of "8/13" as 0. - if strings.Contains(flac, "/13") { - t.Errorf("flac track number carries its count: %s", flac) - } - if mp3 := strings.Join(tg.args(".mp3"), " "); !strings.Contains(mp3, "track=8/13") { - t.Errorf("mp3 track should be 8/13, which ID3 readers parse: %s", mp3) - } - if strings.Contains(flac, "MUSICBRAINZ_ALBUMID") { - t.Errorf("an empty release id was written: %s", flac) - } - if mp3 := strings.Join(tg.args(".mp3"), " "); !strings.Contains(mp3, "MusicBrainz Track Id=rec-08") { - t.Errorf("mp3 args %s", mp3) - } - if m4a := strings.Join(tg.args(".m4a"), " "); strings.Contains(m4a, "MusicBrainz") { - t.Errorf("m4a args %s", m4a) - } -} diff --git a/internal/indexer/indexer.go b/internal/indexer/indexer.go deleted file mode 100644 index d6a8af17..00000000 --- a/internal/indexer/indexer.go +++ /dev/null @@ -1,156 +0,0 @@ -// Package indexer is what every search source answers with, and the Torznab -// client. -// -// A client here holds ONE endpoint and knows nothing about the others. The -// fan-out across sources, the merge and what a source being down means belong -// to internal/acquire, because they are decisions about a search rather than -// about one source. -// -// Prowlarr is not served from here: it has no aggregate Torznab feed (`all` -// 404s like any id it does not have), so asking it everything at once means -// its native API, which internal/prowlarr speaks. -package indexer - -import ( - "errors" - "fmt" - "io" - "net/http" - "strings" - "time" -) - -// ErrUnconfigured is a source with no address (or, for Prowlarr, no key): not -// a failure, an instance that does not search there. -var ErrUnconfigured = errors.New("indexer is not configured") - -// ErrUnreachable is a search that could not be made: no network, a timeout, a -// malformed answer, a status outside 2xx. -var ErrUnreachable = errors.New("indexer unreachable") - -// ErrAuth is a key the source refused. Separate from ErrUnreachable because -// it needs a different sentence and a different action: a refused key is a -// field in Settings, an outage is something to wait out. -var ErrAuth = errors.New("the API key was refused") - -// UserAgent names Minstrel in Prowlarr's and each indexer's logs. -const UserAgent = "Minstrel (self-hosted music server; release search)" - -// MusicCategories are the Newznab categories a music search asks for: 3000 -// Audio, with its MP3 (3010) and Lossless (3040) children alongside, because -// an indexer that files music under a child answers only for the child. -// 3030 (Audiobook) is deliberately absent. -var MusicCategories = []int{3000, 3010, 3040} - -// Query is one search: the words, and which categories to ask in. Empty -// Categories asks every category. -type Query struct { - Text string - Categories []int -} - -// Result is one search result, as the source described it. -type Result struct { - Title string - // InfoHash is the torrent's identity, lowercased; empty when the source - // gave none. - InfoHash string - // Magnet is a magnet URI when the source published one. - Magnet string - // DownloadURL is a .torrent URL when it did not. It must be fetched - // through the source that offered it (it holds the tracker credentials), - // never handed to the download client. - DownloadURL string - SizeBytes int64 - Category int - // Indexer is the tracker BEHIND the source, as the source named it. - Indexer string - // Source is the acquisition_services code that was asked: where a - // .torrent fetch must be routed back to. - Source string - Published time.Time - // Seeders and Peers as reported. A feed that has not sampled a swarm - // reports a nominal 1, so these are not health unless SwarmKnown. - Seeders int - Peers int - // SwarmKnown says Seeders was measured, which only FabledExchange's own - // search can say. - SwarmKnown bool - // FilesCount is how many files the torrent holds, 0 when not said. - FilesCount int -} - -// Send sends req through c, stopping at a redirect to a magnet (returned as a -// *MagnetLink), and reads at most 8 MB of the answer. A call that never got -// an answer is ErrUnreachable; the status is the caller's to read. -func Send(c *http.Client, req *http.Request) (*http.Response, []byte, error) { - resp, err := StopAtMagnet(c).Do(req) - if m, ok := AsMagnet(err); ok { - return nil, nil, &MagnetLink{URI: m} - } - if err != nil { - return nil, nil, fmt.Errorf("%w: %v", ErrUnreachable, err) - } - defer func() { _ = resp.Body.Close() }() - body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) - if err != nil { - return nil, nil, fmt.Errorf("%w: read body: %v", ErrUnreachable, err) - } - return resp, body, nil -} - -// StatusError is what a non-2xx status means for a search source: a 429 is -// RateLimited naming who, anything else ErrUnreachable. Nil for a 2xx. -func StatusError(resp *http.Response, who string) error { - switch { - case resp.StatusCode == http.StatusTooManyRequests: - return &RateLimited{Who: who, RetryAfter: RetryAfter(resp.Header, time.Now())} - case resp.StatusCode < 200 || resp.StatusCode >= 300: - return fmt.Errorf("%w: HTTP %d", ErrUnreachable, resp.StatusCode) - } - return nil -} - -// NormalizeHash is a torrent's identity in its one canonical spelling. Every -// comparison of infohashes goes through it, so a hash differing only in case -// is never two releases. -func NormalizeHash(s string) string { - return strings.ToLower(strings.TrimSpace(s)) -} - -// IsInfoHash says whether s is shaped like a v1 (40) or v2 (64) hex infohash. -func IsInfoHash(s string) bool { - s = NormalizeHash(s) - if len(s) != 40 && len(s) != 64 { - return false - } - for _, r := range s { - if (r < '0' || r > '9') && (r < 'a' || r > 'f') { - return false - } - } - return true -} - -// MagnetHash pulls the infohash out of a magnet link, or returns "". It does -// not validate it. -func MagnetHash(magnet string) string { - const prefix = "urn:btih:" - at := strings.Index(magnet, prefix) - if at < 0 { - return "" - } - hash := magnet[at+len(prefix):] - if cut := strings.IndexAny(hash, "&/?"); cut >= 0 { - hash = hash[:cut] - } - return strings.ToLower(hash) -} - -// FirstLine is an error's first line, for a sentence on the settings page. -func FirstLine(s string) string { - if i := strings.IndexByte(s, '\n'); i >= 0 { - return s[:i] - } - return s -} diff --git a/internal/indexer/magnet.go b/internal/indexer/magnet.go deleted file mode 100644 index 123e61c2..00000000 --- a/internal/indexer/magnet.go +++ /dev/null @@ -1,58 +0,0 @@ -package indexer - -import ( - "bytes" - "errors" - "net/http" -) - -// MagnetLink is a download link that turned out to be a magnet. Returned as -// an error by a .torrent fetch so the grab hands the magnet to the download -// client instead. Public trackers do this routinely: Prowlarr's download link -// answers with a redirect to `magnet:?xt=…`, which Go's client would otherwise -// fail on as an unsupported scheme. -type MagnetLink struct{ URI string } - -func (m *MagnetLink) Error() string { return "the download link is a magnet link" } - -// AsMagnet says whether err is a magnet link, and which. -func AsMagnet(err error) (string, bool) { - var m *MagnetLink - if errors.As(err, &m) && m.URI != "" { - return m.URI, true - } - return "", false -} - -// StopAtMagnet returns a copy of c that stops at a redirect to a magnet URI -// and reports it as a *MagnetLink. Every other redirect behaves as c would. -func StopAtMagnet(c *http.Client) *http.Client { - if c == nil { - c = http.DefaultClient - } - out := *c - next := c.CheckRedirect - out.CheckRedirect = func(req *http.Request, via []*http.Request) error { - if req.URL != nil && req.URL.Scheme == "magnet" { - return &MagnetLink{URI: req.URL.String()} - } - if next != nil { - return next(req, via) - } - if len(via) >= 10 { - return errors.New("stopped after 10 redirects") - } - return nil - } - return &out -} - -// MagnetBody is a response whose whole body is a magnet URI, which some -// indexers send with a 200 instead of a redirect. Nil otherwise. -func MagnetBody(body []byte) error { - trimmed := bytes.TrimSpace(body) - if bytes.HasPrefix(trimmed, []byte("magnet:")) && !bytes.ContainsAny(trimmed, " \n<") { - return &MagnetLink{URI: string(trimmed)} - } - return nil -} diff --git a/internal/indexer/ratelimit.go b/internal/indexer/ratelimit.go deleted file mode 100644 index 5be3ca9f..00000000 --- a/internal/indexer/ratelimit.go +++ /dev/null @@ -1,50 +0,0 @@ -package indexer - -import ( - "errors" - "fmt" - "net/http" - "strconv" - "time" -) - -// RateLimited is a source answering 429. Named so the search pacing can hold -// that source back for as long as it asked; still an ErrUnreachable to -// everything else, because this search did not reach it. -type RateLimited struct { - // RetryAfter is what the source asked for; zero when it did not say. - RetryAfter time.Duration - // Who names the source in the sentence, e.g. "Prowlarr". - Who string -} - -func (e *RateLimited) Error() string { - return fmt.Sprintf("%v: HTTP 429, %s is rate-limiting this search", ErrUnreachable, e.Who) -} - -func (e *RateLimited) Unwrap() error { return ErrUnreachable } - -// AsRateLimited finds a RateLimited anywhere in err's chain. -func AsRateLimited(err error) (*RateLimited, bool) { - var rl *RateLimited - if errors.As(err, &rl) { - return rl, true - } - return nil, false -} - -// RetryAfter reads a Retry-After header: seconds, or an HTTP date. Zero when -// absent or unreadable. -func RetryAfter(h http.Header, now time.Time) time.Duration { - v := h.Get("Retry-After") - if v == "" { - return 0 - } - if s, err := strconv.Atoi(v); err == nil && s > 0 { - return time.Duration(s) * time.Second - } - if t, err := http.ParseTime(v); err == nil && t.After(now) { - return t.Sub(now) - } - return 0 -} diff --git a/internal/indexer/torznab.go b/internal/indexer/torznab.go deleted file mode 100644 index 8a458b1b..00000000 --- a/internal/indexer/torznab.go +++ /dev/null @@ -1,253 +0,0 @@ -package indexer - -import ( - "context" - "encoding/xml" - "fmt" - "net/http" - "net/url" - "strconv" - "strings" - "time" -) - -// DefaultTimeout is what an unset Timeout means. Longer than a metadata -// call: a feed may itself fan out to several trackers before answering. -const DefaultTimeout = 30 * time.Second - -// TorznabConfig is one Torznab feed. -type TorznabConfig struct { - // Code is the acquisition_services row this client was built from, - // stamped onto every Result. - Code string - // FeedURL is the feed's whole address up to and including /api, as - // Jackett or a Prowlarr indexer shows it — e.g. - // http://prowlarr:9696/12/api. Query parameters are appended to it. - // One field rather than base + path + indexer id: a pasted URL is more - // reliable than Minstrel being right about a third party's routes. - FeedURL string - // APIKey is optional: Torznab makes it so. A feed that needs one says so - // with Newznab error 100, which is ErrAuth. - APIKey string - Timeout time.Duration -} - -// Torznab searches one Torznab feed. -type Torznab struct { - Config TorznabConfig - // HTTP is injectable for tests. Nil takes http.DefaultClient. - HTTP *http.Client -} - -// Search asks the feed for q. `t=search` is free text, which every indexer -// supports; `t=music` takes artist and album separately, and a release name -// does not reliably say which of its parts is which. -func (c *Torznab) Search(ctx context.Context, q Query) ([]Result, error) { - params := url.Values{"t": {"search"}, "q": {q.Text}} - for _, cat := range q.Categories { - params.Add("cat", strconv.Itoa(cat)) - } - body, err := c.get(ctx, c.endpoint(params)) - if err != nil { - return nil, err - } - out, err := parseFeed(body) - if err != nil { - return nil, err - } - for i := range out { - out[i].Source = c.Config.Code - } - return out, nil -} - -// Download fetches a result's .torrent bytes through the feed, which holds -// the tracker's credentials. A result with a magnet needs none of this. -func (c *Torznab) Download(ctx context.Context, r Result) ([]byte, error) { - if r.DownloadURL == "" { - return nil, fmt.Errorf("%w: %q has no download URL", ErrUnreachable, r.Title) - } - body, err := c.get(ctx, r.DownloadURL) - if err != nil { - return nil, err - } - return torrentBody(r.Title, body) -} - -// torrentBody checks a fetched .torrent. A torrent is a bencoded dictionary -// and starts with 'd'; an expired session gets an HTML login page with HTTP -// 200, which the download client would otherwise reject as an unsupported -// file from a component that did nothing wrong. -func torrentBody(title string, body []byte) ([]byte, error) { - if err := MagnetBody(body); err != nil { - return nil, err - } - if len(body) == 0 || body[0] != 'd' { - return nil, fmt.Errorf("%w: %q returned %d bytes that are not a torrent", ErrUnreachable, title, len(body)) - } - return body, nil -} - -// TorrentBody is torrentBody for the other search clients' fetches. -func TorrentBody(title string, body []byte) ([]byte, error) { return torrentBody(title, body) } - -func (c *Torznab) endpoint(params url.Values) string { - if c.Config.APIKey != "" { - params.Set("apikey", c.Config.APIKey) - } - feed := strings.TrimSpace(c.Config.FeedURL) - sep := "?" - if strings.Contains(feed, "?") { - sep = "&" - } - return feed + sep + params.Encode() -} - -func (c *Torznab) get(ctx context.Context, endpoint string) ([]byte, error) { - if strings.TrimSpace(c.Config.FeedURL) == "" { - return nil, ErrUnconfigured - } - timeout := c.Config.Timeout - if timeout <= 0 { - timeout = DefaultTimeout - } - ctx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) - if err != nil { - return nil, fmt.Errorf("%w: build request: %v", ErrUnreachable, err) - } - req.Header.Set("User-Agent", UserAgent) - resp, body, err := Send(c.HTTP, req) - if err != nil { - return nil, err - } - if err := StatusError(resp, "the indexer"); err != nil { - return nil, err - } - // Newznab reports errors as HTTP 200 with an document, so a - // client checking only the status reads a refused key as an empty result - // set: search quietly stops finding things. - if err := errorDocument(body); err != nil { - return nil, err - } - return body, nil -} - -// errorDocument reads an answer. Newznab's 1xx -// codes (100 wrong key, 101 suspended, 102 insufficient privileges) are all -// about who is asking, so they are ErrAuth. -func errorDocument(body []byte) error { - head := body - if len(head) > 512 { - head = head[:512] - } - if !strings.Contains(string(head), " - // and repeats it in , either populated by version. - for _, candidate := range []string{it.Link, it.Enclosure.URL} { - if strings.HasPrefix(candidate, "magnet:") && r.Magnet == "" { - r.Magnet = candidate - } else if candidate != "" && r.DownloadURL == "" { - r.DownloadURL = candidate - } - } - // The infohash from the explicit attr, then the magnet, then the GUID - // only when it is shaped like a hash: Prowlarr puts a URL there as - // often as a hash. - r.InfoHash = NormalizeHash(it.attr("infohash")) - if r.InfoHash == "" { - r.InfoHash = MagnetHash(r.Magnet) - } - if r.InfoHash == "" && IsInfoHash(it.GUID) { - r.InfoHash = NormalizeHash(it.GUID) - } - if t, err := time.Parse(time.RFC1123Z, strings.TrimSpace(it.PubDate)); err == nil { - r.Published = t - } else if t, err := time.Parse(time.RFC1123, strings.TrimSpace(it.PubDate)); err == nil { - r.Published = t - } - out = append(out, r) - } - return out, nil -} - -func atoi(s string) int { - n, err := strconv.Atoi(strings.TrimSpace(s)) - if err != nil { - return 0 - } - return n -} diff --git a/internal/indexer/torznab_test.go b/internal/indexer/torznab_test.go deleted file mode 100644 index 2855f0af..00000000 --- a/internal/indexer/torznab_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package indexer - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "testing" - "time" -) - -const sampleFeed = ` - - - - Radiohead - OK Computer (1997) [FLAC] - https://tracker.example/details/1 - https://prowlarr.example/1/download?link=abc - 512000000 - Tue, 07 Oct 2026 10:00:00 +0000 - - - - - - - - Radiohead - Kid A (2000) [MP3 320] - 0123456789abcdef0123456789abcdef01234567 - magnet:?xt=urn:btih:FFEEDDCCBBAA99887766554433221100FFEEDDCC&dn=kid+a - - - - - -` - -func TestTorznabSearch_ParsesTheFeedAndStampsTheSource(t *testing.T) { - reqs := make(chan *http.Request, 1) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reqs <- r - _, _ = w.Write([]byte(sampleFeed)) - })) - defer srv.Close() - - c := &Torznab{Config: TorznabConfig{Code: "torznab-2", FeedURL: srv.URL + "/12/api", APIKey: "k"}} - results, err := c.Search(context.Background(), Query{Text: "radiohead", Categories: MusicCategories}) - if err != nil { - t.Fatalf("search: %v", err) - } - got := <-reqs - if got.URL.Path != "/12/api" || got.URL.Query().Get("t") != "search" || got.URL.Query().Get("apikey") != "k" { - t.Errorf("request = %s, want the feed URL with t=search and the key", got.URL) - } - if cats := got.URL.Query()["cat"]; len(cats) != 3 || cats[0] != "3000" { - t.Errorf("categories = %v, want the music categories", cats) - } - if len(results) != 2 { - t.Fatalf("results = %d, want 2 (the untitled item dropped)", len(results)) - } - first := results[0] - if first.InfoHash != "aabbccddeeff00112233445566778899aabbccdd" || first.Seeders != 12 || - first.Category != 3040 || first.Indexer != "RED" || first.DownloadURL == "" || first.Source != "torznab-2" { - t.Errorf("first = %+v", first) - } - if first.Published.IsZero() { - t.Error("pubDate was not parsed") - } - // The magnet's hash wins over a GUID shaped like another hash. - if results[1].Magnet == "" || results[1].InfoHash != "ffeeddccbbaa99887766554433221100ffeeddcc" { - t.Errorf("second = %+v, want the magnet's hash", results[1]) - } -} - -func TestTorznabSearch_KeepsAQueryAlreadyInTheFeedURL(t *testing.T) { - reqs := make(chan *http.Request, 1) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reqs <- r - _, _ = w.Write([]byte(``)) - })) - defer srv.Close() - - c := &Torznab{Config: TorznabConfig{FeedURL: srv.URL + "/api?passkey=p"}} - if _, err := c.Search(context.Background(), Query{Text: "x"}); err != nil { - t.Fatalf("search: %v", err) - } - got := <-reqs - if got.URL.Query().Get("passkey") != "p" || got.URL.Query().Get("q") != "x" { - t.Errorf("request = %s, want the pasted query kept and ours added", got.URL) - } -} - -// Newznab reports a refused key as HTTP 200 with an document. Read -// as a feed, that is an empty result set: search would quietly find nothing. -func TestTorznabSearch_ReadsAnErrorDocument(t *testing.T) { - for name, tc := range map[string]struct { - doc string - want error - }{ - "a wrong key": {``, ErrAuth}, - "anything else": {``, ErrUnreachable}, - } { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`` + tc.doc)) - })) - c := &Torznab{Config: TorznabConfig{FeedURL: srv.URL + "/api"}} - _, err := c.Search(context.Background(), Query{Text: "x"}) - srv.Close() - if !errors.Is(err, tc.want) { - t.Errorf("%s: err = %v, want %v", name, err, tc.want) - } - } -} - -func TestTorznabSearch_A429IsRateLimitedWithItsRetryAfter(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Retry-After", "90") - w.WriteHeader(http.StatusTooManyRequests) - })) - defer srv.Close() - - c := &Torznab{Config: TorznabConfig{FeedURL: srv.URL + "/api"}} - _, err := c.Search(context.Background(), Query{Text: "x"}) - rl, ok := AsRateLimited(err) - if !ok || rl.RetryAfter != 90*time.Second { - t.Fatalf("err = %v, want RateLimited for 90s", err) - } - if !errors.Is(err, ErrUnreachable) { - t.Error("a 429 should still read as unreachable to everything else") - } -} - -func TestTorznabSearch_NoAddressIsUnconfigured(t *testing.T) { - _, err := (&Torznab{}).Search(context.Background(), Query{Text: "x"}) - if !errors.Is(err, ErrUnconfigured) { - t.Fatalf("err = %v, want ErrUnconfigured", err) - } -} - -func TestTorznabDownload_RefusesWhatIsNotATorrent(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/login": - _, _ = w.Write([]byte(`please log in`)) - case "/magnet": - _, _ = w.Write([]byte("magnet:?xt=urn:btih:abc")) - case "/redirect": - http.Redirect(w, r, "magnet:?xt=urn:btih:def", http.StatusFound) - default: - _, _ = w.Write([]byte("d8:announce0:e")) - } - })) - defer srv.Close() - - c := &Torznab{Config: TorznabConfig{FeedURL: srv.URL + "/api"}} - ctx := context.Background() - if _, err := c.Download(ctx, Result{Title: "t", DownloadURL: srv.URL + "/login"}); !errors.Is(err, ErrUnreachable) { - t.Errorf("an HTML page: err = %v, want ErrUnreachable", err) - } - for _, path := range []string{"/magnet", "/redirect"} { - _, err := c.Download(ctx, Result{Title: "t", DownloadURL: srv.URL + path}) - if _, ok := AsMagnet(err); !ok { - t.Errorf("%s: err = %v, want a MagnetLink", path, err) - } - } - body, err := c.Download(ctx, Result{Title: "t", DownloadURL: srv.URL + "/file"}) - if err != nil || string(body) != "d8:announce0:e" { - t.Errorf("a torrent: body %q err %v", body, err) - } -} - -func TestRetryAfter(t *testing.T) { - now := time.Date(2026, 10, 10, 0, 0, 0, 0, time.UTC) - for v, want := range map[string]time.Duration{ - "": 0, - "30": 30 * time.Second, - "soon": 0, - "Sat, 10 Oct 2026 00:02:00 GMT": 2 * time.Minute, - } { - h := http.Header{} - if v != "" { - h.Set("Retry-After", v) - } - if got := RetryAfter(h, now); got != want { - t.Errorf("RetryAfter(%q) = %v, want %v", v, got, want) - } - } -} diff --git a/internal/library/acoustid_lookup.go b/internal/library/acoustid_lookup.go index ce881a0f..5b68b294 100644 --- a/internal/library/acoustid_lookup.go +++ b/internal/library/acoustid_lookup.go @@ -14,8 +14,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/acoustid" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/acoustid" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // AcoustID lookup worker. @@ -49,7 +50,7 @@ const acoustIDLookupConcurrency = 2 // silence; a radio edit or a live take differs by far more. const acoustIDDurationToleranceSec = 3 -// Lookup states, as migration 0069's CHECK has them. +// Lookup states, as the CHECK on track_acoustid_lookups.state has them. const ( lookupMatched = "matched" lookupAmbiguous = "ambiguous" @@ -171,19 +172,8 @@ func (w *AcoustIDLookupWorker) Status() AcoustIDLookupStatus { // Run blocks until ctx is cancelled: one pass at start, then one per tick, on // a kick, and after every settings save. func (w *AcoustIDLookupWorker) Run(ctx context.Context) { - w.runOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - case <-w.kick: - case <-w.settings.Changed(): - } - w.runOnce(ctx) - } + periodic.Run(ctx, w.logger, "acoustid lookup", w.tick, w.runOnce, + periodic.WakeOn(w.kick, w.settings.Changed())) } // runOnce contains a pass so that nothing it does (an error, a panic) can stop diff --git a/internal/library/acoustid_lookup_test.go b/internal/library/acoustid_lookup_test.go index aa0fdc5a..4b7241ee 100644 --- a/internal/library/acoustid_lookup_test.go +++ b/internal/library/acoustid_lookup_test.go @@ -15,9 +15,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/acoustid" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/acoustid" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func cand(id, title string, sec int, score float64) acoustid.Candidate { @@ -158,7 +158,7 @@ func addTrack(t *testing.T, q *dbq.Queries, album dbq.Album, artist dbq.Artist, // restoring `mbid = EXCLUDED.mbid` in UpsertTrack: the first re-read below // then erases the looked-up id. func TestUpsertTrack_KeepsALookedUpMbidUntilATagCarriesOne_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -198,7 +198,7 @@ func TestUpsertTrack_KeepsALookedUpMbidUntilATagCarriesOne_Integration(t *testin } func TestAcoustIDLookup_FillsOnlyWhatItCanSettle_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -269,7 +269,7 @@ func TestAcoustIDLookup_FillsOnlyWhatItCanSettle_Integration(t *testing.T) { } func TestAcoustIDLookup_StopsWhenTheServiceCannotAnswer_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -306,7 +306,7 @@ func TestAcoustIDLookup_StopsWhenTheServiceCannotAnswer_Integration(t *testing.T // similarity worker picks the track as a seed and can map ListenBrainz's // answers back to it. func TestAcoustIDLookup_FilledTrackReachesSimilarity_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/acoustid_settings.go b/internal/library/acoustid_settings.go index f504219d..bbb35b45 100644 --- a/internal/library/acoustid_settings.go +++ b/internal/library/acoustid_settings.go @@ -9,7 +9,8 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/secret" ) // AcoustID lookup settings: a database row, changed without a restart, shared @@ -30,10 +31,10 @@ type AcoustIDSettings struct { // Ready reports whether the worker may call AcoustID at all. func (s AcoustIDSettings) Ready() bool { return s.Enabled && s.APIKey != "" } -// DefaultAcoustIDSettings mirrors migration 0069's defaults: off, no key. +// DefaultAcoustIDSettings mirrors acoustid_settings's defaults: off, no key. var DefaultAcoustIDSettings = AcoustIDSettings{MinScore: 0.85} -// The score threshold's bounds, as migration 0069's CHECK has them. Below 0.5 +// The score threshold's bounds, as acoustid_settings's CHECK has them. Below 0.5 // AcoustID's own docs call a match doubtful; the floor keeps a typo in the // field from filling the library with guesses. const ( @@ -97,8 +98,12 @@ func (s *AcoustIDSettingsService) Set(ctx context.Context, in AcoustIDSettingsUp } params := dbq.UpdateAcoustIDSettingsParams{Enabled: in.Enabled, MinScore: in.MinScore} if in.APIKey != nil { + sealed, err := secret.Seal(secret.AcoustIDAPIKey.Purpose(), "", *in.APIKey) + if err != nil { + return AcoustIDSettings{}, fmt.Errorf("acoustid settings: seal key: %w", err) + } params.SetApiKey = true - params.ApiKey = *in.APIKey + params.ApiKey = sealed } row, err := dbq.New(s.pool).UpdateAcoustIDSettings(ctx, params) if err != nil { @@ -126,7 +131,7 @@ func (s *AcoustIDSettingsService) Changed() <-chan struct{} { func acoustIDSettingsFromRow(row dbq.AcoustidSetting) AcoustIDSettings { out := AcoustIDSettings{Enabled: row.Enabled, MinScore: row.MinScore, UpdatedAt: row.UpdatedAt.Time} if row.ApiKey != nil { - out.APIKey = *row.ApiKey + out.APIKey = secret.Reveal(secret.AcoustIDAPIKey.Purpose(), "", *row.ApiKey) } return out } diff --git a/internal/library/album_loudness.go b/internal/library/album_loudness.go index 17e67fae..0972b1f0 100644 --- a/internal/library/album_loudness.go +++ b/internal/library/album_loudness.go @@ -8,8 +8,8 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Album loudness. diff --git a/internal/library/album_loudness_test.go b/internal/library/album_loudness_test.go index 93f2cf98..20d3cc44 100644 --- a/internal/library/album_loudness_test.go +++ b/internal/library/album_loudness_test.go @@ -8,8 +8,9 @@ import ( "path/filepath" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // histAt builds a histogram of n blocks all at one loudness. @@ -115,7 +116,7 @@ func TestComputeAlbumLoudness(t *testing.T) { // stored histograms, does nothing when nothing changed, and recomputes on // each kind of membership change. func TestAlbumLoudness_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/artistcredit.go b/internal/library/artistcredit.go new file mode 100644 index 00000000..f2d0ce78 --- /dev/null +++ b/internal/library/artistcredit.go @@ -0,0 +1,140 @@ +package library + +import ( + "io" + "regexp" + "strings" + + "github.com/dhowden/tag" +) + +// artistCredit is who a track is filed under, and the credit shown beside it. +// +// A track's ARTIST tag is a credit, not always one artist: "Low Tide Choir +// feat. Ruby Calloway" names a guest, and a collaboration names two artists +// equally. Filed under the whole string, each such credit became an artist of +// its own, with its own page, its own place in the artist list and its own +// "Songs like" mix, holding one or two tracks. The track is filed under its +// first artist instead, and the full credit is kept to show with it. +type artistCredit struct { + // Name is the artist the track is filed under. + Name string + // MBID is Name's MusicBrainz id, or "". + MBID string + // Credit is the full credit when it names more than Name, else "". + Credit string +} + +// featuring finds where a guest credit starts: "X feat. Y", "X ft. Y", +// "X featuring Y", "X (feat. Y)". Outside brackets the abbreviations need +// their full stop, so a band called "Tiny Feat" is not cut short; inside +// brackets the stop is optional. +var featuring = regexp.MustCompile(`(?i)\s+(?:[(\[]\s*(?:feat\.?|ft\.?|featuring)|feat\.|ft\.|featuring)\s`) + +// readArtistCredit works out a track's artist credit from its tags. +// +// - A file that lists its artists one by one (Picard's ARTISTS tag, two or +// more values) is filed under the first. This is the only way a +// collaboration is split: "A & B" may be two artists or one band +// ("Simone & Garfield", "St. Mark & The Mended Bones"), and only the +// list says which. +// - Otherwise a featured guest is cut from the credit: "X feat. Y" is filed +// under X. +// - Otherwise the credit is the artist. +// +// The MusicBrainz id is the first of the file's artist ids, which Picard +// writes in credit order, so it belongs to the first artist. +func readArtistCredit(meta tag.Metadata, rs io.ReadSeeker, ids TagMBIDs) artistCredit { + credit := strings.TrimSpace(meta.Artist()) + listed := readTagList(meta, rs, "ARTISTS", "ARTISTS") + mbid := ids.Artist + if isVorbis(meta) { + // dhowden/tag keeps the last of a repeated Vorbis field, which on a + // credit of two artists is the second artist's id. + if all := readTagList(meta, rs, "MUSICBRAINZ_ARTISTID", ""); len(all) > 0 { + mbid = cleanMBID(all[0]) + } + } + + name := credit + switch { + case len(listed) >= 2: + name = listed[0] + if credit == "" { + credit = strings.Join(listed, ", ") + } + case credit != "": + name = withoutGuests(credit) + } + if name == "" { + return artistCredit{Name: "Unknown Artist"} + } + out := artistCredit{Name: name, MBID: mbid} + if credit != name { + out.Credit = credit + } + return out +} + +// withoutGuests cuts a featured guest from a credit: "X feat. Y" gives X. +// Album artists go through it too, as a single's release credit often names +// its guest. +func withoutGuests(credit string) string { + if loc := featuring.FindStringIndex(credit); loc != nil && loc[0] > 0 { + return strings.TrimSpace(credit[:loc[0]]) + } + return credit +} + +func isVorbis(meta tag.Metadata) bool { return meta.Format() == tag.VORBIS } + +// readTagList returns every value of a field that can repeat, in file order: +// the Vorbis comment vorbisKey (FLAC, Ogg Vorbis, Opus), or the user-defined +// text field called textName (ID3v2 TXXX, MP4 freeform). An empty textName +// reads Vorbis only. A file that cannot be read for it gives nil. +func readTagList(meta tag.Metadata, rs io.ReadSeeker, vorbisKey, textName string) []string { + var values []string + switch meta.Format() { + case tag.VORBIS: + if meta.FileType() == tag.OGG { + values, _ = readOggValues(rs, vorbisKey) + } else { + values, _ = readFLACValues(rs, vorbisKey) + } + case tag.MP4: + if textName != "" { + values, _ = readMP4FreeformValues(rs, textName) + } + case tag.ID3v2_2, tag.ID3v2_3, tag.ID3v2_4: + if textName != "" { + values = id3TextList(meta, textName) + } + } + return values +} + +// id3TextList reads the TXXX field called name. dhowden/tag files each TXXX +// frame under "TXXX", "TXXX_0", … as a *tag.Comm. ID3v2.4 separates the +// values of one frame with NUL. ID3v2.3 has no separator, and a "/" there +// may be part of a name (AM/FM), so a v2.3 frame is one value. +func id3TextList(meta tag.Metadata, name string) []string { + var out []string + for key, v := range meta.Raw() { + if !strings.HasPrefix(key, "TXXX") { + continue + } + c, ok := v.(*tag.Comm) + if !ok || !strings.EqualFold(c.Description, name) { + continue + } + for _, part := range strings.Split(c.Text, "\x00") { + if p := strings.TrimSpace(part); p != "" { + out = append(out, p) + } + } + // One frame per field name: a tagger that wrote two would leave the + // order between them to map iteration. + break + } + return out +} diff --git a/internal/library/artistcredit_test.go b/internal/library/artistcredit_test.go new file mode 100644 index 00000000..00346e47 --- /dev/null +++ b/internal/library/artistcredit_test.go @@ -0,0 +1,156 @@ +package library + +import ( + "bytes" + "testing" + + "github.com/dhowden/tag" +) + +func TestWithoutGuests(t *testing.T) { + tests := []struct{ credit, want string }{ + {"Low Tide Choir feat. Ruby Calloway", "Low Tide Choir"}, + {"Low Tide Choir ft. Ruby Calloway", "Low Tide Choir"}, + {"Low Tide Choir featuring Ruby Calloway", "Low Tide Choir"}, + {"Low Tide Choir (feat. Ruby Calloway)", "Low Tide Choir"}, + {"Low Tide Choir [ft Ruby Calloway]", "Low Tide Choir"}, + {"Low Tide Choir FEAT. Ruby Calloway & Mae", "Low Tide Choir"}, + // Names that only look like a credit stay whole. + {"Tiny Feat", "Tiny Feat"}, + {"Tiny Feat featuring Bonnie Rains", "Tiny Feat"}, + {"Deft Monks", "Deft Monks"}, + {"Loft Cell", "Loft Cell"}, + {"Featuring Fools", "Featuring Fools"}, + {"Simone & Garfield", "Simone & Garfield"}, + {"St. Mark & The Mended Bones", "St. Mark & The Mended Bones"}, + } + for _, tc := range tests { + if got := withoutGuests(tc.credit); got != tc.want { + t.Errorf("withoutGuests(%q) = %q, want %q", tc.credit, got, tc.want) + } + } +} + +// id3Meta is an ID3v2 file's tags as dhowden/tag presents them. +type id3Meta struct { + tag.Metadata + artist string + raw map[string]interface{} +} + +func (m id3Meta) Format() tag.Format { return tag.ID3v2_4 } +func (m id3Meta) FileType() tag.FileType { return tag.MP3 } +func (m id3Meta) Artist() string { return m.artist } +func (m id3Meta) Raw() map[string]interface{} { return m.raw } + +func TestReadArtistCredit_ID3(t *testing.T) { + tests := []struct { + name string + artist string + raw map[string]interface{} + mbid string + want artistCredit + }{ + { + name: "a guest is cut from the credit", + artist: "Low Tide Choir feat. Ruby Calloway", + mbid: "id-choir", + want: artistCredit{Name: "Low Tide Choir", MBID: "id-choir", Credit: "Low Tide Choir feat. Ruby Calloway"}, + }, + { + name: "a collaboration the file lists is filed under its first artist", + artist: "Paper Lanterns & Ruby Calloway", + raw: map[string]interface{}{"TXXX": &tag.Comm{Description: "ARTISTS", Text: "Paper Lanterns\x00Ruby Calloway"}}, + want: artistCredit{Name: "Paper Lanterns", Credit: "Paper Lanterns & Ruby Calloway"}, + }, + { + name: "an & the file does not list is one artist", + artist: "St. Mark & The Mended Bones", + raw: map[string]interface{}{"TXXX": &tag.Comm{Description: "ARTISTS", Text: "St. Mark & The Mended Bones"}}, + want: artistCredit{Name: "St. Mark & The Mended Bones"}, + }, + { + name: "a v2.3 list has no separator, so a slash stays in the name", + artist: "AM/FM", + raw: map[string]interface{}{"TXXX_0": &tag.Comm{Description: "Artists", Text: "AM/FM"}}, + want: artistCredit{Name: "AM/FM"}, + }, + { + name: "no artist at all", + want: artistCredit{Name: "Unknown Artist"}, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := readArtistCredit(id3Meta{artist: tc.artist, raw: tc.raw}, nil, TagMBIDs{Artist: tc.mbid}) + if got != tc.want { + t.Errorf("readArtistCredit = %+v, want %+v", got, tc.want) + } + }) + } +} + +// A FLAC credited to two artists, as Picard writes it: ARTIST is the credit, +// and ARTISTS and MUSICBRAINZ_ARTISTID list the artists in credit order. +// dhowden/tag keeps the last of each repeated field, so it alone would file +// the track under the second artist's id. +func TestReadArtistCredit_FLACListsItsArtists(t *testing.T) { + data := buildFLAC(false, + "TITLE=Undertow", + "ARTIST=Paper Lanterns & Ruby Calloway", + "ARTISTS=Paper Lanterns", + "ARTISTS=Ruby Calloway", + "MUSICBRAINZ_ARTISTID=id-lanterns", + "MUSICBRAINZ_ARTISTID=id-ruby", + ) + rs := bytes.NewReader(data) + meta, err := tag.ReadFrom(rs) + if err != nil { + t.Fatalf("tag.ReadFrom: %v", err) + } + got := readArtistCredit(meta, rs, ReadTagMBIDs(meta)) + want := artistCredit{Name: "Paper Lanterns", MBID: "id-lanterns", Credit: "Paper Lanterns & Ruby Calloway"} + if got != want { + t.Errorf("readArtistCredit = %+v, want %+v", got, want) + } +} + +func TestReadArtistCredit_FLACWithOneArtist(t *testing.T) { + data := buildFLAC(false, "ARTIST=Marisa & the Cats", "ARTISTS=Marisa & the Cats", "MUSICBRAINZ_ARTISTID=id-kats") + rs := bytes.NewReader(data) + meta, err := tag.ReadFrom(rs) + if err != nil { + t.Fatalf("tag.ReadFrom: %v", err) + } + got := readArtistCredit(meta, rs, ReadTagMBIDs(meta)) + if want := (artistCredit{Name: "Marisa & the Cats", MBID: "id-kats"}); got != want { + t.Errorf("readArtistCredit = %+v, want %+v", got, want) + } +} + +func TestReadMP4FreeformValues(t *testing.T) { + freeform := func(name string, values ...string) []byte { + children := [][]byte{ + mp4Box("mean", []byte{0, 0, 0, 0}, []byte("com.apple.iTunes")), + mp4Box("name", []byte{0, 0, 0, 0}, []byte(name)), + } + for _, v := range values { + children = append(children, mp4Text(v)) + } + return mp4Box("----", children...) + } + data := buildMP4(true, + freeform("MusicBrainz Artist Id", "id-lanterns"), + freeform("ARTISTS", "Paper Lanterns", "Ruby Calloway"), + ) + got, err := readMP4FreeformValues(bytes.NewReader(data), "artists") + if err != nil { + t.Fatalf("readMP4FreeformValues: %v", err) + } + if want := []string{"Paper Lanterns", "Ruby Calloway"}; !equalStrings(got, want) { + t.Errorf("ARTISTS = %q, want %q", got, want) + } + if got, err := readMP4FreeformValues(bytes.NewReader(buildMP4(true)), "ARTISTS"); err != nil || got != nil { + t.Errorf("no ARTISTS item: got %q, %v; want nil, nil", got, err) + } +} diff --git a/internal/library/delete.go b/internal/library/delete.go index 8e65edf2..f342bb00 100644 --- a/internal/library/delete.go +++ b/internal/library/delete.go @@ -14,9 +14,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // ErrTrackNotFound is returned when DeleteTrackFile is called with an id @@ -78,9 +78,10 @@ type DeletedTrack struct { } // DeleteTrackFile removes a track's file from disk and then its row, tidying -// away an album or artist the delete leaves empty. It is the ONLY path that -// deletes a track file: the admin remove-track endpoint and quarantine's Delete -// file both come through here. +// away an album or artist the delete leaves empty. It is the only path that +// deletes a track with its file: the admin remove-track endpoint and Reports' +// "Remove from library" both come through here. RemoveFile is the other +// path that deletes a file, and it keeps the track. // // Order is the whole contract. The file goes first, and if it cannot go — a // read-only mount, a permission denial, an I/O error — nothing else happens and diff --git a/internal/library/delete_test.go b/internal/library/delete_test.go index f51af5c3..02858f7d 100644 --- a/internal/library/delete_test.go +++ b/internal/library/delete_test.go @@ -3,9 +3,7 @@ package library import ( "context" "errors" - "io" "io/fs" - "log/slog" "os" "path/filepath" "syscall" @@ -14,32 +12,10 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func seedTrack(t *testing.T, pool *pgxpool.Pool, filePath string) (dbq.Track, dbq.Album, dbq.Artist) { t.Helper() q := dbq.New(pool) @@ -76,7 +52,7 @@ func stubRemoveFile(t *testing.T, fn func(string) error) { } func TestDeleteTrackFile_HappyPath(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) dir := t.TempDir() @@ -114,7 +90,7 @@ func TestDeleteTrackFile_HappyPath(t *testing.T) { } func TestDeleteTrackFile_EmptiedAlbumAndArtistGoToo(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) path := filepath.Join(t.TempDir(), "lone.mp3") @@ -157,7 +133,7 @@ func TestDeleteTrackFile_UnremovableFileDeletesNothing(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) dir := t.TempDir() @@ -202,7 +178,7 @@ func TestDeleteTrackFile_UnremovableFileDeletesNothing(t *testing.T) { } func TestDeleteTrackFile_FileAlreadyGoneSucceeds(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) track, _, _ := seedTrack(t, pool, "/no/such/file/anywhere.mp3") @@ -216,7 +192,7 @@ func TestDeleteTrackFile_FileAlreadyGoneSucceeds(t *testing.T) { } func TestDeleteTrackFile_NotFoundReturnsErr(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) var bogus pgtype.UUID bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} diff --git a/internal/library/duplicate_classify.go b/internal/library/duplicate_classify.go index b4b19817..c02aa3fa 100644 --- a/internal/library/duplicate_classify.go +++ b/internal/library/duplicate_classify.go @@ -17,13 +17,13 @@ import ( // a song once, so the extra copies are the ones to fold away. // - cross_release: the copies are on different albums. A single and the // album it came from, a deluxe edition and the standard one, or one -// recording a later release retitled ("The Ragtime Cat", "F.O.D. (live)", +// recording a later release retitled ("The Ragtime Cat", "F.O.E. (live)", // a romanized title): each copy belongs to its own release, so none is // deleted (unless it is a video rip; the resolver decides). Copies under // different titles on different releases are retitles, not different // songs. // - distinct: one album, two versions of a song that sound alike, named as -// such ("Lovesick", "Lovesick (Instrumental)"). Not duplicates. +// such ("Homesick", "Homesick (Instrumental)"). Not duplicates. // - mismatch: one album holds the same audio under different song titles: // one file filling several track slots, a broken download. Which slot is // right is the resolver's to decide from MusicBrainz's track lengths. @@ -54,7 +54,7 @@ type ClassifyMember struct { // adds to a title (featuring credits, remaster notes, video markers) and keeps // what names a different recording (live, demo, remix, instrumental). On one // album, titles that differ only by such a word are two versions (distinct) -// unless the bytes are identical, which is one file twice: "WWW" and "WWW +// unless the bytes are identical, which is one file twice: "XYZ" and "XYZ // (instrumental)" holding the same file is a wrong slot. func ClassifyDuplicateGroup(tier string, members []ClassifyMember) DuplicateClass { if len(members) < 2 { @@ -98,8 +98,8 @@ var versionWord = regexp.MustCompile( // versionWords lists, sorted and lowercased, the version words in a copy's // title and file name together. Two copies holding one title tag can still be -// two versions, told apart only by the file name: "Suite-Pee" and -// "Suite-Pee (Clean Version)", "Luv (sic) Grand Finale" and its instrumental. +// two versions, told apart only by the file name: "Suite-Tea" and +// "Suite-Tea (Clean Version)", "Hush (sic) Grand Finale" and its instrumental. func versionWords(title, path string) string { seen := map[string]bool{} name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) @@ -123,7 +123,7 @@ func versionWords(title, path string) string { // songKey is MatchTitleKey with every bracketed segment and a dashed version // suffix dropped: the song a title names, whatever version of it. -// "Lovesick (Instrumental)", "Lovesick - Instrumental Version" and "Lovesick" +// "Homesick (Instrumental)", "Homesick - Instrumental Version" and "Homesick" // share one. func songKey(title, artist string) string { t := versionSuffix.ReplaceAllString(bracketed.ReplaceAllString(title, " "), "") @@ -134,9 +134,9 @@ func songKey(title, artist string) string { } var ( - // A bracketed credit: "(feat. Panda Bear)", "[ft. X]", "(featuring Y)". + // A bracketed credit: "(feat. Koala Bear)", "[ft. X]", "(featuring Y)". featBracket = regexp.MustCompile(`(?i)[(\[][^)\]]*\b(feat\.?|ft\.?|featuring)\s[^)\]]*[)\]]`) - // A credit trailing the title without brackets: "Doin' It Right ft. Panda + // A credit trailing the title without brackets: "Doin' It Twice ft. Koala // Bear". featTrailing = regexp.MustCompile(`(?i)\s(feat\.?|ft\.?|featuring)\s.*$`) // "(2011 Remaster)", "[Remastered]", "- Remastered 2009". diff --git a/internal/library/duplicate_classify_test.go b/internal/library/duplicate_classify_test.go index 9aea59c3..3cc1a16f 100644 --- a/internal/library/duplicate_classify_test.go +++ b/internal/library/duplicate_classify_test.go @@ -4,13 +4,13 @@ import ( "fmt" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // The group shapes the classifier tells apart. func TestClassifyDuplicateGroup(t *testing.T) { m := func(album, title string) ClassifyMember { - return ClassifyMember{AlbumID: album, Title: title, ArtistName: "Gorillaz"} + return ClassifyMember{AlbumID: album, Title: title, ArtistName: "Plastic Apes"} } cases := []struct { name string @@ -18,30 +18,30 @@ func TestClassifyDuplicateGroup(t *testing.T) { members []ClassifyMember want DuplicateClass }{ - {"Humanz: one album, one song twice", "exact", - []ClassifyMember{m("humanz", "Saturnz Barz"), m("humanz", "Saturnz Barz (Official Video)")}, ClassSameRelease}, + {"Mammalz: one album, one song twice", "exact", + []ClassifyMember{m("mammalz", "Neptunez Barz"), m("mammalz", "Neptunez Barz (Official Video)")}, ClassSameRelease}, {"one album, video upload title with artist prefix", "acoustic", - []ClassifyMember{m("humanz", "Andromeda"), m("humanz", "Gorillaz - Andromeda (Official Audio)")}, ClassSameRelease}, + []ClassifyMember{m("mammalz", "Cassiopeia"), m("mammalz", "Plastic Apes - Cassiopeia (Official Audio)")}, ClassSameRelease}, {"one album, identical bytes under a version title: one file in two slots", "exact", - []ClassifyMember{m("www", "WWW"), m("www", "WWW (instrumental)")}, ClassMismatch}, + []ClassifyMember{m("www", "XYZ"), m("www", "XYZ (instrumental)")}, ClassMismatch}, {"one album, acoustic match, two versions named", "acoustic", - []ClassifyMember{m("moe", "Lovesick"), m("moe", "Lovesick (Instrumental)")}, ClassDistinct}, + []ClassifyMember{m("moe", "Homesick"), m("moe", "Homesick (Instrumental)")}, ClassDistinct}, {"Void: one album, one audio under three song titles", "acoustic", - []ClassifyMember{m("void", "Slimewar (into the void)"), m("void", "Void"), m("void", "Reach")}, ClassMismatch}, + []ClassifyMember{m("void", "Slimeworld (into the void)"), m("void", "Void"), m("void", "Reach")}, ClassMismatch}, {"a version named after a dash", "acoustic", []ClassifyMember{m("andora", "Goodbye Yesterday"), m("andora", "Goodbye Yesterday - Instrumental Version")}, ClassDistinct}, {"a dash that names no version", "acoustic", []ClassifyMember{m("a", "Monday Chill - Part One"), m("a", "Monday Chill - Part Two")}, ClassMismatch}, {"Slasher and Slasher II are not versions of one song", "acoustic", []ClassifyMember{m("slasher", "Slasher"), m("slasher", "Slasher II")}, ClassMismatch}, - {"Big Me: the single and the album", "exact", - []ClassifyMember{m("single", "Big Me"), m("album", "Big Me")}, ClassCrossRelease}, + {"Big You: the single and the album", "exact", + []ClassifyMember{m("single", "Big You"), m("album", "Big You")}, ClassCrossRelease}, {"remaster and featuring credits are one song", "acoustic", - []ClassifyMember{m("a", "Feel Good Inc. (2017 Remaster)"), m("b", "Feel Good Inc feat. De La Soul")}, ClassCrossRelease}, + []ClassifyMember{m("a", "Feel Fine Ltd. (2017 Remaster)"), m("b", "Feel Fine Ltd feat. Del Mar Soul")}, ClassCrossRelease}, {"a later release retitles the recording", "acoustic", []ClassifyMember{m("coco", "Ragtime Cat"), m("single", "The Ragtime Cat")}, ClassCrossRelease}, {"identical bytes on two albums under two titles", "exact", - []ClassifyMember{m("dookie", "F.O.D."), m("live", "F.O.D. (live)")}, ClassCrossRelease}, + []ClassifyMember{m("cookie", "F.O.E."), m("live", "F.O.E. (live)")}, ClassCrossRelease}, {"a lone copy", "exact", []ClassifyMember{m("a", "Song")}, ClassReview}, } for _, tc := range cases { @@ -53,9 +53,9 @@ func TestClassifyDuplicateGroup(t *testing.T) { func TestMatchTitleKey(t *testing.T) { cases := []struct{ title, artist, want string }{ - {"Saturnz Barz (Official Video)", "Gorillaz", "saturnzbarz"}, - {"Gorillaz - Saturnz Barz", "Gorillaz", "saturnzbarz"}, - {"Doin' It Right (Music Video) ft. Panda Bear", "Daft Punk", "doinitright"}, + {"Neptunez Barz (Official Video)", "Plastic Apes", "neptunezbarz"}, + {"Plastic Apes - Neptunez Barz", "Plastic Apes", "neptunezbarz"}, + {"Doin' It Twice (Music Video) ft. Koala Bear", "Deft Monks", "doinittwice"}, {"Song [feat. X]", "", "song"}, {"Song - Remastered 2009", "", "song"}, {"Rock & Roll", "", "rockandroll"}, @@ -79,12 +79,12 @@ func TestMatchTitleKey(t *testing.T) { // named differently must agree. func TestVersionWords(t *testing.T) { differ := [][2][2]string{ - {{"Suite-Pee", "/m/SOAD/Sugar/System of a Down - Sugar - 02 - Suite-Pee.mp3"}, - {"Suite-Pee", "/m/SOAD/Sugar/System of a Down - Sugar - 02 - Suite-Pee (Clean Version).mp3"}}, - {{"Luv (sic) Grand Finale", "/m/Nujabes/Hexalogy/Nujabes - Luv(sic) Hexalogy - 06 - Luv (sic) Grand Finale Instrumentals.mp3"}, - {"Luv (sic) Grand Finale", "/m/Nujabes/Hexalogy/0106 - Luvsic Grand Finale.m4a"}}, - {{"Charger", "/m/Gorillaz/Humanz/Gorillaz - Humanz - 08 - Charger - live in Cologne 2017.mp3"}, - {"Charger", "/m/Gorillaz/Humanz/CD 01/08 Charger.flac"}}, + {{"Suite-Tea", "/m/SOAC/Sugar/System of a Clown - Sugar - 02 - Suite-Tea.mp3"}, + {"Suite-Tea", "/m/SOAC/Sugar/System of a Clown - Sugar - 02 - Suite-Tea (Clean Version).mp3"}}, + {{"Hush (sic) Grand Finale", "/m/Sebanuj/Heptalogy/Sebanuj - Hush(sic) Heptalogy - 06 - Hush (sic) Grand Finale Instrumentals.mp3"}, + {"Hush (sic) Grand Finale", "/m/Sebanuj/Heptalogy/0106 - Hushsic Grand Finale.m4a"}}, + {{"Dynamo", "/m/Plastic Apes/Mammalz/Plastic Apes - Mammalz - 08 - Dynamo - live in Cologne 2017.mp3"}, + {"Dynamo", "/m/Plastic Apes/Mammalz/CD 01/08 Dynamo.flac"}}, } for _, p := range differ { a, b := versionWords(p[0][0], p[0][1]), versionWords(p[1][0], p[1][1]) @@ -93,12 +93,12 @@ func TestVersionWords(t *testing.T) { } } agree := [][2][2]string{ - {{"Heat Waves (Shakur Ahmad Remix)", "/m/GA/Glass Animals - Dreamland Deluxe - 02 - Heat Waves (Shakur Ahmad Remix).mp3"}, - {"Heat Waves (Shakur Ahmad Remix)", "/m/GA/02. Heat Waves (Shakur Ahmad Remix).flac"}}, - {{"Luv (sic) Instrumentals", "/m/Nujabes/0201 - Luvsic instrumentals.m4a"}, - {"Luv (sic) Instrumentals", "/m/Nujabes/Nujabes - Luv(sic) Hexalogy - 01 - Luv (sic) Instrumentals.mp3"}}, - {{"Henrietta", "/m/The Fratellis - Costello Music - 01 - Henrietta.mp3"}, - {"Henrietta", "/m/The Fratellis - Costello Music - 01 - Henrietta.flac"}}, + {{"Heat Lines (Tariq Amal Remix)", "/m/GA/Glass Insects - Dreamland Deluxe - 02 - Heat Lines (Tariq Amal Remix).mp3"}, + {"Heat Lines (Tariq Amal Remix)", "/m/GA/02. Heat Lines (Tariq Amal Remix).flac"}}, + {{"Hush (sic) Instrumentals", "/m/Sebanuj/0201 - Hushsic instrumentals.m4a"}, + {"Hush (sic) Instrumentals", "/m/Sebanuj/Sebanuj - Hush(sic) Heptalogy - 01 - Hush (sic) Instrumentals.mp3"}}, + {{"Henrietta Mae", "/m/The Fratellinis - Castello Music - 01 - Henrietta Mae.mp3"}, + {"Henrietta Mae", "/m/The Fratellinis - Castello Music - 01 - Henrietta Mae.flac"}}, } for _, p := range agree { a, b := versionWords(p[0][0], p[0][1]), versionWords(p[1][0], p[1][1]) @@ -113,11 +113,11 @@ func TestWrongSlots(t *testing.T) { copies := func(titles ...string) []slotCopy { out := make([]slotCopy, len(titles)) for i, title := range titles { - out[i] = slotCopy{Title: title, Artist: "Savant", DurationMs: 220000} + out[i] = slotCopy{Title: title, Artist: "Savanta", DurationMs: 220000} } return out } - void := []dbq.MbReleaseTrack{track("Slimewar (Into the Void)", 300000), track("Reach", 281000), track("Void", 220500)} + void := []dbq.MbReleaseTrack{track("Slimeworld (Into the Void)", 300000), track("Reach", 281000), track("Void", 220500)} cases := []struct { name string copies []slotCopy @@ -126,17 +126,17 @@ func TestWrongSlots(t *testing.T) { losers []int ok bool }{ - {"Void: the file is Void's; the other two slots are other songs", copies("Slimewar (into the void)", "Void", "Reach"), void, 1, []int{0, 2}, true}, + {"Void: the file is Void's; the other two slots are other songs", copies("Slimeworld (into the void)", "Void", "Reach"), void, 1, []int{0, 2}, true}, {"no track list", copies("Void", "Reach"), nil, -1, nil, false}, {"a title the track list does not hold", copies("Void", "Bonus"), void, -1, nil, false}, {"Killjoy held twice beside Dreamland's slot", []slotCopy{ - {Title: "Dreamland", Artist: "Fox Stevenson", DurationMs: 167000}, - {Title: "Killjoy", Artist: "Fox Stevenson", DurationMs: 167000}, - {Title: "Killjoy", Artist: "Fox Stevenson", DurationMs: 166000}, + {Title: "Dreamland", Artist: "Lynx Morrison", DurationMs: 167000}, + {Title: "Killjoy", Artist: "Lynx Morrison", DurationMs: 167000}, + {Title: "Killjoy", Artist: "Lynx Morrison", DurationMs: 166000}, }, []dbq.MbReleaseTrack{track("Killjoy", 166500), track("Dreamland", 214000)}, 1, []int{0}, true}, {"two slots fit the file", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 221500)}, -1, nil, false}, {"a slot near but not within the fit", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 226000)}, -1, nil, false}, - {"no slot fits, and every slot is clearly another song's", copies("Reach", "Slimewar (into the void)"), void, -1, []int{0, 1}, true}, + {"no slot fits, and every slot is clearly another song's", copies("Reach", "Slimeworld (into the void)"), void, -1, []int{0, 1}, true}, {"no slot fits, but one is near", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 226000), track("Reach", 281000)}, -1, nil, false}, {"an unknown length counts for nothing", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 0)}, -1, nil, false}, } @@ -149,15 +149,15 @@ func TestWrongSlots(t *testing.T) { } } -// The lengths cannot place a recording filed as several songs (Savant's -// Mortals, cut to each slot's length); what AcoustID calls it can. +// The lengths cannot place a recording filed as several songs (Savanta's +// Immortals, cut to each slot's length); what AcoustID calls it can. func TestNamedCopies(t *testing.T) { track := func(title string, ms int32, rec string) dbq.MbReleaseTrack { return dbq.MbReleaseTrack{Title: title, LengthMs: ms, RecordingMbid: rec} } copies := []slotCopy{ - {Title: "Tormentor", Artist: "The Wombats", DurationMs: 220000}, - {Title: "Record Shop", Artist: "The Wombats", DurationMs: 181000}, + {Title: "Tormentor", Artist: "The Wallabies", DurationMs: 220000}, + {Title: "Record Shop", Artist: "The Wallabies", DurationMs: 181000}, } album := []dbq.MbReleaseTrack{ track("Tormentor", 221000, "rec-tormentor"), track("Record Shop", 180000, "rec-record-shop"), track("Ice Cream", 200000, "rec-ice"), diff --git a/internal/library/duplicate_match_test.go b/internal/library/duplicate_match_test.go index f0d2decf..179e3845 100644 --- a/internal/library/duplicate_match_test.go +++ b/internal/library/duplicate_match_test.go @@ -115,7 +115,7 @@ func TestGroupDuplicates_ExactTier(t *testing.T) { res := groupDuplicates([]fingerprintCandidate{ {ID: "www-01", DurationMs: 215000, StreamSHA256: hash}, {ID: "www-02", DurationMs: 215000, StreamSHA256: hash}, - {ID: "lovesick", DurationMs: 198000, StreamSHA256: []byte("another")}, + {ID: "homesick", DurationMs: 198000, StreamSHA256: []byte("another")}, }, defaultAcousticMaxBitErrorRate) want := []duplicateGroup{{Tier: tierExact, Members: []string{"www-01", "www-02"}}} if !reflect.DeepEqual(res.Groups, want) { diff --git a/internal/library/duplicate_merge.go b/internal/library/duplicate_merge.go index 54f4cd40..291c14cb 100644 --- a/internal/library/duplicate_merge.go +++ b/internal/library/duplicate_merge.go @@ -11,9 +11,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Duplicate merge. @@ -187,7 +187,6 @@ func foldTrackInto( ctx context.Context, tq *dbq.Queries, survivorID, loserID pgtype.UUID, changes *mergeChanges, ) (foldResult, error) { var f foldResult - survivorKey := syncpkg.FormatUUID(survivorID) loserKey := syncpkg.FormatUUID(loserID) n, err := tq.MergeRepointPlayEvents(ctx, dbq.MergeRepointPlayEventsParams{SurvivorID: survivorID, LoserID: loserID}) @@ -206,30 +205,19 @@ func foldTrackInto( if _, err := tq.MergeRepointPlaybackErrors(ctx, dbq.MergeRepointPlaybackErrorsParams{SurvivorID: survivorID, LoserID: loserID}); err != nil { return f, fmt.Errorf("move playback errors: %w", err) } - if _, err := tq.MergeRepointRequests(ctx, dbq.MergeRepointRequestsParams{SurvivorID: survivorID, LoserID: loserID}); err != nil { - return f, fmt.Errorf("move request matches: %w", err) - } playlists, err := tq.MergeRepointPlaylistTracks(ctx, dbq.MergeRepointPlaylistTracksParams{SurvivorID: survivorID, LoserID: loserID}) if err != nil { return f, fmt.Errorf("move playlist entries: %w", err) } f.PlaylistEntries = len(playlists) - for _, pl := range playlists { - plKey := syncpkg.FormatUUID(pl) - changes.playlistDelete(syncpkg.EncodePlaylistTrackID(plKey, loserKey)) - changes.playlistUpsert(syncpkg.EncodePlaylistTrackID(plKey, survivorKey)) - } users, err := tq.MergeCopyGeneralLikes(ctx, dbq.MergeCopyGeneralLikesParams{SurvivorID: survivorID, LoserID: loserID}) if err != nil { return f, fmt.Errorf("move likes: %w", err) } for _, u := range users { - userKey := syncpkg.FormatUUID(u) - f.Likers = append(f.Likers, userKey) - changes.likeDelete(syncpkg.EncodeLikeID(userKey, loserKey)) - changes.likeUpsert(syncpkg.EncodeLikeID(userKey, survivorKey)) + f.Likers = append(f.Likers, syncpkg.FormatUUID(u)) } if _, err := tq.MergeCopyTrackTags(ctx, dbq.MergeCopyTrackTagsParams{SurvivorID: survivorID, LoserID: loserID}); err != nil { @@ -300,10 +288,9 @@ func mergedCopyOf(m dbq.ListDuplicateGroupMergeMembersRow) MergedCopy { } // mergeChanges collects the sync-log entries a merge owes clients' caches, each -// once: a user who liked two removed copies still gets one upsert for the -// survivor. +// once: the removed copies' tracks. type mergeChanges struct { - tracks, likeDeletes, likeUpserts, playlistDeletes, playlistUpserts map[string]struct{} + tracks map[string]struct{} } func addTo(set *map[string]struct{}, id string) { @@ -313,11 +300,7 @@ func addTo(set *map[string]struct{}, id string) { (*set)[id] = struct{}{} } -func (c *mergeChanges) trackDelete(id string) { addTo(&c.tracks, id) } -func (c *mergeChanges) likeDelete(id string) { addTo(&c.likeDeletes, id) } -func (c *mergeChanges) likeUpsert(id string) { addTo(&c.likeUpserts, id) } -func (c *mergeChanges) playlistDelete(id string) { addTo(&c.playlistDeletes, id) } -func (c *mergeChanges) playlistUpsert(id string) { addTo(&c.playlistUpserts, id) } +func (c *mergeChanges) trackDelete(id string) { addTo(&c.tracks, id) } func (c *mergeChanges) log(ctx context.Context, tx pgx.Tx) error { for _, entry := range []struct { @@ -326,10 +309,6 @@ func (c *mergeChanges) log(ctx context.Context, tx pgx.Tx) error { op syncpkg.Op }{ {syncpkg.EntityTrack, c.tracks, syncpkg.OpDelete}, - {syncpkg.EntityLikeTrack, c.likeDeletes, syncpkg.OpDelete}, - {syncpkg.EntityLikeTrack, c.likeUpserts, syncpkg.OpUpsert}, - {syncpkg.EntityPlaylistTrack, c.playlistDeletes, syncpkg.OpDelete}, - {syncpkg.EntityPlaylistTrack, c.playlistUpserts, syncpkg.OpUpsert}, } { if len(entry.ids) == 0 { continue diff --git a/internal/library/duplicate_merge_test.go b/internal/library/duplicate_merge_test.go index 3d9def22..dbf6ca34 100644 --- a/internal/library/duplicate_merge_test.go +++ b/internal/library/duplicate_merge_test.go @@ -13,8 +13,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // mergeFixture is a library with one duplicate pair carrying history on both @@ -32,7 +32,7 @@ type mergeFixture struct { func newMergeFixture(t *testing.T) mergeFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -59,7 +59,7 @@ func newMergeFixture(t *testing.T) mergeFixture { } return tr } - f.remove = upsert("WWW (copy)", f.removePath) + f.remove = upsert("XYZ (copy)", f.removePath) f.other = upsert("Neighbour", filepath.Join(dir, "other.mp3")) mustExec := func(sql string, args ...any) { diff --git a/internal/library/duplicate_resolve.go b/internal/library/duplicate_resolve.go index a41c0480..17bc1e1f 100644 --- a/internal/library/duplicate_resolve.go +++ b/internal/library/duplicate_resolve.go @@ -11,41 +11,32 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Duplicate resolver. // -// The sweep proposes duplicate groups; the resolver decides what each one is -// and settles the ones that are safe to settle without asking. Minstrel is the -// only program writing the library, so no copy is kept because something else -// depends on it. What decides is what the copies are: +// The sweep proposes duplicate groups; the resolver decides what each one is. +// It never removes a file: other programs file music into the library too, +// and a copy one of them filed is not Minstrel's to delete. Removing a copy +// is an admin's merge. What a pass does on its own changes only Minstrel's +// database: // -// - On one album, a song is held once: the extra copies are merged into the -// best by ProposeSurvivor. -// - Across releases, each copy belongs to its own release (a single and its -// album): nothing is removed, and the copies are linked as one song. An -// album holding the song twice among them still holds it once: its extra -// copies are merged into its best. -// - Except that a video rip is no release's copy. When every copy but one is -// a rip, across releases or under another title, the rips are merged into -// the one that is not. +// - Copies of one song, on one album or across releases (a single and its +// album), are linked as one song: a like on one is a like on all, and +// the Liked list, shuffle and the mixes count the song once. A group an +// admin may want to thin (one album holding the song twice, or video rips +// beside a real copy) also waits for them. +// - A copy named like a video rip is held back from radio and the mixes. // - Two versions of a song on one album that sound alike are not duplicates: // the group is dismissed (duplicate_settle.go). // - One file filling several of an album's track slots: MusicBrainz's track -// lengths say which slot it belongs to, or AcoustID which song it is when -// each copy was cut to its own slot's length, and the copies in the other -// slots are removed so the album is fetched again (duplicate_settle.go). +// lengths, or AcoustID, say which song the recording is, and the group's +// note tells the admin who settles it (duplicate_settle.go). // - Anything else waits for an admin. const ( - // resolveMergeCap bounds the merges one pass makes. The first pass after - // deploy meets the whole backlog; a cap spreads it over a few hours, each - // pass short. - resolveMergeCap = 200 // duplicateResolveTick is how often the worker runs a pass. duplicateResolveTick = time.Hour // scanWaitRetry is how soon a pass put off for a running scan is tried @@ -55,15 +46,13 @@ const ( // DuplicateResolveResult tallies one pass. type DuplicateResolveResult struct { - Groups int - Classes map[DuplicateClass]int - Merged int - MergeFailed int - // SongsLinked counts cross-release groups newly linked as one song. + Groups int + Classes map[DuplicateClass]int + // SongsLinked counts groups newly linked as one song. SongsLinked int - // Dismissed counts groups of distinct versions dismissed; WrongFiles the - // copies removed from track slots that were not theirs. - Dismissed, WrongFiles int + // Dismissed counts groups of distinct versions dismissed; SlotsNamed the + // one-album mismatches whose recording the pass could name. + Dismissed, SlotsNamed int // HeldBack counts tracks newly held back from radio and the mixes as video // rips; Released counts held-back tracks whose name no longer says so. HeldBack, Released int64 @@ -107,24 +96,29 @@ func (g *resolveGroup) lone() int { return at } -// mergePlan says whether the resolver may merge the group on its own, and into -// which copy (an index into members; -1 means ProposeSurvivor decides). -func mergePlan(g *resolveGroup) (ok bool, survivor int) { +// wantsAdmin says whether a group waits for an admin to decide which copies +// to keep: every group but distinct versions, and copies on separate +// releases with no rip among them, which are complete once linked. +func (g *resolveGroup) wantsAdmin() bool { switch g.class { - case ClassSameRelease: - return true, -1 + case ClassDistinct: + return false case ClassCrossRelease: - if i := g.lone(); i >= 0 { - return true, i - } + return g.lone() >= 0 } - return false, -1 + return true } // TrackListFetcher reads a release group's releases and track lists from -// MusicBrainz into the catalogue (catalogue.Service.RefreshReleaseGroup). +// MusicBrainz into the catalogue (catalogue.Service.RefreshReleaseGroup). It +// returns ErrLookupOff while an admin has switched the lookup off. type TrackListFetcher func(ctx context.Context, releaseGroupMBID string) error +// ErrLookupOff is a TrackListFetcher's answer while an admin has switched +// MusicBrainz track lists off. The pass then decides from the track lists +// already read, without asking again until the next pass. +var ErrLookupOff = errors.New("an admin has switched this lookup off") + // RecordingIdentifier asks AcoustID which recordings a file may be // (AcoustIDLookupWorker.IdentifyRecordings). type RecordingIdentifier func(ctx context.Context, path string) ([]string, error) @@ -144,14 +138,14 @@ type ResolveSources struct { // with it off, the pass only classifies. It decides from what the library and // catalogue hold; ResolveDuplicatesWith may also ask MusicBrainz and AcoustID. func ResolveDuplicates( - ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, act bool, + ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, act bool, ) (DuplicateResolveResult, error) { - return ResolveDuplicatesWith(ctx, pool, logger, dataDir, act, ResolveSources{}) + return ResolveDuplicatesWith(ctx, pool, logger, act, ResolveSources{}) } // ResolveDuplicatesWith is ResolveDuplicates that may ask src. func ResolveDuplicatesWith( - ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, act bool, src ResolveSources, + ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, act bool, src ResolveSources, ) (DuplicateResolveResult, error) { if logger == nil { logger = slog.Default() @@ -170,6 +164,9 @@ func ResolveDuplicatesWith( g.classify() res.Classes[g.class]++ } + if act { + res.SlotsNamed = nameWrongSlots(ctx, pool, logger, groups, src) + } if err := writeResolveVerdicts(ctx, q, groups); err != nil { return res, err } @@ -186,188 +183,30 @@ func ResolveDuplicatesWith( return res, fmt.Errorf("release renamed tracks: %w", err) } - // Merges before links, so a rip merged away is not linked first. - merged := map[pgtype.UUID]bool{} - var mergedNames []string - for _, g := range groups { - if res.Merged >= resolveMergeCap { - break - } - if ctx.Err() != nil { - return res, ctx.Err() - } - ok, survivor := mergePlan(g) - if !ok { - continue - } - if err := autoMerge(ctx, pool, logger, dataDir, g, survivor); err != nil { - res.MergeFailed++ - logger.Warn("duplicate resolve: merge failed", "group_id", syncpkg.FormatUUID(g.id), "err", err) - continue - } - merged[g.id] = true - res.Merged++ - if len(mergedNames) < notifyItems { - mergedNames = append(mergedNames, TrackLabel(g.members[0].ArtistName, g.members[0].Title)) - } - } - - folded, foldedNames := foldAlbumCopies(ctx, pool, logger, dataDir, groups, merged, resolveMergeCap-res.Merged) - res.Merged += folded - mergedNames = append(mergedNames, foldedNames...) - - res.Dismissed = dismissDistinct(ctx, pool, logger, groups, merged) - wrong, names := settleWrongSlots(ctx, pool, logger, groups, merged, src) - res.WrongFiles = wrong - mergedNames = append(mergedNames, names...) - - linked, err := linkCrossRelease(ctx, pool, logger, groups, merged) + settled := map[pgtype.UUID]bool{} + res.Dismissed = dismissDistinct(ctx, pool, logger, groups, settled) + linked, err := linkSongs(ctx, pool, logger, groups) res.SongsLinked = linked if err != nil { return res, err } - - if settledCopies := res.Merged + res.WrongFiles; settledCopies > 0 { - notifyAdmins(ctx, notifications.KindDuplicatesResolved, notifications.Payload{ - Count: int64(settledCopies), Items: mergedNames[:min(len(mergedNames), notifyItems)], - }) - } - notifyNewForReview(ctx, groups, merged) + notifyNewForReview(ctx, groups, settled) return res, nil } -// foldAlbumCopies merges, in each cross-release group, the extra copies one -// album holds of the song into the best of that album's copies: the one that is -// not a video rip when only one is not, else ProposeSurvivor's choice. Copies -// whose title or file name name different versions (versionWords) are not -// folded, even when they carry one title tag: a song and its clean version are -// both kept. The copies on other releases stay and are linked as one song. At -// most budget copies go. It returns how many went and the songs they were, and -// drops them from their groups. -func foldAlbumCopies( - ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, - groups []*resolveGroup, merged map[pgtype.UUID]bool, budget int, -) (int, []string) { - n := 0 - var names []string - for _, g := range groups { - if g.class != ClassCrossRelease || merged[g.id] || ctx.Err() != nil || n >= budget { - continue - } - onAlbum := map[string][]int{} - for i, m := range g.members { - k := syncpkg.FormatUUID(m.AlbumID) + "\x00" + MatchTitleKey(m.Title, m.ArtistName) + - "\x00" + versionWords(m.Title, m.FilePath) - onAlbum[k] = append(onAlbum[k], i) - } - gone := map[int]bool{} - for _, copies := range onAlbum { - if len(copies) < 2 { - continue - } - keep, reason := albumCopySurvivor(g, copies) - for _, i := range copies { - if i == keep || n >= budget { - continue - } - if err := foldAlbumCopy(ctx, pool, logger, dataDir, g, i, keep, reason); err != nil { - logger.Warn("duplicate resolve: merging an album's extra copy failed", - "group_id", syncpkg.FormatUUID(g.id), "path", g.members[i].FilePath, "err", err) - continue - } - gone[i] = true - n++ - if len(names) < notifyItems { - names = append(names, TrackLabel(g.members[i].ArtistName, g.members[i].Title)) - } - } - } - if len(gone) > 0 { - kept := g.members[:0:0] - for i, m := range g.members { - if !gone[i] { - kept = append(kept, m) - } - } - g.members = kept - } - } - return n, names -} - -// albumCopySurvivor picks which of one album's copies (indexes into the -// group's members) to keep, and why. -func albumCopySurvivor(g *resolveGroup, copies []int) (int, string) { - notRip := -1 - for _, i := range copies { - if isRip(g.members[i]) { - continue - } - if notRip >= 0 { - notRip = -1 - break - } - notRip = i - } - if notRip >= 0 { - return notRip, "the copy that is not a video rip" - } - all := survivorCandidates(g) - cands := make([]SurvivorCandidate, len(copies)) - for j, i := range copies { - cands[j] = all[i] - } - id, reason := ProposeSurvivor(cands) - for _, i := range copies { - if all[i].TrackID == id { - return i, reason - } - } - return copies[0], reason -} - -// foldAlbumCopy replaces one of an album's copies with the copy kept, history -// and all, and records it as the resolver's merge. -func foldAlbumCopy( - ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, - g *resolveGroup, gone, keep int, reason string, -) error { - from, into := g.members[gone], g.members[keep] - moved, err := ReplaceTrack(ctx, pool, logger, dataDir, from.TrackID, into.TrackID) - if err != nil { - return err - } - audit.WriteOrLog(ctx, pool, logger, pgtype.UUID{}, pgtype.UUID{}, audit.ActionDuplicateMerge, map[string]any{ - "automatic": true, - "group_id": syncpkg.FormatUUID(g.id), - "tier": g.tier, - "class": string(g.class), - "survivor_track_id": syncpkg.FormatUUID(into.TrackID), - "survivor_path": into.FilePath, - "survivor_reason": reason + "; the album held the song twice", - "removed": []map[string]string{ - {"track_id": syncpkg.FormatUUID(from.TrackID), "file_path": from.FilePath}, - }, - "moved": map[string]any{ - "play_events": moved.PlayEvents, "skip_events": moved.SkipEvents, - "likes": moved.Likes, "playlist_entries": moved.PlaylistEntries, - }, - }) - return nil -} - -// linkCrossRelease links each cross-release group's copies as one song: a -// like on one is a like on all, and the Liked list, shuffle and the -// mixes count the song once. A group the pass merged has nothing left to link. -// Linking an already-linked group changes nothing, -// so this runs every pass; likes are shared only when a link is new, since a -// like made after it reaches every copy as it is made. -func linkCrossRelease( - ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, merged map[pgtype.UUID]bool, +// linkSongs links each group of one song's copies as one song: a like on +// one is a like on all, and the Liked list, shuffle and the mixes count the +// song once. That holds for copies on one album as for copies across +// releases; which copies to keep is the admin's merge. Linking an +// already-linked group changes nothing, so this runs every pass; likes are +// shared only when a link is new, since a like made after it reaches every +// copy as it is made. +func linkSongs( + ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, ) (int, error) { linked := 0 for _, g := range groups { - if g.class != ClassCrossRelease || merged[g.id] { + if g.class != ClassCrossRelease && g.class != ClassSameRelease { continue } if ctx.Err() != nil { @@ -405,17 +244,9 @@ func linkSong(ctx context.Context, pool *pgxpool.Pool, ids []pgtype.UUID) (bool, if link.Moved == 0 { return false, nil } - added, err := tq.ShareSongLikes(ctx, link.SongKey) - if err != nil { + if _, err := tq.ShareSongLikes(ctx, link.SongKey); err != nil { return false, fmt.Errorf("share likes: %w", err) } - likeIDs := make([]string, len(added)) - for i, a := range added { - likeIDs[i] = syncpkg.EncodeLikeID(syncpkg.FormatUUID(a.UserID), syncpkg.FormatUUID(a.TrackID)) - } - if err := syncpkg.LogChanges(ctx, tx, syncpkg.EntityLikeTrack, likeIDs, syncpkg.OpUpsert); err != nil { - return false, fmt.Errorf("log shared likes: %w", err) - } return true, tx.Commit(ctx) } @@ -452,10 +283,13 @@ func (g *resolveGroup) classify() { // to say. func resolveNote(g *resolveGroup) string { switch g.class { + case ClassSameRelease: + return "The album holds this song more than once. The copies count as one song; merge to keep one." case ClassCrossRelease: if g.lone() < 0 { return "Each copy belongs to its own release, so none is removed; they count as one song." } + return "Every copy but one is named like a video rip. They count as one song; merge to keep the one that is not." case ClassMismatch: return "One recording fills several of this album's track slots, and MusicBrainz's track lengths could not say which is its own." } @@ -478,68 +312,10 @@ func writeResolveVerdicts(ctx context.Context, q *dbq.Queries, groups []*resolve return nil } -// survivorCandidates builds what ProposeSurvivor weighs for a group's copies. -func survivorCandidates(g *resolveGroup) []SurvivorCandidate { - cands := make([]SurvivorCandidate, len(g.members)) - for i, m := range g.members { - cands[i] = SurvivorCandidate{ - TrackID: syncpkg.FormatUUID(m.TrackID), - FileFormat: m.FileFormat, - FileSize: m.FileSize, - AddedAt: m.AddedAt.Time, - TagFit: TagFitScore(m.TrackNumber != nil, m.PositionClash, m.FilePath, m.HasMbid), - } - } - return cands -} - -// autoMerge merges one group into the copy at index survivor, or the copy -// ProposeSurvivor picks when survivor is -1, and records the merge as the -// resolver's. -func autoMerge( - ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, g *resolveGroup, survivor int, -) error { - survivorKey, reason := ProposeSurvivor(survivorCandidates(g)) - if survivor >= 0 { - survivorKey, reason = syncpkg.FormatUUID(g.members[survivor].TrackID), "the copy that is not a video rip" - } - var survivorID pgtype.UUID - if err := survivorID.Scan(survivorKey); err != nil { - return fmt.Errorf("parse survivor id: %w", err) - } - res, err := MergeDuplicateGroup(ctx, pool, logger, dataDir, g.id, survivorID) - if err != nil { - return err - } - if err := dbq.New(pool).MarkDuplicateGroupResolvedAutomatically(ctx, g.id); err != nil { - logger.Warn("duplicate resolve: marking the merge automatic failed", "group_id", syncpkg.FormatUUID(g.id), "err", err) - } - removed := make([]map[string]string, 0, len(res.Removed)) - for _, c := range res.Removed { - removed = append(removed, map[string]string{"track_id": syncpkg.FormatUUID(c.TrackID), "file_path": c.FilePath}) - } - audit.WriteOrLog(ctx, pool, logger, pgtype.UUID{}, pgtype.UUID{}, audit.ActionDuplicateMerge, map[string]any{ - "automatic": true, - "group_id": syncpkg.FormatUUID(g.id), - "tier": res.Tier, - "class": string(g.class), - "survivor_track_id": syncpkg.FormatUUID(res.Survivor.TrackID), - "survivor_path": res.Survivor.FilePath, - "survivor_reason": reason, - "removed": removed, - "moved": map[string]any{ - "play_events": res.PlayEvents, "skip_events": res.SkipEvents, - "likes": res.Likes, "playlist_entries": res.PlaylistEntries, - }, - }) - return nil -} - // DuplicateResolveWorker runs a resolver pass every hour. type DuplicateResolveWorker struct { pool *pgxpool.Pool logger *slog.Logger - dataDir string settings *FingerprintSettingsService src ResolveSources tick time.Duration @@ -548,10 +324,10 @@ type DuplicateResolveWorker struct { // NewDuplicateResolveWorker builds a worker with the production cadence. src // is what a pass may ask beyond the library. func NewDuplicateResolveWorker( - pool *pgxpool.Pool, logger *slog.Logger, dataDir string, settings *FingerprintSettingsService, src ResolveSources, + pool *pgxpool.Pool, logger *slog.Logger, settings *FingerprintSettingsService, src ResolveSources, ) *DuplicateResolveWorker { return &DuplicateResolveWorker{ - pool: pool, logger: logger, dataDir: dataDir, settings: settings, src: src, tick: duplicateResolveTick, + pool: pool, logger: logger, settings: settings, src: src, tick: duplicateResolveTick, } } @@ -575,8 +351,8 @@ func (w *DuplicateResolveWorker) Run(ctx context.Context) { } } -// tickOnce contains one pass so nothing it does can stop the next tick (rule -// 157). It reports whether the pass was put off for a running scan. +// tickOnce contains one pass so nothing it does can stop the next tick. It +// reports whether the pass was put off for a running scan. func (w *DuplicateResolveWorker) tickOnce(ctx context.Context) (waitForScan bool) { defer func() { if r := recover(); r != nil { @@ -595,26 +371,32 @@ func (w *DuplicateResolveWorker) tickOnce(ctx context.Context) (waitForScan bool } return false } - // A scan in flight has listed the files it will reconcile: a copy removed - // now is marked present again when it does. A run past StuckScanThreshold - // is a dead one. - run, err := q.GetInFlightScanRun(ctx) + // A pass waits out a whole scan run, whose later stages re-read files + // too. A run past StuckScanThreshold is a dead one. + running, err := scanRunning(ctx, q) switch { - case err == nil && time.Since(run.StartedAt.Time) <= StuckScanThreshold: - return true - case err != nil && !errors.Is(err, pgx.ErrNoRows): + case err != nil: if ctx.Err() == nil { w.logger.Warn("duplicate resolve: scan check failed", "err", err) } return false + case running: + return true } - res, err := ResolveDuplicatesWith(ctx, w.pool, w.logger, w.dataDir, w.settings.Get().AutoResolve, w.src) + // A run can begin after the check above, and a watcher batch has no run + // at all: filesGate keeps either from rewriting tracks while this pass + // decides from them. + if !filesGate.tryAcquire() { + return true + } + defer filesGate.release() + res, err := ResolveDuplicatesWith(ctx, w.pool, w.logger, w.settings.Get().AutoResolve, w.src) if err != nil && ctx.Err() == nil { w.logger.Warn("duplicate resolve: pass failed", "err", err) } w.logger.Info("duplicate resolve complete", - "groups", res.Groups, "merged", res.Merged, "merge_failed", res.MergeFailed, - "songs_linked", res.SongsLinked, "dismissed", res.Dismissed, "wrong_files", res.WrongFiles, + "groups", res.Groups, "songs_linked", res.SongsLinked, "dismissed", res.Dismissed, + "slots_named", res.SlotsNamed, "held_back", res.HeldBack, "released", res.Released) return false } diff --git a/internal/library/duplicate_resolve_test.go b/internal/library/duplicate_resolve_test.go index 5cd41a74..fc39e324 100644 --- a/internal/library/duplicate_resolve_test.go +++ b/internal/library/duplicate_resolve_test.go @@ -6,16 +6,18 @@ import ( "log/slog" "os" "path/filepath" + "strings" "testing" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) -// resolveFixture is the Humanz shape: one album, one song twice, both copies on +// resolveFixture is the Mammalz shape: one album, one song twice, both copies on // disk under an artist/album folder, in one pending exact-tier group. type resolveFixture struct { pool *pgxpool.Pool @@ -26,16 +28,16 @@ type resolveFixture struct { func newResolveFixture(t *testing.T) resolveFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) - dir := filepath.Join(t.TempDir(), "Gorillaz", "Humanz (2017)") + dir := filepath.Join(t.TempDir(), "Plastic Apes", "Mammalz (2017)") if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } f := resolveFixture{pool: pool} - f.cleanPath = filepath.Join(dir, "Gorillaz - Humanz - 03 - Saturnz Barz.mp3") - f.ripPath = filepath.Join(dir, "Gorillaz - Humanz - 03 - Saturnz Barz (Official Video).mp3") + f.cleanPath = filepath.Join(dir, "Plastic Apes - Mammalz - 03 - Neptunez Barz.mp3") + f.ripPath = filepath.Join(dir, "Plastic Apes - Mammalz - 03 - Neptunez Barz (Official Video).mp3") for _, p := range []string{f.cleanPath, f.ripPath} { if err := os.WriteFile(p, []byte("audio"), 0o644); err != nil { t.Fatal(err) @@ -45,7 +47,7 @@ func newResolveFixture(t *testing.T) resolveFixture { var artist dbq.Artist f.clean, album, artist = seedTrack(t, pool, f.cleanPath) rip, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ - Title: "Saturnz Barz (Official Video)", AlbumID: album.ID, ArtistID: artist.ID, + Title: "Neptunez Barz (Official Video)", AlbumID: album.ID, ArtistID: artist.ID, DurationMs: 1000, FilePath: f.ripPath, FileSize: 100, FileFormat: "mp3", }) if err != nil { @@ -58,7 +60,7 @@ func newResolveFixture(t *testing.T) resolveFixture { t.Fatalf("exec %q: %v", sql, err) } } - exec(`UPDATE tracks SET title = 'Saturnz Barz' WHERE id = $1`, f.clean.ID) + exec(`UPDATE tracks SET title = 'Neptunez Barz' WHERE id = $1`, f.clean.ID) if err := pool.QueryRow(ctx, `INSERT INTO duplicate_groups (member_key, tier) VALUES ('resolve-fixture', 'exact') RETURNING id`, ).Scan(&f.groupID); err != nil { @@ -94,44 +96,47 @@ func autoMergeAudit(t *testing.T, pool *pgxpool.Pool, groupID pgtype.UUID) (n in return n, reason } -// One album holding a song twice: the extra copy goes, the copy whose name and -// tags fit the album stays, and the merge is recorded as the resolver's: -// Minstrel is the only program writing the library. -func TestResolveDuplicates_MergesASameReleaseCopy_Integration(t *testing.T) { +// One album holding a song twice: the pass removes neither file, since +// another program may have filed either. It links the copies as one song and +// leaves the group for an admin to merge. +func TestResolveDuplicates_LinksASameReleaseCopyAndRemovesNothing_Integration(t *testing.T) { f := newResolveFixture(t) - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) + res, err := ResolveDuplicates(context.Background(), f.pool, nil, true) if err != nil { t.Fatalf("resolve: %v", err) } - if res.Merged != 1 || res.Classes[ClassSameRelease] != 1 { - t.Fatalf("result = %+v, want the same-release group merged", res) + if res.Classes[ClassSameRelease] != 1 || res.SongsLinked != 1 { + t.Fatalf("result = %+v, want the same-release group linked as one song", res) } - if exists(f.ripPath) || !exists(f.cleanPath) { - t.Errorf("rip exists=%v clean exists=%v; want only the clean copy left", exists(f.ripPath), exists(f.cleanPath)) + if !exists(f.ripPath) || !exists(f.cleanPath) { + t.Errorf("rip exists=%v clean exists=%v; want both files left in place", exists(f.ripPath), exists(f.cleanPath)) } - status, class, _, auto := f.group(t) - if status != "merged" || class == nil || *class != string(ClassSameRelease) || !auto { - t.Errorf("group = (%s, %v, auto=%v), want merged same_release by the resolver", status, class, auto) + status, class, note, auto := f.group(t) + if status != "pending" || class == nil || *class != string(ClassSameRelease) || auto || note == nil { + t.Errorf("group = (%s, %v, note %v, auto=%v), want a pending same_release group with a note", status, class, note, auto) } - if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 1 { - t.Errorf("automatic merge audit rows = %d, want 1", n) + if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 0 { + t.Errorf("automatic merge audit rows = %d, want none", n) } } -// With auto-resolve off, the pass classifies and removes nothing. +// With auto-resolve off, the pass classifies, and links and removes nothing. func TestResolveDuplicates_ClassifiesOnlyWithoutPermission_Integration(t *testing.T) { f := newResolveFixture(t) - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", false) + res, err := ResolveDuplicates(context.Background(), f.pool, nil, false) if err != nil { t.Fatal(err) } - if res.Merged != 0 || !exists(f.ripPath) { - t.Errorf("merged %d", res.Merged) + if res.SongsLinked != 0 || !exists(f.ripPath) || !exists(f.cleanPath) { + t.Errorf("result %+v; want nothing linked or removed", res) } status, class, _, _ := f.group(t) if status != "pending" || class == nil || *class != string(ClassSameRelease) { t.Errorf("group = (%s, %v), want pending and classified", status, class) } + if keys := songKeys(t, dbq.New(f.pool), f.clean.ID, f.rip.ID); keys[0] == keys[1] { + t.Error("linked as one song with auto-resolve off") + } } // crossReleaseRipFixture is a video rip on one release with the clean copy on @@ -145,14 +150,14 @@ type crossReleaseRipFixture struct { func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) root := t.TempDir() f := crossReleaseRipFixture{pool: pool} - f.cleanPath = filepath.Join(root, "Gorillaz", "Demon Days (2005)", "06 - Feel Good Inc.mp3") - f.ripPath = filepath.Join(root, "Gorillaz", "Feel Good Inc (2005)", "01 - Feel Good Inc. (Official Video).mp3") - artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Gorillaz", SortName: "Gorillaz"}) + f.cleanPath = filepath.Join(root, "Plastic Apes", "Ghost Nights (2005)", "06 - Feel Fine Ltd.mp3") + f.ripPath = filepath.Join(root, "Plastic Apes", "Feel Fine Ltd (2005)", "01 - Feel Fine Ltd. (Official Video).mp3") + artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Plastic Apes", SortName: "Plastic Apes"}) if err != nil { t.Fatal(err) } @@ -177,8 +182,8 @@ func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture { } return tr } - f.clean = track("Demon Days", "Feel Good Inc.", f.cleanPath) - f.rip = track("Feel Good Inc.", "Feel Good Inc. (Official Video)", f.ripPath) + f.clean = track("Ghost Nights", "Feel Fine Ltd.", f.cleanPath) + f.rip = track("Feel Fine Ltd.", "Feel Fine Ltd. (Official Video)", f.ripPath) if err := pool.QueryRow(ctx, `INSERT INTO duplicate_groups (member_key, tier) VALUES ('cross-rip', 'acoustic') RETURNING id`, ).Scan(&f.groupID); err != nil { @@ -192,80 +197,61 @@ func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture { return f } -// A video rip on one release with the clean copy on another: the rip is no -// release's copy, so it goes and the album cut stays. -func TestResolveDuplicates_MergesARipAcrossReleases_Integration(t *testing.T) { - f := newCrossReleaseRipFixture(t) - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) - if err != nil { - t.Fatal(err) - } - if res.Classes[ClassCrossRelease] != 1 || res.Merged != 1 { - t.Fatalf("classes %v, merged %d; want the cross-release group merged", res.Classes, res.Merged) - } - if exists(f.ripPath) || !exists(f.cleanPath) { - t.Errorf("rip exists %v, clean exists %v; want only the clean copy", exists(f.ripPath), exists(f.cleanPath)) - } - if _, reason := autoMergeAudit(t, f.pool, f.groupID); reason != "the copy that is not a video rip" { - t.Errorf("survivor reason %q, want the rip rule", reason) - } -} - -// Copies on two releases that are both clean each belong to their release: -// nothing is removed, and they are linked as one song. A rip an admin -// marked fine counts as clean. -func TestResolveDuplicates_KeepsCleanCopiesOnTwoReleases_Integration(t *testing.T) { - for name, prepare := range map[string]func(f crossReleaseRipFixture) (string, []any){ - "renamed": func(f crossReleaseRipFixture) (string, []any) { - return `UPDATE tracks SET title = 'Feel Good Inc.', file_path = $2 WHERE id = $1`, - []any{f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Good Inc.mp3")} - }, - "kept as fine": func(f crossReleaseRipFixture) (string, []any) { +// Copies on separate releases (an album cut and the same song's single) are +// linked as one song and every file stays. When all but one copy is named +// like a video rip, the group's note asks an admin to merge; when every copy +// is clean (named cleanly, kept as fine by an admin, or one recording under +// two titles), each belongs to its release and the note says none is removed. +func TestResolveDuplicates_LinksCopiesAcrossReleasesAndRemovesNothing_Integration(t *testing.T) { + const ripNote, cleanNote = "named like a video rip", "none is removed" + for _, tc := range []struct { + name string + prepare func(f crossReleaseRipFixture) (string, []any) // nil: the fixture as built + wantNote string + }{ + {"a rip beside the clean copy", nil, ripNote}, + {"the rip renamed", func(f crossReleaseRipFixture) (string, []any) { + return `UPDATE tracks SET title = 'Feel Fine Ltd.', file_path = $2 WHERE id = $1`, + []any{f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Fine Ltd.mp3")} + }, cleanNote}, + {"the rip kept as fine", func(f crossReleaseRipFixture) (string, []any) { return `UPDATE tracks SET source_verdict = 'fine' WHERE id = $1`, []any{f.rip.ID} - }, + }, cleanNote}, + // A later release retitled the recording; identical audio. + {"one recording under two titles", func(f crossReleaseRipFixture) (string, []any) { + return `WITH g AS (UPDATE duplicate_groups SET tier = 'exact' WHERE id = $3) + UPDATE tracks SET title = 'DARE', file_path = $2 WHERE id = $1`, + []any{f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - DARE.mp3"), f.groupID} + }, cleanNote}, } { - t.Run(name, func(t *testing.T) { + t.Run(tc.name, func(t *testing.T) { f := newCrossReleaseRipFixture(t) - sql, args := prepare(f) - if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil { - t.Fatal(err) + if tc.prepare != nil { + sql, args := tc.prepare(f) + if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil { + t.Fatal(err) + } } - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) + res, err := ResolveDuplicates(context.Background(), f.pool, nil, true) if err != nil { t.Fatal(err) } - if res.Merged != 0 || !exists(f.ripPath) { - t.Errorf("merged %d; want both copies kept", res.Merged) + if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 { + t.Fatalf("result %+v; want the cross-release group linked as one song", res) } - if res.SongsLinked != 1 { - t.Errorf("linked %d, want the pair linked as one song", res.SongsLinked) + if !exists(f.ripPath) || !exists(f.cleanPath) { + t.Errorf("rip exists %v, clean exists %v; want both files left in place", exists(f.ripPath), exists(f.cleanPath)) + } + if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, tc.wantNote) { + t.Errorf("note %q, want it to say %q", note, tc.wantNote) + } + if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 0 { + t.Errorf("automatic merge audit rows = %d, want none", n) } }) } } -// Identical audio under two titles on two albums, neither a rip: a later -// release retitled the recording ("F.O.D." and "F.O.D. (live)"). Each copy -// belongs to its release, so nothing is removed and they count as one song. -func TestResolveDuplicates_LinksOneRecordingUnderTwoTitles_Integration(t *testing.T) { - f := newCrossReleaseRipFixture(t) - ctx := context.Background() - if _, err := f.pool.Exec(ctx, `UPDATE duplicate_groups SET tier = 'exact' WHERE id = $1`, f.groupID); err != nil { - t.Fatal(err) - } - if _, err := f.pool.Exec(ctx, `UPDATE tracks SET title = 'DARE', file_path = $2 WHERE id = $1`, - f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - DARE.mp3")); err != nil { - t.Fatal(err) - } - res, err := ResolveDuplicates(ctx, f.pool, nil, "", true) - if err != nil { - t.Fatal(err) - } - if res.Classes[ClassCrossRelease] != 1 || res.Merged != 0 || res.SongsLinked != 1 { - t.Fatalf("classes %v, merged %d, linked %d; want the pair linked and kept", res.Classes, res.Merged, res.SongsLinked) - } -} - // oneAlbumFixture is one album holding two tracks in one pending group, each // with a file on disk. type oneAlbumFixture struct { @@ -279,10 +265,10 @@ type oneAlbumFixture struct { func newOneAlbumFixture(t *testing.T, tier, titleA, titleB string) oneAlbumFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) - dir := filepath.Join(t.TempDir(), "Savant", "Void") + dir := filepath.Join(t.TempDir(), "Savanta", "Void") if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } @@ -331,12 +317,12 @@ func auditCount(t *testing.T, pool *pgxpool.Pool, action string, groupID pgtype. // Two versions of a song on one album that sound alike are not duplicates: // the group is dismissed and both files stay. func TestResolveDuplicates_DismissesTwoVersionsOfASong_Integration(t *testing.T) { - f := newOneAlbumFixture(t, "acoustic", "Lovesick", "Lovesick (Instrumental)") - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) + f := newOneAlbumFixture(t, "acoustic", "Homesick", "Homesick (Instrumental)") + res, err := ResolveDuplicates(context.Background(), f.pool, nil, true) if err != nil { t.Fatal(err) } - if res.Dismissed != 1 || res.Merged != 0 || !exists(f.aPath) || !exists(f.bPath) { + if res.Dismissed != 1 || !exists(f.aPath) || !exists(f.bPath) { t.Fatalf("result %+v; want the group dismissed and both files kept", res) } if status, _, _, auto := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "dismissed" || !auto { @@ -377,10 +363,32 @@ func seedTrackList(t *testing.T, pool *pgxpool.Pool, album dbq.Album, songs map[ } } +// noteOf is a group's resolve note, or "" when it has none. +func noteOf(t *testing.T, pool *pgxpool.Pool, groupID pgtype.UUID) string { + t.Helper() + _, _, note, _ := (resolveFixture{pool: pool, groupID: groupID}).group(t) + if note == nil { + return "" + } + return *note +} + +// settleKeeping settles a wrong slot as an admin would, keeping the copy at +// keep. +func settleKeeping(t *testing.T, f oneAlbumFixture, keep pgtype.UUID) WrongSlotResult { + t.Helper() + res, err := SettleWrongSlot(context.Background(), f.pool, nil, f.groupID, keep, pgtype.UUID{}) + if err != nil { + t.Fatalf("settle: %v", err) + } + return res +} + // One recording in two slots of an album: MusicBrainz says Void is as long as -// the file and Reach is a minute longer, so the copy in Reach's slot goes. Its -// track stays, marked missing, for the album to be fetched again. -func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testing.T) { +// the file and Reach is a minute longer. The pass removes nothing; it names +// Void in the group's note. Settled with that copy, the copy in Reach's slot +// goes, and its track stays, marked missing, until a good copy arrives. +func TestResolveDuplicates_NamesTheSongOfACopyInAnotherSongsSlot_Integration(t *testing.T) { f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 281000}) // The wrong file is Void's recording, so it carries Void's MBID. @@ -388,18 +396,25 @@ func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testi `UPDATE tracks SET mbid = 'rec-void', mbid_source = 'tag' WHERE id = ANY($1)`, []pgtype.UUID{f.a.ID, f.b.ID}); err != nil { t.Fatal(err) } - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) + res, err := ResolveDuplicates(context.Background(), f.pool, nil, true) if err != nil { t.Fatal(err) } + if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("result %+v, void exists %v, reach exists %v; want Void named and both files kept", + res, exists(f.aPath), exists(f.bPath)) + } + if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "\u201cVoid\u201d") { + t.Errorf("note %q, want it to name Void", note) + } + settleKeeping(t, f, f.a.ID) // Folded by that MBID into the copy kept, the slot would never be wanted // back. if pairs, err := PairMissingTracks(context.Background(), f.pool, nil); err != nil || pairs.Folded() != 0 { t.Fatalf("missing-pair pass = %+v, %v; want the emptied slot left alone", pairs, err) } - if res.WrongFiles != 1 || !exists(f.aPath) || exists(f.bPath) { - t.Fatalf("result %+v, void exists %v, reach exists %v; want only Reach's copy removed", - res, exists(f.aPath), exists(f.bPath)) + if !exists(f.aPath) || exists(f.bPath) { + t.Fatalf("void exists %v, reach exists %v; want only Reach's copy removed", exists(f.aPath), exists(f.bPath)) } var missing bool if err := f.pool.QueryRow(context.Background(), @@ -409,8 +424,8 @@ func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testi if !missing { t.Error("Reach's track is not marked missing, so nothing will fetch it again") } - if status, _, _, auto := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" || !auto { - t.Errorf("group = (%s, auto=%v), want settled by the resolver", status, auto) + if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" { + t.Errorf("group = %s, want settled", status) } if n := auditCount(t, f.pool, "duplicate_wrong_file", f.groupID); n != 1 { t.Errorf("wrong-file audit rows = %d, want 1", n) @@ -418,9 +433,9 @@ func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testi } // A slot emptied of another song's file folds into a copy of its own song the -// album already holds (Savant's VOID DLC "Weeper" beside Void's). A copy under +// album already holds (Savanta's VOID DLC "Sleeper" beside Void's). A copy under // the title that is not as long as the song is another song: the slot waits for -// a copy fetched again, and folds into that. +// a good copy, and folds into that. func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *testing.T) { for _, tc := range []struct { name string @@ -445,9 +460,8 @@ func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *tes } } held("17 - Reach (other edition).m4a", tc.heldMs) - res, err := ResolveDuplicates(ctx, f.pool, nil, "", true) - if err != nil || res.WrongFiles != 1 { - t.Fatalf("resolve = %+v, %v; want Reach's slot emptied", res, err) + if res := settleKeeping(t, f, f.a.ID); len(res.Removed) != 1 { + t.Fatalf("settle = %+v; want Reach's slot emptied", res) } pairs, err := PairMissingTracks(ctx, f.pool, nil) if err != nil || pairs.Folded() != tc.foldsFirst { @@ -465,64 +479,46 @@ func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *tes } // One recording filling two slots whose songs are both clearly something else -// (Shnabubula's whole album in one file): both copies go, nothing is kept. -func TestResolveDuplicates_RemovesEveryCopyWhenNoSlotIsTheirs_Integration(t *testing.T) { +// (Shnorkelbub's whole album in one file): the note says it is neither song, +// and both files stay until an admin settles it. +func TestResolveDuplicates_SaysWhenNoSlotIsTheRecordings_Integration(t *testing.T) { f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") seedTrackList(t, f.pool, f.album, map[string]int{"Void": 282000, "Reach": 421000}) - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) + res, err := ResolveDuplicates(context.Background(), f.pool, nil, true) if err != nil { t.Fatal(err) } - if res.WrongFiles != 2 || exists(f.aPath) || exists(f.bPath) { - t.Fatalf("result %+v, void exists %v, reach exists %v; want both copies removed", + if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("result %+v, void exists %v, reach exists %v; want it named and both files kept", res, exists(f.aPath), exists(f.bPath)) } - if status, _, _, auto := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" || !auto { - t.Errorf("group = (%s, auto=%v), want settled by the resolver", status, auto) + if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "none of these songs") { + t.Errorf("note %q, want it to say the recording is neither song", note) } - if n := auditCount(t, f.pool, "duplicate_wrong_file", f.groupID); n != 1 { - t.Errorf("wrong-file audit rows = %d, want 1", n) + if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" { + t.Errorf("group = %s, want pending for an admin", status) } } // seedTrimmedAlbum is newOneAlbumFixture for one recording cut to both its // slots' lengths: identical audio, as Tormentor and as Record Shop, each as // long as its own slot's song, and the track list naming each slot's -// recording. The files came from a download Minstrel imported. +// recording. func seedTrimmedAlbum(t *testing.T) oneAlbumFixture { t.Helper() f := newOneAlbumFixture(t, "exact", "Tormentor", "Record Shop") ctx := context.Background() seedTrackList(t, f.pool, f.album, map[string]int{"Tormentor": 221000, "Record Shop": 219000}) - for _, stmt := range []struct { - sql string - args []any - }{ - {`UPDATE mb_release_tracks SET recording_mbid = 'rec-' || lower(replace(title, ' ', '-'))`, nil}, - {`INSERT INTO grabs (info_hash, name, key, client, save_path, origin, import_state, destination) - VALUES ('abc123', 'The Wombats - Void [WEB]', 'k', 'qbit', '/dl', 'schedule', 'imported', $1)`, - []any{filepath.Dir(f.aPath)}}, - } { - if _, err := f.pool.Exec(ctx, stmt.sql, stmt.args...); err != nil { - t.Fatalf("exec %q: %v", stmt.sql, err) - } + if _, err := f.pool.Exec(ctx, + `UPDATE mb_release_tracks SET recording_mbid = 'rec-' || lower(replace(title, ' ', '-'))`); err != nil { + t.Fatal(err) } return f } -func releaseBlocked(t *testing.T, pool *pgxpool.Pool, hash string) bool { - t.Helper() - var n int - if err := pool.QueryRow(context.Background(), - `SELECT count(*) FROM release_blocks WHERE info_hash = $1 AND reason = 'files'`, hash).Scan(&n); err != nil { - t.Fatal(err) - } - return n == 1 -} - -// AcoustID matched one copy to Tormentor's recording: that copy stays, Record -// Shop's goes, and the download they came from is set aside. -func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) { +// AcoustID matched one copy to Tormentor's recording: the note names +// Tormentor, and both files stay. +func TestResolveDuplicates_NamesTheCopyAcoustIDNames_Integration(t *testing.T) { f := seedTrimmedAlbum(t) if _, err := f.pool.Exec(context.Background(), `INSERT INTO track_acoustid_lookups (track_id, state, candidates, recording_mbid) VALUES ($1, 'matched', 1, 'rec-tormentor')`, @@ -530,7 +526,7 @@ func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) { t.Fatal(err) } asked := 0 - res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{ + res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{ Identify: func(context.Context, string) ([]string, error) { asked++; return nil, nil }, }) if err != nil { @@ -539,12 +535,12 @@ func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) { if asked != 0 { t.Errorf("AcoustID asked %d times; the copy's own lookup already answered", asked) } - if res.WrongFiles != 1 || !exists(f.aPath) || exists(f.bPath) { - t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want only Record Shop's copy removed", + if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want Tormentor named and both kept", res, exists(f.aPath), exists(f.bPath)) } - if !releaseBlocked(t, f.pool, "abc123") { - t.Error("the download the files came from was not set aside, so the album would be fetched from it again") + if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "AcoustID says") || !strings.Contains(note, "Tormentor") { + t.Errorf("note %q, want AcoustID's answer naming Tormentor", note) } } @@ -573,37 +569,43 @@ func TestResolveDuplicates_AgreeingLookupsDecideAnAcousticGroup_Integration(t *t f.a.ID, f.b.ID); err != nil { t.Fatal(err) } - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) + res, err := ResolveDuplicates(context.Background(), f.pool, nil, true) if err != nil { t.Fatal(err) } - if res.WrongFiles != 1 || exists(f.aPath) || !exists(f.bPath) { - t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want only Tormentor's copy removed", + if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want Record Shop named and both kept", res, exists(f.aPath), exists(f.bPath)) } + if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "Record Shop") { + t.Errorf("note %q, want it to name Record Shop", note) + } }) t.Run("unknown", func(t *testing.T) { f := setup(t) asked := 0 - res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{ + res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{ Identify: func(context.Context, string) ([]string, error) { asked++; return nil, nil }, }) if err != nil { t.Fatal(err) } - if asked != 0 || res.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) { - t.Fatalf("asked %d, result %+v; want nothing asked or removed for copies that may be two takes", asked, res) + if asked != 0 || res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("asked %d, result %+v; want nothing asked or named for copies that may be two takes", asked, res) } }) } -// A pass while a scan is walking the library waits for it: a copy removed -// under the walk is marked present again when the scan reconciles. A run -// stuck past StuckScanThreshold does not hold the resolver up. +// A pass while a scan is walking the library waits for it: a pass deciding +// from tracks the scan is still rewriting would decide from a library +// half-read. A run stuck past StuckScanThreshold does not hold the resolver +// up. Files being +// read with no run recorded (a scan whose run row hasn't landed yet, a +// watcher batch) hold it up as well. func TestDuplicateResolveWorker_WaitsForARunningScan_Integration(t *testing.T) { f := seedTrimmedAlbum(t) ctx := context.Background() - w := NewDuplicateResolveWorker(f.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), "", nil, ResolveSources{}) + w := NewDuplicateResolveWorker(f.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), nil, ResolveSources{}) if _, err := f.pool.Exec(ctx, `INSERT INTO scan_runs DEFAULT VALUES`); err != nil { t.Fatal(err) } @@ -619,15 +621,30 @@ func TestDuplicateResolveWorker_WaitsForARunningScan_Integration(t *testing.T) { if w.tickOnce(ctx) { t.Error("a scan stuck for two hours held the resolver up") } + + if _, err := f.pool.Exec(ctx, `DELETE FROM scan_runs`); err != nil { + t.Fatal(err) + } + if !filesGate.tryAcquire() { + t.Fatal("the files gate was already held") + } + waited := w.tickOnce(ctx) + filesGate.release() + if !waited { + t.Error("a pass ran while files were being read, with no scan run recorded") + } + if w.tickOnce(ctx) { + t.Error("a pass was put off with nothing reading files") + } } -// AcoustID knows the recording as no song of the album: every copy goes. With -// AcoustID unreachable, nothing is decided and the group waits. +// AcoustID knows the recording as no song of the album: the note says so. With +// AcoustID unreachable, nothing is decided. Either way the group waits. func TestResolveDuplicates_TrimmedCopiesAcoustIDCannotName_Integration(t *testing.T) { t.Run("no match", func(t *testing.T) { f := seedTrimmedAlbum(t) asked := 0 - res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{ + res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{ Identify: func(context.Context, string) ([]string, error) { asked++ return []string{"rec-elsewhere"}, nil @@ -636,23 +653,26 @@ func TestResolveDuplicates_TrimmedCopiesAcoustIDCannotName_Integration(t *testin if err != nil { t.Fatal(err) } - if asked != 1 || res.WrongFiles != 2 || exists(f.aPath) || exists(f.bPath) { - t.Fatalf("asked %d, result %+v; want one lookup and both copies removed", asked, res) + if asked != 1 || res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("asked %d, result %+v; want one lookup, the slot named and both files kept", asked, res) } - if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" { - t.Errorf("group = %s, want settled", status) + if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "none of these songs") { + t.Errorf("note %q, want it to say the recording is neither song", note) + } + if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" { + t.Errorf("group = %s, want pending", status) } }) t.Run("unreachable", func(t *testing.T) { f := seedTrimmedAlbum(t) - res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{ + res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{ Identify: func(context.Context, string) ([]string, error) { return nil, ErrIdentifyUnavailable }, }) if err != nil { t.Fatal(err) } - if res.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) || releaseBlocked(t, f.pool, "abc123") { - t.Fatalf("result %+v; want nothing removed or set aside while AcoustID cannot answer", res) + if res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("result %+v; want nothing named while AcoustID cannot answer", res) } if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" { t.Errorf("group = %s, want pending", status) @@ -678,24 +698,46 @@ func TestResolveDuplicates_FetchesAMissingTrackList_Integration(t *testing.T) { seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 281000}) return nil } - res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{TrackLists: fetch}) + res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{TrackLists: fetch}) if err != nil { t.Fatal(err) } - if calls != 1 || res.WrongFiles != 1 || exists(f.bPath) { - t.Fatalf("fetches %d, result %+v; want one fetch and Reach's copy removed", calls, res) + if calls != 1 || res.SlotsNamed != 1 || !exists(f.bPath) { + t.Fatalf("fetches %d, result %+v; want one fetch, the slot named and Reach's copy kept", calls, res) } } -// Without a track list that decides, nothing is removed. -func TestResolveDuplicates_LeavesAnUndecidedSlotForTheOperator_Integration(t *testing.T) { +// With MusicBrainz track lists switched off, the resolver asks once, gets +// ErrLookupOff, and names nothing it can't decide without the list. +func TestResolveDuplicates_TrackListsSwitchedOff_Integration(t *testing.T) { f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") - seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 221000}) - res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) + if _, err := f.pool.Exec(context.Background(), + `UPDATE albums SET release_group_mbid = $2 WHERE id = $1`, f.album.ID, "rg-off"); err != nil { + t.Fatal(err) + } + calls := 0 + off := func(context.Context, string) error { + calls++ + return ErrLookupOff + } + res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{TrackLists: off}) if err != nil { t.Fatal(err) } - if res.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) { + if calls != 1 || res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) { + t.Fatalf("fetches %d, result %+v; want one refused fetch and both copies kept", calls, res) + } +} + +// Without a track list that decides, nothing is named. +func TestResolveDuplicates_LeavesAnUndecidedSlotForTheOperator_Integration(t *testing.T) { + f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") + seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 221000}) + res, err := ResolveDuplicates(context.Background(), f.pool, nil, true) + if err != nil { + t.Fatal(err) + } + if res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) { t.Fatalf("result %+v; want both copies kept when the lengths cannot tell", res) } if status, class, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" || @@ -710,8 +752,7 @@ func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) { f := newCrossReleaseRipFixture(t) ctx := context.Background() q := dbq.New(f.pool) - // Without its group the rip has no clean copy to merge into, so it stays - // on disk and only its verdict changes. + // Without its group the rip is judged by its name alone. if _, err := f.pool.Exec(ctx, `DELETE FROM duplicate_groups WHERE id = $1`, f.groupID); err != nil { t.Fatal(err) } @@ -725,7 +766,7 @@ func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) { } resolve := func() DuplicateResolveResult { t.Helper() - res, err := ResolveDuplicates(ctx, f.pool, nil, "", true) + res, err := ResolveDuplicates(ctx, f.pool, nil, true) if err != nil { t.Fatal(err) } @@ -757,7 +798,7 @@ func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) { t.Fatal(err) } if _, err := f.pool.Exec(ctx, `UPDATE tracks SET file_path = $2 WHERE id = $1`, - f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Good Inc.mp3")); err != nil { + f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Fine Ltd.mp3")); err != nil { t.Fatal(err) } if res := resolve(); res.Released != 1 { diff --git a/internal/library/duplicate_settle.go b/internal/library/duplicate_settle.go index d44b0c4f..d4028d31 100644 --- a/internal/library/duplicate_settle.go +++ b/internal/library/duplicate_settle.go @@ -11,26 +11,25 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/audit" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/audit" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/musicbrainz" + "github.com/Fabled-Sword/minstrel/internal/notifications" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Duplicates that settle without a merge, so they do not wait on an admin. // Retitles across releases are linked like any cross-release group. What is // left on one album is three shapes: // -// - distinct: two versions of a song that sound alike ("Lovesick" and -// "Lovesick (Instrumental)"). Not duplicates, so the group is dismissed. +// - distinct: two versions of a song that sound alike ("Homesick" and +// "Homesick (Instrumental)"). Not duplicates, so the group is dismissed. // - mismatch: one file filling several track slots (one recording as // three of an album's tracks). The album's MusicBrainz track list // says how long each slot's song is. When exactly one slot's song is as // long as the file and every other slot's song is clearly not, the copies -// in the other slots are removed and their tracks marked missing, so the -// reacquisition sweeper wants the album back and a good copy fills them. +// in the other slots are removed and their tracks marked missing, until a +// good copy fills them. // When every slot's song is clearly not the file, every copy goes. // - named: the lengths cannot say (one recording filed as many tracks, each // cut to its own slot's length), but AcoustID @@ -40,9 +39,6 @@ import ( // when it is in none of their slots. Same audio that AcoustID does not // know at all is no copy's song, and every copy goes. // -// Whenever copies go, the release the files came from is set aside, so the -// album fetched again is not the same files. -// // Anything less certain stays with an admin, who settles it the same way // with their own answer (SettleWrongSlot). @@ -74,7 +70,7 @@ type slotCopy struct { // wrongSlots decides which copies of a one-album mismatch sit in a slot that // is not theirs. keep is the copy whose slot fits the recording, or -1 when -// every copy is clearly another song's (Shnabubula's whole album, 45 minutes +// every copy is clearly another song's (Shnorkelbub's whole album, 45 minutes // in one file, filed as both "Fading Light" and "Looking for Answers"): then // all of them go. ok is false when the track list cannot say, and nothing // should be removed. @@ -82,8 +78,7 @@ type slotCopy struct { // Several copies may fit when they carry the same title ("Killjoy" twice // beside "Dreamland"): they are one song held twice, not a wrong slot, so they // are neither kept nor lost here. Once the wrong slot is emptied, the next -// sweep finds the pair on its own, and the resolver merges it as any song held -// twice on one album. +// sweep finds the pair on its own, as any song held twice on one album. func wrongSlots(copies []slotCopy, tracks []dbq.MbReleaseTrack) (keep int, losers []int, ok bool) { keep = -1 keepKey := "" @@ -168,14 +163,12 @@ func dismissDistinct( return n } -// settleWrongSlots removes the copies that sit in another song's slot, for -// every one-album mismatch the track list, or AcoustID with it, decides. It -// returns how many copies went and the songs whose slots were emptied, and -// adds the groups it settled to settled. -func settleWrongSlots( - ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, settled map[pgtype.UUID]bool, - src ResolveSources, -) (int, []string) { +// nameWrongSlots says, in the note of every one-album mismatch the track list +// or AcoustID decides, which song the recording is, so the admin settling it +// (SettleWrongSlot) need not work it out. It returns how many it named. +func nameWrongSlots( + ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, src ResolveSources, +) int { q := dbq.New(pool) tracksByGroup := map[string][]dbq.MbReleaseTrack{} fetches, identifies := trackListFetchesPerPass, identifiesPerPass @@ -185,10 +178,9 @@ func settleWrongSlots( if src.Identify == nil { identifies = 0 } - removed := 0 - var names []string + named := 0 for _, g := range groups { - if g.class != ClassMismatch || settled[g.id] || ctx.Err() != nil { + if g.class != ClassMismatch || ctx.Err() != nil { continue } rg := g.members[0].ReleaseGroupMbid @@ -204,7 +196,9 @@ func settleWrongSlots( } if len(tracks) == 0 && fetches > 0 && neverRead(ctx, q, rg) { fetches-- - if err := src.TrackLists(ctx, rg); err != nil { + if err := src.TrackLists(ctx, rg); errors.Is(err, ErrLookupOff) { + fetches = 0 + } else if err != nil { logger.Info("duplicate resolve: fetching the album's track list failed", "release_group", rg, "err", err) if errors.Is(err, musicbrainz.ErrUnreachable) { fetches = 0 @@ -220,13 +214,15 @@ func settleWrongSlots( for i, m := range g.members { copies[i] = slotCopy{Title: m.Title, Artist: m.ArtistName, DurationMs: m.DurationMs} } - keep, losers, ok := wrongSlots(copies, tracks) + source := "MusicBrainz's track lengths say" + keep, _, ok := wrongSlots(copies, tracks) if !ok { recordings, known := groupRecordings(ctx, logger, g, src.Identify, &identifies) if !known { continue } - if keep, losers, ok = namedCopies(copies, tracks, recordings); !ok { + source = "AcoustID says" + if keep, _, ok = namedCopies(copies, tracks, recordings); !ok { logger.Info("duplicate resolve: AcoustID's answer does not place the recording in one slot; left for review", "group_id", syncpkg.FormatUUID(g.id), "recordings", recordings) } @@ -234,22 +230,20 @@ func settleWrongSlots( if !ok { continue } - // Set aside before the files go: a pass that dies between the two - // still does not fetch the same files again. - blocked := blockReleasesHolding(ctx, pool, logger, g) - emptied := emptiedSlots(ctx, q, logger, g, losers, tracks) - n, err := removeWrongSlots(ctx, pool, logger, g, keep, losers, emptied, blocked, pgtype.UUID{}) - removed += n - if err != nil { - logger.Warn("duplicate resolve: removing wrong-slot copies failed", "group_id", syncpkg.FormatUUID(g.id), "err", err) - continue - } - settled[g.id] = true - for _, i := range losers { - names = append(names, TrackLabel(g.members[i].ArtistName, g.members[i].Title)) - } + g.note = wrongSlotNote(source, g, keep) + named++ } - return removed, names + return named +} + +// wrongSlotNote is what a mismatch's note says once the pass knows which song +// the recording is: the copy at keep, or none of them when keep is -1. +func wrongSlotNote(source string, g *resolveGroup, keep int) string { + if keep < 0 { + return source + " this recording is none of these songs. Settle it to empty the slots it fills." + } + return source + " this recording is \u201c" + g.members[keep].Title + + "\u201d. Settle it with that copy to empty the slots that are not its own." } // ErrNotWrongSlot means a group is not one recording filling several of an @@ -261,22 +255,18 @@ var ErrNotWrongSlot = errors.New("library: duplicate group is not one recording type WrongSlotResult struct { Kept *MergedCopy Removed []MergedCopy - // Blocked names the releases set aside. None when the album was imported - // before Minstrel downloaded anything: the same files may come back. - Blocked []string } // SettleWrongSlot settles a one-album mismatch the resolver left for the // admin, with their answer in place of MusicBrainz's lengths and // AcoustID's. keepID is the copy whose title they say the recording is; an -// invalid id means they cannot say, and every copy goes. Either way it is the -// resolver's own path: the release the files came from is set aside, the -// copies removed are marked missing, and the album is wanted again for them. -// A merge does none of that, and keeps one copy's title whether or not it is -// the audio's. +// invalid id means they cannot say, and every copy goes. Either way the copies +// removed are marked missing, and their slots wait for a good copy. A merge +// does none of that, and keeps one copy's title whether or not it is the +// audio's. // // Copies sharing the kept copy's title are one song held twice and stay, as in -// wrongSlots: the next sweep finds the pair and the resolver merges it. +// wrongSlots: the next sweep finds the pair, for an admin to merge. func SettleWrongSlot( ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groupID, keepID, actorID pgtype.UUID, ) (WrongSlotResult, error) { @@ -320,9 +310,9 @@ func SettleWrongSlot( } } - res := WrongSlotResult{Blocked: blockReleasesHolding(ctx, pool, logger, g)} + var res WrongSlotResult emptied := emptiedSlots(ctx, q, logger, g, losers, tracks) - n, err := removeWrongSlots(ctx, pool, logger, g, keep, losers, emptied, res.Blocked, actorID) + n, err := removeWrongSlots(ctx, pool, logger, g, keep, losers, emptied, actorID) if keep >= 0 { res.Kept = &MergedCopy{TrackID: g.members[keep].TrackID, FilePath: g.members[keep].FilePath} } @@ -434,42 +424,11 @@ func groupRecordings( return ids, true } -// blockReleasesHolding sets aside the downloads a group's files were imported -// from, and returns their names. An album imported before Minstrel downloaded -// anything has none. -func blockReleasesHolding(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, g *resolveGroup) []string { - q := dbq.New(pool) - seen := map[string]bool{} - var names []string - for _, m := range g.members { - grabs, err := q.ListImportedGrabsHolding(ctx, m.FilePath) - if err != nil { - logger.Warn("duplicate resolve: finding the download a file came from failed", "path", m.FilePath, "err", err) - continue - } - for _, gr := range grabs { - if seen[gr.InfoHash] { - continue - } - seen[gr.InfoHash] = true - if err := acquire.NewMemory(pool).Block(ctx, dbq.BlockReleaseParams{ - InfoHash: gr.InfoHash, Name: gr.Name, Reason: acquire.BlockFiles, - Detail: "one recording fills several of the album's tracks.", WantID: gr.WantID, - }); err != nil { - logger.Warn("duplicate resolve: setting the release aside failed", "release", gr.Name, "err", err) - continue - } - names = append(names, gr.Name) - } - } - return names -} - // emptiedSlots is the losers whose song the album holds no other copy of: // no present track on it under that title as long as the song's slot. Those -// wait for a copy fetched again (migration 0095). The rest are the song held -// twice, and missing-pair folding folds them into the copy held: Savant's -// VOID DLC "Weeper" beside Void's. A failed read counts every loser as +// wait for a good copy to arrive. The rest are the song held +// twice, and missing-pair folding folds them into the copy held: Savanta's +// VOID DLC "Sleeper" beside Void's. A failed read counts every loser as // emptied, which only makes the album wait for a copy it may not need. func emptiedSlots( ctx context.Context, q *dbq.Queries, logger *slog.Logger, g *resolveGroup, losers []int, tracks []dbq.MbReleaseTrack, @@ -515,17 +474,16 @@ func neverRead(ctx context.Context, q *dbq.Queries, rg string) bool { // removeWrongSlots deletes each loser's file, then marks its track missing in // the same transaction that closes the group. The row is kept, with its likes -// and plays: it is the slot, and a good copy fetched again takes it over. Its -// recording MBID is dropped, being the wrong file's, so missing-pair folding -// does not fold the slot into the copy that was kept. The slots in emptied -// are stamped to wait for a copy fetched again (emptiedSlots). blocked names -// the releases set aside, for the record. A file that cannot be removed stops +// and plays: it is the slot, and a good copy that arrives later takes it over. +// Its recording MBID is dropped, being the wrong file's, so missing-pair +// folding does not fold the slot into the copy that was kept. The slots in +// emptied are stamped to wait for a good copy (emptiedSlots). A file that cannot be removed stops // the group; the ones already gone are still marked, and the group waits for // the next pass. actorID is the admin settling it by hand, invalid for the // resolver. func removeWrongSlots( ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, g *resolveGroup, keep int, losers []int, - emptied []pgtype.UUID, blocked []string, actorID pgtype.UUID, + emptied []pgtype.UUID, actorID pgtype.UUID, ) (int, error) { var gone []pgtype.UUID var removedFiles []map[string]string @@ -546,8 +504,8 @@ func removeWrongSlots( } err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { tq := dbq.New(tx) - if _, err := tq.MarkTracksMissing(ctx, gone); err != nil { - return fmt.Errorf("mark missing: %w", err) + if err := markRemoved(ctx, tq, gone, RemovedForDuplicate, actorID); err != nil { + return err } if err := tq.ClearTrackMbids(ctx, gone); err != nil { return fmt.Errorf("clear mbids: %w", err) @@ -555,9 +513,6 @@ func removeWrongSlots( if err := tq.MarkTracksEmptied(ctx, emptied); err != nil { return fmt.Errorf("mark emptied: %w", err) } - if err := logTrackChanges(ctx, tq, gone); err != nil { - return fmt.Errorf("log changes: %w", err) - } if removeErr != nil { return nil } @@ -579,9 +534,6 @@ func removeWrongSlots( "artist": g.members[0].ArtistName, "removed": removedFiles, } - if len(blocked) > 0 { - details["blocked"] = blocked - } keptPath := "" if keep >= 0 { kept := g.members[keep] @@ -595,21 +547,19 @@ func removeWrongSlots( } // notifyNewForReview tells admins about groups this pass classified for the -// first time and left for them. A group the resolver settled, linked or will -// link is not news, and would bury the groups that need them. +// first time and left for them. A group that needs no one (distinct versions +// dismissed, or copies on separate releases that count as one song) is not +// news, and would bury the groups that need them. func notifyNewForReview(ctx context.Context, groups []*resolveGroup, settled map[pgtype.UUID]bool) { var count int64 var items []string for _, g := range groups { - if g.members[0].PriorClass != nil || settled[g.id] { - continue - } - if g.class != ClassReview && g.class != ClassMismatch { + if g.members[0].PriorClass != nil || settled[g.id] || !g.wantsAdmin() { continue } count++ if len(items) < notifyItems { - items = append(items, TrackLabel(g.members[0].ArtistName, g.members[0].Title)) + items = append(items, notifications.TrackLabel(g.members[0].ArtistName, g.members[0].Title)) } } if count > 0 { diff --git a/internal/library/duplicate_settle_test.go b/internal/library/duplicate_settle_test.go index bf14ffc3..2b8560c6 100644 --- a/internal/library/duplicate_settle_test.go +++ b/internal/library/duplicate_settle_test.go @@ -3,32 +3,25 @@ package library import ( "context" "errors" - "path/filepath" "strings" "testing" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // undecidedSlot is one recording filed as Void and as Reach, two songs -// MusicBrainz lists at lengths that cannot tell them apart, from a download -// Minstrel imported: the resolver leaves it pending for an admin. +// MusicBrainz lists at lengths that cannot tell them apart: the resolver +// leaves it pending for an admin. func undecidedSlot(t *testing.T) (oneAlbumFixture, dbq.User) { t.Helper() f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") ctx := context.Background() seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 221000}) - if _, err := f.pool.Exec(ctx, - `INSERT INTO grabs (info_hash, name, key, client, save_path, origin, import_state, destination) - VALUES ('abc123', 'Savant - Void [WEB]', 'k', 'qbit', '/dl', 'schedule', 'imported', $1)`, - filepath.Dir(f.aPath)); err != nil { - t.Fatal(err) - } - if res, err := ResolveDuplicates(ctx, f.pool, nil, "", true); err != nil || res.WrongFiles != 0 { + if res, err := ResolveDuplicates(ctx, f.pool, nil, true); err != nil || res.SlotsNamed != 0 { t.Fatalf("resolve = %+v, %v; want the group left for the operator", res, err) } name := strings.NewReplacer("/", "-", " ", "-").Replace(t.Name()) @@ -41,8 +34,8 @@ func undecidedSlot(t *testing.T) (oneAlbumFixture, dbq.User) { return f, u } -// emptiedTrack says whether a copy's track is marked missing and waiting for -// the album to be fetched again. +// emptiedTrack says whether a copy's track is marked missing and its slot +// emptied. func emptiedTrack(t *testing.T, f oneAlbumFixture, id pgtype.UUID) bool { t.Helper() var emptied bool @@ -72,9 +65,8 @@ func settledByHand(t *testing.T, f oneAlbumFixture, actor dbq.User) { } } -// "Get it again": the admin cannot say which song the recording is, so -// every copy goes, the download they came from is set aside, and both slots -// wait for the album fetched again. A merge would have kept one title. +// The admin cannot say which song the recording is, so every copy goes and +// both slots show as missing. A merge would have kept one title. func TestSettleWrongSlot_GetItAgainRemovesEveryCopy_Integration(t *testing.T) { f, op := undecidedSlot(t) ctx := context.Background() @@ -88,11 +80,16 @@ func TestSettleWrongSlot_GetItAgainRemovesEveryCopy_Integration(t *testing.T) { } for _, id := range []pgtype.UUID{f.a.ID, f.b.ID} { if !emptiedTrack(t, f, id) { - t.Errorf("track %s is not waiting to be fetched again", syncpkg.FormatUUID(id)) + t.Errorf("track %s is not marked missing with its slot emptied", syncpkg.FormatUUID(id)) + } + got, err := dbq.New(f.pool).GetTrackByID(ctx, id) + if err != nil { + t.Fatal(err) + } + if got.RemovedReason == nil || *got.RemovedReason != string(RemovedForDuplicate) || got.RemovedBy != op.ID { + t.Errorf("track %s waits with reason %v by %v, want duplicate by the admin", + syncpkg.FormatUUID(id), got.RemovedReason, got.RemovedBy) } - } - if !releaseBlocked(t, f.pool, "abc123") || len(res.Blocked) != 1 { - t.Errorf("blocked %v; want the download the files came from set aside", res.Blocked) } settledByHand(t, f, op) @@ -102,7 +99,7 @@ func TestSettleWrongSlot_GetItAgainRemovesEveryCopy_Integration(t *testing.T) { } // "This one is Reach": the copy the admin names stays, and only Void's slot -// is emptied and wanted again. +// is emptied. func TestSettleWrongSlot_KeepsTheCopyTheOperatorNames_Integration(t *testing.T) { f, op := undecidedSlot(t) res, err := SettleWrongSlot(context.Background(), f.pool, nil, f.groupID, f.b.ID, op.ID) @@ -114,10 +111,7 @@ func TestSettleWrongSlot_KeepsTheCopyTheOperatorNames_Integration(t *testing.T) res, exists(f.aPath), exists(f.bPath)) } if !emptiedTrack(t, f, f.a.ID) { - t.Error("Void's track is not waiting to be fetched again") - } - if !releaseBlocked(t, f.pool, "abc123") { - t.Error("the download the files came from is not set aside") + t.Error("Void's track is not marked missing with its slot emptied") } settledByHand(t, f, op) } @@ -127,7 +121,7 @@ func TestSettleWrongSlot_KeepsTheCopyTheOperatorNames_Integration(t *testing.T) func TestSettleWrongSlot_RefusesWhatItCannotSettle_Integration(t *testing.T) { ctx := context.Background() t.Run("two versions of a song", func(t *testing.T) { - f := newOneAlbumFixture(t, "acoustic", "Lovesick", "Lovesick (Instrumental)") + f := newOneAlbumFixture(t, "acoustic", "Homesick", "Homesick (Instrumental)") if _, err := SettleWrongSlot(ctx, f.pool, nil, f.groupID, pgtype.UUID{}, pgtype.UUID{}); !errors.Is(err, ErrNotWrongSlot) { t.Errorf("err = %v, want ErrNotWrongSlot", err) } @@ -141,7 +135,7 @@ func TestSettleWrongSlot_RefusesWhatItCannotSettle_Integration(t *testing.T) { if _, err := SettleWrongSlot(ctx, f.pool, nil, f.groupID, other, op.ID); !errors.Is(err, ErrSurvivorNotInGroup) { t.Errorf("err = %v, want ErrSurvivorNotInGroup", err) } - if !exists(f.aPath) || !exists(f.bPath) || releaseBlocked(t, f.pool, "abc123") { + if !exists(f.aPath) || !exists(f.bPath) { t.Error("something changed") } }) diff --git a/internal/library/duplicate_survivor.go b/internal/library/duplicate_survivor.go index bfb8a021..bf68aaba 100644 --- a/internal/library/duplicate_survivor.go +++ b/internal/library/duplicate_survivor.go @@ -1,6 +1,8 @@ package library import ( + "path/filepath" + "regexp" "sort" "strings" "time" @@ -23,12 +25,18 @@ type SurvivorCandidate struct { // - it has a track number that no other track on its album also claims // - its file name carries no video-rip marker (SourceMarkersFor) // - it has a MusicBrainz recording id +// - it sits in a folder named for its album (inAlbumFolder), as a tagger or +// download manager files it, rather than loose beside the artist's other +// songs // // Two copies of one song differ in these far more often than in anything a // listener hears: rips of one song can differ by a few bytes, which makes file // size a poor guide. -func TagFitScore(hasTrackNumber, positionClash bool, filePath string, hasMBID bool) int { +func TagFitScore(hasTrackNumber, positionClash bool, filePath, albumTitle string, hasMBID bool) int { score := 0 + if inAlbumFolder(filePath, albumTitle) { + score++ + } if hasTrackNumber && !positionClash { score++ } @@ -41,6 +49,27 @@ func TagFitScore(hasTrackNumber, positionClash bool, filePath string, hasMBID bo return score } +// discFolder is a folder holding one medium of an album ("CD 01", "Disc 2"). +var discFolder = regexp.MustCompile(`(?i)^(cd|disc|disk)\s*\d+$`) + +// folderYear is a release year at the end of an album folder's name. +var folderYear = regexp.MustCompile(`\s*[(\[]\d{4}[)\]]\s*$`) + +// inAlbumFolder reports whether a file sits in a folder named for its album, +// "Album (Year)" or that folder's "CD nn" medium folder. Letters and digits +// alone are compared, since a filer drops characters a path cannot hold. +func inAlbumFolder(filePath, albumTitle string) bool { + want := normalizeTitle(albumTitle) + if want == "" { + return false + } + dir := filepath.Dir(filePath) + if discFolder.MatchString(filepath.Base(dir)) { + dir = filepath.Dir(dir) + } + return normalizeTitle(folderYear.ReplaceAllString(filepath.Base(dir), "")) == want +} + // losslessFormats are the scanned extensions that are lossless by definition. // m4a is left out on purpose: it holds either ALAC or AAC, and the scanner // records only the extension, so calling it lossless would sometimes prefer an diff --git a/internal/library/duplicate_survivor_test.go b/internal/library/duplicate_survivor_test.go index ad0020f9..ab9b1b57 100644 --- a/internal/library/duplicate_survivor_test.go +++ b/internal/library/duplicate_survivor_test.go @@ -119,7 +119,7 @@ func TestProposeSurvivor_LosslessThenTagFit(t *testing.T) { wantID: "fits", wantReason: "tags fit the album", }, { - // The Humanz shape: two rips a few bytes apart, one carrying a + // The Mammalz shape: two rips a few bytes apart, one carrying a // video marker and clashing with another track's position. name: "tag fit beats a few bytes", cands: []SurvivorCandidate{ @@ -148,15 +148,35 @@ func TestTagFitScore(t *testing.T) { hasMBID bool want int }{ - {"clean, numbered, identified", true, false, "/music/A/B/A - B - 01 - Song.flac", true, 3}, - {"position taken by another track", true, true, "/music/A/B/A - B - 01 - Song.flac", true, 2}, - {"no track number", false, false, "/music/A/B/Song.flac", true, 2}, - {"video rip", true, false, "/music/A/B/A - B - 01 - Song (Official Video).mp3", true, 2}, - {"rip with nothing else", false, false, "/music/A/B/Song (Official Video).mp3", false, 0}, + {"filed, numbered, identified", true, false, "/music/A/B (2001)/A - B - 01 - Song.flac", true, 4}, + {"filed on a medium of the album", true, false, "/music/A/B (2001)/CD 02/A - B - 01 - Song.flac", true, 4}, + {"loose in the artist's folder", true, false, "/music/A/A - Song.flac", true, 3}, + {"position taken by another track", true, true, "/music/A/B/A - B - 01 - Song.flac", true, 3}, + {"no track number", false, false, "/music/A/B/Song.flac", true, 3}, + {"video rip", true, false, "/music/A/B/A - B - 01 - Song (Official Video).mp3", true, 3}, + {"loose rip with nothing else", false, false, "/music/A/Song (Official Video).mp3", false, 0}, } for _, tc := range cases { - if got := TagFitScore(tc.hasTrackNumber, tc.clash, tc.path, tc.hasMBID); got != tc.want { + if got := TagFitScore(tc.hasTrackNumber, tc.clash, tc.path, "B", tc.hasMBID); got != tc.want { t.Errorf("%s: TagFitScore = %d, want %d", tc.name, got, tc.want) } } } + +// A copy a filer put in its album's folder is proposed over a loose copy of +// the same audio in the artist's folder, though the loose one is larger and +// older: size and age decide only between copies that fit equally. +func TestProposeSurvivor_PrefersTheCopyFiledInItsAlbumFolder(t *testing.T) { + old := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + filed := SurvivorCandidate{ + TrackID: "filed", FileFormat: "flac", FileSize: 30_000_000, AddedAt: old.AddDate(5, 0, 0), + TagFit: TagFitScore(true, false, "/music/Tin Orchard/Dusk (2019)/Tin Orchard - Dusk - 01 - Dusk.flac", "Dusk", true), + } + loose := SurvivorCandidate{ + TrackID: "loose", FileFormat: "flac", FileSize: 31_000_000, AddedAt: old, + TagFit: TagFitScore(true, false, "/music/Tin Orchard/01 Dusk.flac", "Dusk", true), + } + if id, reason := ProposeSurvivor([]SurvivorCandidate{loose, filed}); id != "filed" || reason != "tags fit the album" { + t.Errorf("ProposeSurvivor = (%q, %q), want the filed copy for its fit", id, reason) + } +} diff --git a/internal/library/duplicate_sweep.go b/internal/library/duplicate_sweep.go index df54351e..159a3d35 100644 --- a/internal/library/duplicate_sweep.go +++ b/internal/library/duplicate_sweep.go @@ -13,8 +13,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Duplicate sweep. @@ -299,11 +300,11 @@ func TryStartDuplicateSweep( return false, fmt.Errorf("duplicate sweep in-flight check: %w", err) } - go func() { + go periodic.Safe(ctx, logger, "duplicate sweep", func(ctx context.Context) { if _, err := RunDuplicateSweep(ctx, pool, logger, cfg); err != nil { logger.Warn("duplicate sweep failed", "err", err) } - }() + }) return true, nil } @@ -326,26 +327,12 @@ func NewDuplicateSweepWorker( // Run blocks until ctx is cancelled, checking once at start and then each tick. func (w *DuplicateSweepWorker) Run(ctx context.Context) { - w.tickOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.tickOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "duplicate sweep", w.tick, w.tickOnce) } -// tickOnce contains one check so nothing it does can stop the next tick. +// tickOnce checks whether a sweep is due and runs it. periodic.Run contains a +// panic. func (w *DuplicateSweepWorker) tickOnce(ctx context.Context) { - defer func() { - if r := recover(); r != nil { - w.logger.Error("duplicate sweep: tick panicked", "panic", r) - } - }() cfg := w.settings.Get() due, err := duplicateSweepDue(ctx, dbq.New(w.pool), cfg, time.Now()) if err != nil { diff --git a/internal/library/duplicate_sweep_test.go b/internal/library/duplicate_sweep_test.go index 676425ff..0d25d1f5 100644 --- a/internal/library/duplicate_sweep_test.go +++ b/internal/library/duplicate_sweep_test.go @@ -13,8 +13,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) func TestCoveredByDismissal(t *testing.T) { @@ -41,7 +42,7 @@ func TestCoveredByDismissal(t *testing.T) { // out, and how re-sweeping treats a dismissal and a proposal that no longer // holds. func TestDuplicateSweep_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/eventbus.go b/internal/library/eventbus.go index aacb603d..e9dc2868 100644 --- a/internal/library/eventbus.go +++ b/internal/library/eventbus.go @@ -5,7 +5,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" + "github.com/Fabled-Sword/minstrel/internal/eventbus" ) // Package-level bus pointer for scan lifecycle events. Set once diff --git a/internal/library/filesgate.go b/internal/library/filesgate.go new file mode 100644 index 00000000..fadaa81f --- /dev/null +++ b/internal/library/filesgate.go @@ -0,0 +1,59 @@ +package library + +import ( + "context" + "errors" + "time" +) + +// filesGate keeps a library scan and a duplicate-resolver pass from running +// at once. A full scan holds it for its whole length and the watcher for each +// batch; a resolver pass runs only while no one else holds it. The scan +// rewrites tracks from the files it reads, and the pass decides from those +// tracks which copies are one song: run together, the pass would decide from +// a library half-read. +// +// A scan that starts during a resolver pass waits for the pass to finish, +// up to filesWaitLimit. A resolver pass that finds the gate taken is put off +// and tried again (DuplicateResolveWorker). +var filesGate = make(gate, 1) + +// filesWaitLimit is how long a scan waits for a resolver pass to let go of +// the files. A pass takes minutes; one still holding them after this long is +// stuck, and the scan gives up rather than wait forever. +const filesWaitLimit = 30 * time.Minute + +// errFilesBusy is a scan giving up on a resolver pass that held the files +// past filesWaitLimit. +var errFilesBusy = errors.New("library files held by a duplicate-resolver pass past the wait limit") + +// gate is a lock that a waiter can give up on. +type gate chan struct{} + +// acquire takes the gate, or returns ctx's error when ctx ends first and +// errFilesBusy once limit has passed. +func (g gate) acquire(ctx context.Context, limit time.Duration) error { + t := time.NewTimer(limit) + defer t.Stop() + select { + case g <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return errFilesBusy + } +} + +// tryAcquire takes the gate if no one holds it, and reports whether it did. +func (g gate) tryAcquire() bool { + select { + case g <- struct{}{}: + return true + default: + return false + } +} + +// release lets go of a gate acquire or tryAcquire took. +func (g gate) release() { <-g } diff --git a/internal/library/filesgate_test.go b/internal/library/filesgate_test.go new file mode 100644 index 00000000..fa364575 --- /dev/null +++ b/internal/library/filesgate_test.go @@ -0,0 +1,94 @@ +package library + +import ( + "context" + "errors" + "io" + "log/slog" + "path/filepath" + "testing" + "time" + + "github.com/Fabled-Sword/minstrel/internal/dbtest" +) + +// A gate is taken by one holder at a time; a waiter gets it once the holder +// lets go, and gives up when its context ends or its limit passes. +func TestGate_OneHolderAndAWaiterThatCanGiveUp(t *testing.T) { + g := make(gate, 1) + if !g.tryAcquire() { + t.Fatal("an empty gate could not be taken") + } + if g.tryAcquire() { + t.Fatal("a held gate was taken a second time") + } + if err := g.acquire(context.Background(), 20*time.Millisecond); !errors.Is(err, errFilesBusy) { + t.Errorf("waiting past the limit: %v, want errFilesBusy", err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := g.acquire(ctx, time.Minute); !errors.Is(err, context.Canceled) { + t.Errorf("waiting with an ended context: %v, want context.Canceled", err) + } + + got := make(chan error, 1) + go func() { got <- g.acquire(context.Background(), time.Minute) }() + select { + case err := <-got: + t.Fatalf("a waiter got a held gate: %v", err) + case <-time.After(50 * time.Millisecond): + } + g.release() + select { + case err := <-got: + if err != nil { + t.Errorf("a waiter after release: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("a waiter did not get the gate once it was released") + } +} + +// A scan that starts while a duplicate-resolver pass holds the files reads +// none of them until the pass lets go, so the pass never decides from a +// library half-read. +func TestScanner_WaitsForAPassHoldingTheFiles_Integration(t *testing.T) { + ctx := context.Background() + pool := dbtest.Open(t) + if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { + t.Fatalf("truncate: %v", err) + } + root := t.TempDir() + writeTestMP3(t, filepath.Join(root, "Tin Orchard/Dusk/01.mp3"), map[string]string{ + "TIT2": "Dusk", "TPE1": "Tin Orchard", "TALB": "Dusk", "TRCK": "1", + }) + scanner := New(pool, slog.New(slog.NewTextHandler(io.Discard, nil)), []string{root}, nil) + + if !filesGate.tryAcquire() { + t.Fatal("the files gate was already held") + } + type result struct { + stats Stats + err error + } + done := make(chan result, 1) + go func() { + stats, err := scanner.Scan(ctx, nil) + done <- result{stats, err} + }() + select { + case r := <-done: + filesGate.release() + t.Fatalf("the scan ran while a pass held the files: %+v, %v", r.stats, r.err) + case <-time.After(200 * time.Millisecond): + } + filesGate.release() + select { + case r := <-done: + if r.err != nil || r.stats.Added != 1 { + t.Errorf("scan after the pass: %+v, %v; want one song added", r.stats, r.err) + } + case <-time.After(30 * time.Second): + t.Fatal("the scan did not run once the pass let go of the files") + } +} diff --git a/internal/library/fingerprint.go b/internal/library/fingerprint.go index ff35fdb5..10f0d97c 100644 --- a/internal/library/fingerprint.go +++ b/internal/library/fingerprint.go @@ -15,7 +15,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // Acoustic identity. diff --git a/internal/library/fingerprint_backfill.go b/internal/library/fingerprint_backfill.go index 7f25ab9c..7ab90dc6 100644 --- a/internal/library/fingerprint_backfill.go +++ b/internal/library/fingerprint_backfill.go @@ -10,7 +10,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // Fingerprint backfill. @@ -101,27 +102,11 @@ func NewFingerprintBackfillWorker( // Run blocks until ctx is cancelled: one pass at start, so a fresh deploy does // not sit idle for an hour, then one per tick. func (w *FingerprintBackfillWorker) Run(ctx context.Context) { - w.runOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.runOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "fingerprint backfill", w.tick, w.runOnce) } -// runOnce contains a pass so that nothing it does — an error, a panic — can -// stop the next tick from firing. +// runOnce runs one pass and logs what it did. periodic.Run contains a panic. func (w *FingerprintBackfillWorker) runOnce(ctx context.Context) { - defer func() { - if r := recover(); r != nil { - w.logger.Error("fingerprint backfill: pass panicked", "panic", r) - } - }() res, err := w.pass(ctx) if err != nil && ctx.Err() == nil { w.logger.Warn("fingerprint backfill: pass failed", "err", err, "processed", res.Processed) diff --git a/internal/library/fingerprint_backfill_test.go b/internal/library/fingerprint_backfill_test.go index ae37c662..fee760e7 100644 --- a/internal/library/fingerprint_backfill_test.go +++ b/internal/library/fingerprint_backfill_test.go @@ -12,13 +12,14 @@ import ( "sync" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // TestFingerprintBackfill_Integration pins which tracks a pass touches, that a // pass ends, and that the coverage gauge counts what the pass wrote. func TestFingerprintBackfill_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/fingerprint_scan_test.go b/internal/library/fingerprint_scan_test.go index 8d505438..1f66bd19 100644 --- a/internal/library/fingerprint_scan_test.go +++ b/internal/library/fingerprint_scan_test.go @@ -14,9 +14,8 @@ import ( "time" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // TestScanner_FingerprintsOnlyNewOrChangedBytes_Integration pins WHEN the scan @@ -27,24 +26,10 @@ import ( // The fingerprinter is stubbed. CI has no real audio, and the tools' output is // covered by the parser tests; this covers the scan's decisions. func TestScanner_FingerprintsOnlyNewOrChangedBytes_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } diff --git a/internal/library/fingerprint_settings.go b/internal/library/fingerprint_settings.go index ff13c24b..659e6cc5 100644 --- a/internal/library/fingerprint_settings.go +++ b/internal/library/fingerprint_settings.go @@ -9,7 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // Fingerprinting settings. @@ -20,13 +20,13 @@ import ( // // The length is the dangerous knob: chromaprints taken at two lengths cannot be // compared. Rather than bumping fingerprintVersion when it changes, every row -// records the length it was taken at (migration 0061) and every reader filters -// on the current one. A row at another length is stale to the backfill, pending +// records the length it was taken at (track_fingerprints.chromaprint_length_sec) +// and every reader filters on the current one. A row at another length is stale to the backfill, pending // to the gauge and invisible to the sweep, which is the effect a version bump // would have, with one difference worth having: setting the length back makes // rows not yet re-derived current again, instead of redoing the library twice. -// Bounds for each setting, mirrored by migration 0061's CHECKs. +// Bounds for each setting, mirrored by fingerprint_settings's CHECKs. const ( // Below 30s a print has too few items to align at the matcher's larger // offsets and still overlap by minOverlapItems. Above 600s each print @@ -56,16 +56,18 @@ type FingerprintSettings struct { AcousticMaxBitErrorRate float64 BackfillConcurrency int32 SweepIntervalHours int32 - // AutoResolve lets the duplicate resolver act on its own: merge copies no - // release needs. Off, it only classifies, and every group waits for an - // admin. + // AutoResolve lets the duplicate resolver act on its own: link copies of + // one song so they count once, dismiss distinct versions, hold back video + // rips, and note which song a misfiled recording is. It never removes a + // file. Off by default: Minstrel acts on duplicates only once an admin asks + // it to. Off, the pass only classifies, and every group waits for an admin. AutoResolve bool // UpdatedAt is when the settings were last saved. Set by the database; // ignored by Set. UpdatedAt time.Time } -// DefaultFingerprintSettings mirrors migration 0061's column defaults, so a +// DefaultFingerprintSettings mirrors fingerprint_settings's column defaults, so a // database that cannot be read still fingerprints the way a fresh install does. var DefaultFingerprintSettings = FingerprintSettings{ Enabled: true, @@ -73,7 +75,7 @@ var DefaultFingerprintSettings = FingerprintSettings{ AcousticMaxBitErrorRate: defaultAcousticMaxBitErrorRate, BackfillConcurrency: fingerprintBackfillConcurrency, SweepIntervalHours: defaultSweepIntervalHours, - AutoResolve: true, + AutoResolve: false, } // ErrFingerprintSettingOutOfRange is returned by Set for a value migration diff --git a/internal/library/fingerprint_settings_test.go b/internal/library/fingerprint_settings_test.go index d77b9b59..63ab25d3 100644 --- a/internal/library/fingerprint_settings_test.go +++ b/internal/library/fingerprint_settings_test.go @@ -6,6 +6,8 @@ import ( "math" "testing" "time" + + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func TestValidateFingerprintSettings(t *testing.T) { @@ -64,7 +66,7 @@ func TestFingerprintSettingsService_NilServesDefaults(t *testing.T) { } func TestFingerprintSettingsService_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() reload := func(step string) FingerprintSettings { t.Helper() @@ -84,7 +86,7 @@ func TestFingerprintSettingsService_Integration(t *testing.T) { t.Fatalf("load: %v", err) } // ResetDB puts every column back to its migration default, so this pins the - // Go defaults to migration 0061's. Were they to drift, a database that + // Go defaults to fingerprint_settings's. Were they to drift, a database that // could not be read would fingerprint differently from one that could. loaded := svc.Get() if loaded.UpdatedAt.IsZero() { diff --git a/internal/library/forget.go b/internal/library/forget.go new file mode 100644 index 00000000..b41a4549 --- /dev/null +++ b/internal/library/forget.go @@ -0,0 +1,100 @@ +package library + +import ( + "context" + "errors" + "fmt" + "log/slog" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" +) + +// ErrTrackPresent means a track asked to be forgotten has its file: it plays, +// and forgetting it would throw away a track the library still holds. +var ErrTrackPresent = errors.New("library: track has its file") + +// ForgottenTrack is one track Forget removed, named for the audit log. +type ForgottenTrack struct { + ID pgtype.UUID + Title string + FilePath string +} + +// ForgetMissingTracks removes tracks that wait for a file and that an admin +// has given up on: each row goes with its likes, plays and playlist places, +// and an album or artist it leaves empty goes too. There is no file to +// delete. It is all or nothing: if any of ids is unknown (ErrTrackNotFound) or +// has its file (ErrTrackPresent), nothing is forgotten. +// +// dataDir, when set, also clears the cached art of an artist that went. +func ForgetMissingTracks( + ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, ids []pgtype.UUID, +) ([]ForgottenTrack, error) { + if logger == nil { + logger = slog.Default() + } + var gone []ForgottenTrack + var emptiedArtists []pgtype.UUID + err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { + tq := dbq.New(tx) + rows, err := tq.LockTracksForForget(ctx, ids) + if err != nil { + return fmt.Errorf("lock tracks: %w", err) + } + if len(rows) != len(uniqueUUIDs(ids)) { + return ErrTrackNotFound + } + for _, r := range rows { + if !r.MissingSince.Valid { + return ErrTrackPresent + } + } + for _, r := range rows { + if _, err := tq.DeleteTrack(ctx, r.ID); err != nil { + return fmt.Errorf("delete track: %w", err) + } + out, err := tidyEmptiedAlbum(ctx, tq, r.AlbumID) + if err != nil { + return err + } + if out.ArtistID != nil { + emptiedArtists = append(emptiedArtists, *out.ArtistID) + } + gone = append(gone, ForgottenTrack{ID: r.ID, Title: r.Title, FilePath: r.FilePath}) + } + return nil + }) + if err != nil { + return nil, err + } + // After the commit, so neither can undo a forget that happened: an + // unlogged change leaves the track in offline clients' caches until the + // next scan, and leftover art is only disk. + for _, t := range gone { + if err := syncpkg.LogChange(ctx, pool, syncpkg.EntityTrack, syncpkg.FormatUUID(t.ID), syncpkg.OpDelete); err != nil { + logger.Warn("forget: LogChange failed", "track_id", syncpkg.FormatUUID(t.ID), "err", err) + } + } + if dataDir != "" { + for _, a := range emptiedArtists { + if err := coverart.CleanupArtistArt(dataDir, a); err != nil { + logger.Warn("forget: artist-art cleanup failed", "artist_id", syncpkg.FormatUUID(a), "err", err) + } + } + } + return gone, nil +} + +func uniqueUUIDs(ids []pgtype.UUID) map[pgtype.UUID]bool { + out := make(map[pgtype.UUID]bool, len(ids)) + for _, id := range ids { + out[id] = true + } + return out +} diff --git a/internal/library/genre.go b/internal/library/genre.go index e84b549f..f1f82f57 100644 --- a/internal/library/genre.go +++ b/internal/library/genre.go @@ -168,7 +168,7 @@ var genreAcronyms = map[string]string{ // how "Children's Music" became "Children'S Music". // // Deliberately a fixed list rather than "lowercase whatever follows an -// apostrophe": that broader rule would break "O'Brien" and "D'Angelo", which +// apostrophe": that broader rule would break "O'Brien" and "D'Arcy", which // are correctly capitalised after the apostrophe. var contractionSuffixes = map[string]bool{ "s": true, "t": true, "re": true, "ll": true, "ve": true, "d": true, "m": true, diff --git a/internal/library/genre_test.go b/internal/library/genre_test.go index 66576036..983693dd 100644 --- a/internal/library/genre_test.go +++ b/internal/library/genre_test.go @@ -67,151 +67,10 @@ func utf8Frame(values ...string) []byte { return append([]byte{0x03}, []byte(strings.Join(values, "\x00"))...) } -// TestReadID3v2GenreValues_MultiValue: dhowden/tag -// rejoins these values with the empty string, producing "Alternative RockRock"; -// the whole point of our own reader is that they stay separate. -func TestReadID3v2GenreValues_MultiValue(t *testing.T) { - for _, major := range []byte{2, 3, 4} { - id := "TCON" - if major == 2 { - id = "TCO" - } - data := buildID3v2(t, major, rawFrame{id, utf8Frame("Alternative Rock", "Rock")}) - got, err := readID3v2GenreValues(bytes.NewReader(data)) - if err != nil { - t.Fatalf("v2.%d: %v", major, err) - } - want := []string{"Alternative Rock", "Rock"} - if !equalStrings(got, want) { - t.Errorf("v2.%d genres = %q, want %q", major, got, want) - } - } -} - -// Eight values that a joining reader would weld into one 70-character token. -func TestReadID3v2GenreValues_ManyValues(t *testing.T) { - values := []string{ - "Boom Bap", "Downtempo", "Hip Hop", "Instrumental", - "Lo-Fi", "Lo-Fi Hip Hop", "Chillwave", "Instrumental Hip Hop", - } - data := buildID3v2(t, 4, rawFrame{"TCON", utf8Frame(values...)}) - got, err := readID3v2GenreValues(bytes.NewReader(data)) - if err != nil { - t.Fatal(err) - } - if !equalStrings(got, values) { - t.Errorf("genres = %q, want %q", got, values) - } -} - -// A trailing null terminator is legal and must not produce an empty value. -func TestReadID3v2GenreValues_TrailingTerminator(t *testing.T) { - data := buildID3v2(t, 4, rawFrame{"TCON", append(utf8Frame("Jazz"), 0x00)}) - got, err := readID3v2GenreValues(bytes.NewReader(data)) - if err != nil { - t.Fatal(err) - } - if !equalStrings(got, []string{"Jazz"}) { - t.Errorf("genres = %q, want [Jazz]", got) - } -} - -// UTF-16 uses a TWO-byte separator. Splitting it on single nulls would cut -// every ASCII character in half, so this guards the width handling. -func TestReadID3v2GenreValues_UTF16(t *testing.T) { - tests := []struct { - name string - payload []byte - }{ - { - // Spec-correct: encoding 1 with a BOM on every value. - name: "utf16le, BOM on each value", - payload: concat([]byte{0x01}, - []byte{0xFF, 0xFE}, utf16LE("Rock"), - []byte{0x00, 0x00}, - []byte{0xFF, 0xFE}, utf16LE("Pop")), - }, - { - // Sloppy but common: BOM only on the first value. Without carrying - // the byte order forward, "Pop" decodes byte-swapped to CJK. - name: "utf16le, BOM only on the first value", - payload: concat([]byte{0x01}, - []byte{0xFF, 0xFE}, utf16LE("Rock"), - []byte{0x00, 0x00}, utf16LE("Pop")), - }, - { - // Encoding 2: big-endian, no BOM anywhere. - name: "utf16be no BOM", - payload: concat([]byte{0x02}, - utf16BE("Rock"), []byte{0x00, 0x00}, utf16BE("Pop")), - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - data := buildID3v2(t, 4, rawFrame{"TCON", tc.payload}) - got, err := readID3v2GenreValues(bytes.NewReader(data)) - if err != nil { - t.Fatal(err) - } - if !equalStrings(got, []string{"Rock", "Pop"}) { - t.Errorf("genres = %q, want [Rock Pop]", got) - } - }) - } -} - -// ISO-8859-1 must be widened, not reinterpreted as UTF-8 — "Bj\xf6rk" would -// otherwise come back as invalid bytes. -func TestReadID3v2GenreValues_Latin1(t *testing.T) { - payload := append([]byte{0x00}, []byte("Chanson Fran\xe7aise")...) - data := buildID3v2(t, 3, rawFrame{"TCON", payload}) - got, err := readID3v2GenreValues(bytes.NewReader(data)) - if err != nil { - t.Fatal(err) - } - if !equalStrings(got, []string{"Chanson Française"}) { - t.Errorf("genres = %q, want [Chanson Française]", got) - } -} - -// Frames before TCON must be walked over correctly. If the size field were -// decoded with the wrong scheme the walk lands mid-frame and TCON is missed. -func TestReadID3v2GenreValues_SkipsPrecedingFrames(t *testing.T) { - for _, major := range []byte{3, 4} { - data := buildID3v2(t, major, - rawFrame{"TIT2", utf8Frame("Some Title")}, - rawFrame{"TPE1", utf8Frame("Some Artist")}, - rawFrame{"TCON", utf8Frame("Shoegaze", "Dream Pop")}, - ) - got, err := readID3v2GenreValues(bytes.NewReader(data)) - if err != nil { - t.Fatalf("v2.%d: %v", major, err) - } - if !equalStrings(got, []string{"Shoegaze", "Dream Pop"}) { - t.Errorf("v2.%d genres = %q, want [Shoegaze Dream Pop]", major, got) - } - } -} - -func TestReadID3v2GenreValues_NoGenreFrame(t *testing.T) { - data := buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("Only A Title")}) - if _, err := readID3v2GenreValues(bytes.NewReader(data)); err == nil { - t.Fatal("expected an error when no genre frame is present") - } -} - -func TestReadID3v2GenreValues_NotAnID3File(t *testing.T) { - if _, err := readID3v2GenreValues(bytes.NewReader([]byte("not a tag at all"))); err == nil { - t.Fatal("expected an error for a file with no ID3v2 tag") - } -} - -// Padding after the last frame is zero bytes; the walk must stop rather than -// read a frame id of "\x00\x00\x00\x00". -func TestReadID3v2GenreValues_StopsAtPadding(t *testing.T) { +// paddedTag is a v2.4 tag holding one TCON frame followed by 32 bytes of +// padding, the way taggers leave room to grow. +func paddedTag(t *testing.T) []byte { tagged := buildID3v2(t, 4, rawFrame{"TCON", utf8Frame("Rock")}) - // Splice 32 padding bytes in before the MPEG sync trailer, growing the - // declared tag size to match. body := tagged[10 : len(tagged)-4] padded := append(append([]byte{}, body...), make([]byte, 32)...) var out bytes.Buffer @@ -219,41 +78,90 @@ func TestReadID3v2GenreValues_StopsAtPadding(t *testing.T) { out.Write([]byte{4, 0x00, 0x00}) out.Write(synchsafeBytes(len(padded))) out.Write(padded) - got, err := readID3v2GenreValues(bytes.NewReader(out.Bytes())) - if err != nil { - t.Fatal(err) - } - if !equalStrings(got, []string{"Rock"}) { - t.Errorf("genres = %q, want [Rock]", got) - } + return out.Bytes() } -// Unsynchronisation inserts 0xFF 0x00 pairs that must be collapsed before the -// frame list is walked, or every offset past the first pair is wrong. -func TestReadID3v2GenreValues_TagUnsynchronisation(t *testing.T) { - // Latin-1 so a genre can legitimately contain the byte 0xFF ("ÿ"). Once - // unsynchronised that becomes 0xFF 0x00 — which is indistinguishable from a - // value separator until the collapse runs, so this fails loudly if - // undoUnsynchronisation is skipped. +// unsynchronisedTag is a v2.3 tag with the unsynchronisation flag set, whose +// Latin-1 genre holds the byte 0xFF. Once unsynchronised that becomes +// 0xFF 0x00, indistinguishable from a value separator until the collapse runs. +func unsynchronisedTag(t *testing.T) []byte { payload := concat([]byte{0x00}, []byte("Ro\xffck"), []byte{0x00}, []byte("Pop")) inner := buildID3v2(t, 3, rawFrame{"TCON", payload}) body := inner[10 : len(inner)-4] encoded := bytes.ReplaceAll(body, []byte{0xFF}, []byte{0xFF, 0x00}) if bytes.Equal(encoded, body) { - t.Fatal("test is vacuous: nothing was unsynchronised") + t.Fatal("fixture is vacuous: nothing was unsynchronised") } var out bytes.Buffer out.WriteString("ID3") out.Write([]byte{3, 0x00, 0x80}) // 0x80 = unsynchronisation out.Write(synchsafeBytes(len(encoded))) out.Write(encoded) + return out.Bytes() +} - got, err := readID3v2GenreValues(bytes.NewReader(out.Bytes())) - if err != nil { - t.Fatal(err) - } - if !equalStrings(got, []string{"Roÿck", "Pop"}) { - t.Errorf("genres = %q, want [Roÿck Pop]", got) +// Minstrel reads ID3v2 genre frames itself because dhowden/tag rejoins +// multiple values with the empty string ("Alternative RockRock"). Each case is +// a detail of the format a reader gets subtly wrong. +func TestReadID3v2GenreValues(t *testing.T) { + multi := utf8Frame("Alternative Rock", "Rock") + for _, tc := range []struct { + name string + data func(t *testing.T) []byte + want []string + err bool + }{ + // Frame size encoding differs per version: 2.4 is synchsafe, 2.2 and + // 2.3 are plain. + {"v2.2 multi-value", func(t *testing.T) []byte { return buildID3v2(t, 2, rawFrame{"TCO", multi}) }, []string{"Alternative Rock", "Rock"}, false}, + {"v2.3 multi-value", func(t *testing.T) []byte { return buildID3v2(t, 3, rawFrame{"TCON", multi}) }, []string{"Alternative Rock", "Rock"}, false}, + {"v2.4 multi-value", func(t *testing.T) []byte { return buildID3v2(t, 4, rawFrame{"TCON", multi}) }, []string{"Alternative Rock", "Rock"}, false}, + {"a trailing terminator adds no empty value", func(t *testing.T) []byte { + return buildID3v2(t, 4, rawFrame{"TCON", append(utf8Frame("Jazz"), 0x00)}) + }, []string{"Jazz"}, false}, + // UTF-16 uses a two-byte separator; splitting on single nulls would + // cut every ASCII character in half. + {"utf16le, BOM on each value", func(t *testing.T) []byte { + return buildID3v2(t, 4, rawFrame{"TCON", concat([]byte{0x01}, + []byte{0xFF, 0xFE}, utf16LE("Rock"), []byte{0x00, 0x00}, []byte{0xFF, 0xFE}, utf16LE("Pop"))}) + }, []string{"Rock", "Pop"}, false}, + // Sloppy but common; without carrying the byte order forward, "Pop" + // decodes byte-swapped to CJK. + {"utf16le, BOM only on the first value", func(t *testing.T) []byte { + return buildID3v2(t, 4, rawFrame{"TCON", concat([]byte{0x01}, + []byte{0xFF, 0xFE}, utf16LE("Rock"), []byte{0x00, 0x00}, utf16LE("Pop"))}) + }, []string{"Rock", "Pop"}, false}, + {"utf16be, no BOM", func(t *testing.T) []byte { + return buildID3v2(t, 4, rawFrame{"TCON", concat([]byte{0x02}, utf16BE("Rock"), []byte{0x00, 0x00}, utf16BE("Pop"))}) + }, []string{"Rock", "Pop"}, false}, + // ISO-8859-1 is widened, not reinterpreted as UTF-8. + {"latin-1", func(t *testing.T) []byte { + return buildID3v2(t, 3, rawFrame{"TCON", append([]byte{0x00}, []byte("Chanson Fran\xe7aise")...)}) + }, []string{"Chanson Française"}, false}, + // A wrongly decoded size lands the walk mid-frame and misses TCON. + {"v2.3 frames before TCON", func(t *testing.T) []byte { + return buildID3v2(t, 3, rawFrame{"TIT2", utf8Frame("Some Title")}, rawFrame{"TPE1", utf8Frame("Some Artist")}, + rawFrame{"TCON", utf8Frame("Shoegaze", "Dream Pop")}) + }, []string{"Shoegaze", "Dream Pop"}, false}, + {"v2.4 frames before TCON", func(t *testing.T) []byte { + return buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("Some Title")}, rawFrame{"TPE1", utf8Frame("Some Artist")}, + rawFrame{"TCON", utf8Frame("Shoegaze", "Dream Pop")}) + }, []string{"Shoegaze", "Dream Pop"}, false}, + // The walk stops at padding rather than reading a frame id of zeros. + {"padding after the last frame", paddedTag, []string{"Rock"}, false}, + {"tag unsynchronisation", unsynchronisedTag, []string{"Roÿck", "Pop"}, false}, + {"no genre frame", func(t *testing.T) []byte { return buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("Only A Title")}) }, nil, true}, + {"not an ID3 file", func(*testing.T) []byte { return []byte("not a tag at all") }, nil, true}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := readID3v2GenreValues(bytes.NewReader(tc.data(t))) + if (err != nil) != tc.err { + t.Fatalf("err = %v, want error: %v", err, tc.err) + } + if !equalStrings(got, tc.want) { + t.Errorf("genres = %q, want %q", got, tc.want) + } + }) } } @@ -288,6 +196,19 @@ func TestNormaliseGenreValue(t *testing.T) { // A label that merely starts with digits is text, not a reference. {"digits in a name", "1980s", []string{"1980s"}}, {"hyphenated", "Lo-Fi Hip Hop", []string{"Lo-Fi Hip Hop"}}, + + // Casing repair runs on text from the file, including the + // parenthesised and refinement paths; punctuation around an acronym + // does not hide it. + {"casing repaired", "Edm", []string{"EDM"}}, + {"casing repaired after a reference", "(17)Uk Garage", []string{"Rock", "UK Garage"}}, + {"casing repaired inside parentheses", "(Live Edm)", []string{"(Live EDM)"}}, + {"casing repaired after an escaped paren", "((Children'S Music", []string{"(Children's Music"}}, + // It never touches a name from the ID3v1 table, which is kept + // canonical: entry 40's 1990s spelling stays though it reads like + // damage. + {"table name not recased", "40", []string{"AlternRock"}}, + {"parenthesised table name not recased", "(40)", []string{"AlternRock"}}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -299,88 +220,64 @@ func TestNormaliseGenreValue(t *testing.T) { } } -func TestNormaliseGenres_DedupesCaseInsensitively(t *testing.T) { - got := normaliseGenres([]string{"Rock", "rock", "ROCK", "Pop"}) - // First spelling wins — we are not imposing a canonical case here, only - // removing values that repeat within a single file. - if !equalStrings(got, []string{"Rock", "Pop"}) { - t.Errorf("genres = %q, want [Rock Pop]", got) +// normaliseGenres removes values that repeat within one file, keeping the +// first spelling; it imposes no canonical case beyond the acronym repair. +func TestNormaliseGenres(t *testing.T) { + for _, tc := range []struct { + name string + in []string + want []string + }{ + {"case-insensitive repeats", []string{"Rock", "rock", "ROCK", "Pop"}, []string{"Rock", "Pop"}}, + // "(40)AlternRock" declares one genre twice, numerically and in text. + {"a reference and its own name", []string{"(40)AlternRock"}, []string{"AlternRock"}}, + {"acronym spellings", []string{"Edm", "EDM", "edm"}, []string{"EDM"}}, + {"nothing usable", []string{"", " ", "9999"}, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := normaliseGenres(tc.in); !equalStrings(got, tc.want) { + t.Errorf("normaliseGenres(%q) = %q, want %q", tc.in, got, tc.want) + } + }) } } -// "(40)AlternRock" declares the same genre twice — numerically and in text. -func TestNormaliseGenres_DedupesResolvedNumeric(t *testing.T) { - got := normaliseGenres([]string{"(40)AlternRock"}) - if !equalStrings(got, []string{"AlternRock"}) { - t.Errorf("genres = %q, want [AlternRock]", got) - } -} - -func TestNormaliseGenres_AllJunkYieldsNil(t *testing.T) { - if got := normaliseGenres([]string{"", " ", "9999"}); got != nil { - t.Errorf("genres = %q, want nil", got) - } -} - -// End-to-end through dhowden/tag, which is what the scanner actually calls. -// Proves the welded value never reaches the caller. -func TestExtractGenres_EndToEnd(t *testing.T) { - data := buildID3v2(t, 4, - rawFrame{"TIT2", utf8Frame("A Song")}, - rawFrame{"TCON", utf8Frame("Alternative Rock", "Rock")}, - ) - rs := bytes.NewReader(data) - meta, err := tag.ReadFrom(rs) - if err != nil { - t.Fatalf("tag.ReadFrom: %v", err) - } - // Confirm the upstream behaviour this reader works around is still present — - // if dhowden ever fixes it, this test tells us the workaround can go. - if welded := meta.Genre(); welded != "Alternative RockRock" { - t.Logf("note: dhowden/tag no longer welds multi-values (got %q)", welded) - } - - genres, fellBack := extractGenres(meta, rs) - if fellBack { - t.Error("fellBack = true, want false — the TCON frame is parseable") - } - if !equalStrings(genres, []string{"Alternative Rock", "Rock"}) { - t.Errorf("genres = %q, want [Alternative Rock Rock]", genres) - } - if joined := strings.Join(genres, genreDelimiter); joined != "Alternative Rock;Rock" { - t.Errorf("stored value = %q, want %q", joined, "Alternative Rock;Rock") - } -} - -// The digit-soup case, end to end: numeric references resolve to names. -func TestExtractGenres_ResolvesNumericReferences(t *testing.T) { - data := buildID3v2(t, 4, rawFrame{"TCON", utf8Frame("40", "17")}) - rs := bytes.NewReader(data) - meta, err := tag.ReadFrom(rs) - if err != nil { - t.Fatalf("tag.ReadFrom: %v", err) - } - genres, _ := extractGenres(meta, rs) - if !equalStrings(genres, []string{"AlternRock", "Rock"}) { - t.Errorf("genres = %q, want [AlternRock Rock]", genres) - } -} - -// A file with no genre at all must yield nothing and must NOT be reported as a -// fallback — that would log a warning for every untagged file in the library. -func TestExtractGenres_NoGenreIsNotAFallback(t *testing.T) { - data := buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("A Song")}) - rs := bytes.NewReader(data) - meta, err := tag.ReadFrom(rs) - if err != nil { - t.Fatalf("tag.ReadFrom: %v", err) - } - genres, fellBack := extractGenres(meta, rs) - if len(genres) != 0 { - t.Errorf("genres = %q, want none", genres) - } - if fellBack { - t.Error("fellBack = true for an untagged file; would log on every such file") +// extractGenres is what the scanner calls, after dhowden/tag has read the +// file. In every format the values stay separate (dhowden welds ID3 values +// together and keeps only the last Vorbis GENRE field), numeric ID3 +// references resolve to names, and a file with no genre yields nothing and is +// not reported as a fallback, which would log a warning for every untagged +// file in the library. +func TestExtractGenres(t *testing.T) { + oggComment := append([]byte("\x03vorbis"), vorbisComment(genreFields("Shoegaze", "Dream Pop")...)...) + oggComment = append(oggComment, 1) // framing bit + for _, tc := range []struct { + name string + data []byte + want []string + }{ + {"id3 multi-value", buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("A Song")}, + rawFrame{"TCON", utf8Frame("Alternative Rock", "Rock")}), []string{"Alternative Rock", "Rock"}}, + {"id3 numeric references", buildID3v2(t, 4, rawFrame{"TCON", utf8Frame("40", "17")}), []string{"AlternRock", "Rock"}}, + {"id3 with no genre", buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("A Song")}), nil}, + {"flac repeated fields", buildFLAC(false, append([]string{"TITLE=Eons"}, genreFields(lifeForms...)...)...), lifeForms}, + {"ogg vorbis repeated fields", buildOgg(7, vorbisIdent(), oggComment), []string{"Shoegaze", "Dream Pop"}}, + {"mp4 several data atoms", buildMP4(true, mp4Box("\xa9gen", mp4Text("Hip Hop"), mp4Text("Lo-Fi"))), []string{"Hip Hop", "Lo-Fi"}}, + } { + t.Run(tc.name, func(t *testing.T) { + rs := bytes.NewReader(tc.data) + meta, err := tag.ReadFrom(rs) + if err != nil { + t.Fatalf("tag.ReadFrom: %v", err) + } + genres, fellBack := extractGenres(meta, rs) + if fellBack { + t.Error("fellBack = true, want false") + } + if !equalStrings(genres, tc.want) { + t.Errorf("genres = %q, want %q", genres, tc.want) + } + }) } } @@ -448,7 +345,7 @@ func TestTrueUpCasing(t *testing.T) { // and must keep their capital — this is why the suffix list is fixed // rather than "lowercase anything after an apostrophe". {"irish surname", "O'Brien Core", "O'Brien Core"}, - {"french elision", "D'Angelo Soul", "D'Angelo Soul"}, + {"french elision", "D'Arcy Soul", "D'Arcy Soul"}, // Ordinary genres pass through untouched. Case is otherwise exposed as // the file says it — "Rock" vs "rock" stays a real distinction. @@ -475,46 +372,3 @@ func TestTrueUpCasing(t *testing.T) { }) } } - -// The casing repair must never touch a name resolved from the ID3v1 table. The -// operator chose to keep that table canonical, so entry 40's 1990s spelling -// "AlternRock" stays as-is even though it reads like damage. -func TestNormaliseGenreValue_CanonicalTableNamesNotRecased(t *testing.T) { - if got := normaliseGenreValue("40"); !equalStrings(got, []string{"AlternRock"}) { - t.Errorf("bare 40 = %q, want [AlternRock]", got) - } - if got := normaliseGenreValue("(40)"); !equalStrings(got, []string{"AlternRock"}) { - t.Errorf("(40) = %q, want [AlternRock]", got) - } -} - -// Casing runs on values that came from the file, including the parenthesised -// and refinement paths. -func TestNormaliseGenreValue_CasingAppliedToFileText(t *testing.T) { - tests := []struct { - in string - want []string - }{ - {"Edm", []string{"EDM"}}, - {"(17)Uk Garage", []string{"Rock", "UK Garage"}}, - // Punctuation around the acronym must not hide it — the letter core is - // what gets matched, and the trimmed edges are re-attached. - {"(Live Edm)", []string{"(Live EDM)"}}, - {"((Children'S Music", []string{"(Children's Music"}}, - } - for _, tc := range tests { - t.Run(tc.in, func(t *testing.T) { - if got := normaliseGenreValue(tc.in); !equalStrings(got, tc.want) { - t.Errorf("normaliseGenreValue(%q) = %q, want %q", tc.in, got, tc.want) - } - }) - } -} - -// Two spellings of one acronym in the same file collapse to a single tag rather -// than surviving as near-duplicates. -func TestNormaliseGenres_AcronymVariantsDedupe(t *testing.T) { - if got := normaliseGenres([]string{"Edm", "EDM", "edm"}); !equalStrings(got, []string{"EDM"}) { - t.Errorf("genres = %q, want [EDM]", got) - } -} diff --git a/internal/library/hidden.go b/internal/library/hidden.go new file mode 100644 index 00000000..01fb7a91 --- /dev/null +++ b/internal/library/hidden.go @@ -0,0 +1,38 @@ +package library + +import ( + "path/filepath" + "strings" +) + +// Hidden files and folders, whose names start with a dot, are not part of +// the library. Other programs that share the music folder keep their own +// things there: a download manager parks the copies it replaced in a hidden +// folder until someone empties it, and macOS leaves "._" files beside every +// track it copies. Indexing them would list a copy the person set aside, or +// adopt it as the original track having moved. Navidrome and Jellyfin skip +// them the same way. + +// hiddenName reports whether a file or folder name is hidden. +func hiddenName(name string) bool { + return strings.HasPrefix(name, ".") && name != "." && name != ".." +} + +// hiddenInLibrary reports whether path is, or sits inside, a hidden file or +// folder below one of the library roots. A root may itself be hidden; only +// what is below it counts. +func hiddenInLibrary(roots []string, path string) bool { + for _, root := range roots { + rel, err := filepath.Rel(root, path) + if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + continue + } + for _, part := range strings.Split(rel, string(filepath.Separator)) { + if hiddenName(part) { + return true + } + } + return false + } + return false +} diff --git a/internal/library/hidden_test.go b/internal/library/hidden_test.go new file mode 100644 index 00000000..d0288fcd --- /dev/null +++ b/internal/library/hidden_test.go @@ -0,0 +1,86 @@ +package library + +import ( + "context" + "io" + "log/slog" + "os" + "path/filepath" + "testing" + + "github.com/fsnotify/fsnotify" +) + +// libraryTree writes empty files at each path below a fresh root. +func libraryTree(t *testing.T, files ...string) string { + t.Helper() + root := t.TempDir() + for _, f := range files { + p := filepath.Join(root, filepath.FromSlash(f)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, nil, 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +// A full scan lists the library's audio files and none inside a hidden +// folder or hidden itself: a download manager's set-aside copies and macOS +// "._" files are not tracks. +func TestEnumerate_LeavesHiddenFilesAndFoldersOut(t *testing.T) { + root := libraryTree(t, + "Artist/Album (2001)/01 Song.flac", + ".set-aside/Artist/Album (2001)/01 Song.flac", + "Artist/.cache/02 Other.mp3", + "Artist/Album (2001)/._01 Song.flac", + ) + s := &Scanner{paths: []string{root}, logger: slog.New(slog.NewTextHandler(io.Discard, nil))} + var stats Stats + got, errs := s.enumerate(context.Background(), nil, &stats) + want := filepath.Join(root, "Artist", "Album (2001)", "01 Song.flac") + if errs != 0 || len(got) != 1 || got[0] != want { + t.Fatalf("enumerate = %v (errors %d), want only %s", got, errs, want) + } +} + +func TestHiddenInLibrary(t *testing.T) { + root := filepath.Join(string(filepath.Separator), "srv", ".music") + for _, tc := range []struct { + path string + want bool + }{ + {"Artist/Album/01.flac", false}, + {".set-aside/Artist/Album/01.flac", true}, + {".set-aside", true}, + {"Artist/._01.flac", true}, + {"Artist/Album..Live/01.flac", false}, + {"", false}, + } { + path := filepath.Join(root, filepath.FromSlash(tc.path)) + if got := hiddenInLibrary([]string{root}, path); got != tc.want { + t.Errorf("hiddenInLibrary(%q) = %v, want %v (a hidden root itself does not count)", path, got, tc.want) + } + } + outside := filepath.Join(string(filepath.Separator), "srv", ".other", "01.flac") + if hiddenInLibrary([]string{root}, outside) { + t.Errorf("a path outside every root counted as hidden in the library") + } +} + +// The watcher ignores a hidden folder appearing in the library, so nothing +// set aside in it is watched or queued for a scan. +func TestWatcher_IgnoresAHiddenFolderAppearing(t *testing.T) { + root := libraryTree(t, ".set-aside/Artist/Album/01 Song.flac") + w := &Watcher{ + scanner: &Scanner{paths: []string{root}}, + logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + } + pending := map[string]struct{}{} + held := filepath.Join(root, ".set-aside") + if w.handleEvent(nil, fsnotify.Event{Name: held, Op: fsnotify.Create}, pending) || len(pending) != 0 { + t.Fatalf("a hidden folder appearing queued %v", pending) + } +} diff --git a/internal/library/id3v2genre.go b/internal/library/id3v2genre.go index 49de328d..af897f35 100644 --- a/internal/library/id3v2genre.go +++ b/internal/library/id3v2genre.go @@ -6,6 +6,8 @@ import ( "io" "strings" "unicode/utf16" + + "github.com/Fabled-Sword/minstrel/internal/tagread" ) // Why this file exists at all: github.com/dhowden/tag reads every other field @@ -27,12 +29,6 @@ import ( // So the TCON frame is parsed here directly. Only the genre frame — everything // else still comes from dhowden/tag, which handles it fine. -// maxID3TagSize caps how much of a file we'll buffer looking for TCON. Real -// tags are kilobytes; embedded cover art pushes them to a few megabytes. The -// cap exists so a corrupt or hostile size field can't make the scanner -// allocate wildly on a file it was only asked to index. -const maxID3TagSize = 16 << 20 - // errNoGenreFrame means the file carries no readable genre frame. It is an // expected outcome (plenty of files are untagged), not a failure. var errNoGenreFrame = errors.New("library: no ID3v2 genre frame") @@ -62,8 +58,8 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) { return nil, errNoGenreFrame } tagFlags := hdr[5] - size := syncsafeInt(hdr[6:10]) - if size <= 0 || size > maxID3TagSize { + size := tagread.SyncsafeInt(hdr[6:10]) + if size <= 0 || size > tagread.MaxTagSize { return nil, errNoGenreFrame } @@ -83,11 +79,11 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) { // Whole-tag unsynchronisation (2.2/2.3). 2.4 moved this per-frame, but // some writers still set it at tag level, and undoing it twice is // harmless: after the first pass no 0xFF 0x00 pairs remain. - body = undoUnsynchronisation(body) + body = tagread.UndoUnsynchronisation(body) } if major >= 3 && tagFlags&0x40 != 0 { var ok bool - if body, ok = skipExtendedHeader(body, major); !ok { + if body, ok = tagread.SkipExtendedHeader(body, major); !ok { return nil, errNoGenreFrame } } @@ -99,7 +95,7 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) { func findGenreFrame(body []byte, major byte) ([]string, error) { // 2.2 frames: 3-byte id + 3-byte size, no flags. 2.3/2.4: 4-byte id + // 4-byte size + 2-byte flags. The size field is the other difference that - // matters — see frameSize. + // matters — see tagread.FrameSize. idLen, sizeLen, flagLen := 4, 4, 2 wantID := "TCON" if major == 2 { @@ -115,7 +111,7 @@ func findGenreFrame(body []byte, major byte) ([]string, error) { if body[off] == 0 { break } - size := frameSize(body[off+idLen:off+idLen+sizeLen], major) + size := tagread.FrameSize(body[off+idLen:off+idLen+sizeLen], major) if size <= 0 || off+hdrLen+size > len(body) { // Bogus length — we can't trust any offset past this point. break @@ -136,25 +132,6 @@ func findGenreFrame(body []byte, major byte) ([]string, error) { return nil, errNoGenreFrame } -// frameSize decodes a frame's length field. 2.4 made it syncsafe (7 bits per -// byte); 2.2 and 2.3 are plain big-endian. Reading a 2.3 size as syncsafe (or -// the reverse) yields a plausible-looking wrong offset rather than an obvious -// error, which is exactly how frame-walking bugs go unnoticed. -func frameSize(b []byte, major byte) int { - switch major { - case 2: - return int(b[0])<<16 | int(b[1])<<8 | int(b[2]) - case 3: - n := binary.BigEndian.Uint32(b) - if n > maxID3TagSize { - return -1 - } - return int(n) - default: - return syncsafeInt(b) - } -} - // frameData strips per-frame wrappers and reports whether the payload is // readable at all. Compressed and encrypted frames are not (we have no // zlib-in-frame or key handling, and neither is meaningful for a genre tag). @@ -192,7 +169,7 @@ func frameData(data []byte, major byte, flags uint16) ([]byte, bool) { data = data[4:] // syncsafe expanded size; we don't need it } if flags&0x0002 != 0 { - data = undoUnsynchronisation(data) + data = tagread.UndoUnsynchronisation(data) } return data, true } @@ -333,56 +310,3 @@ func decodeUTF16(b []byte, bigEndian bool) string { } return string(utf16.Decode(units)) } - -// skipExtendedHeader advances past the optional extended header. The two -// versions disagree about whether the size field counts itself, which is worth -// spelling out because getting it wrong offsets the entire frame list by four -// bytes and makes every frame id look like padding. -func skipExtendedHeader(body []byte, major byte) ([]byte, bool) { - if len(body) < 4 { - return nil, false - } - if major == 3 { - // 2.3: size EXCLUDES the four size bytes themselves. - size := int(binary.BigEndian.Uint32(body[0:4])) - if size < 0 || 4+size > len(body) { - return nil, false - } - return body[4+size:], true - } - // 2.4: syncsafe size INCLUDING the size bytes. - size := syncsafeInt(body[0:4]) - if size < 4 || size > len(body) { - return nil, false - } - return body[size:], true -} - -// syncsafeInt decodes a 4-byte synchsafe integer (7 significant bits per byte). -func syncsafeInt(b []byte) int { - if len(b) < 4 { - return -1 - } - // A set high bit means this isn't a valid synchsafe integer. Some writers - // emit a plain big-endian size here; refusing is safer than silently - // dropping bits and walking to a wrong offset. - for _, c := range b[:4] { - if c&0x80 != 0 { - return -1 - } - } - return int(b[0])<<21 | int(b[1])<<14 | int(b[2])<<7 | int(b[3]) -} - -// undoUnsynchronisation collapses the 0xFF 0x00 pairs that unsynchronisation -// inserts to stop a tag from looking like an MPEG frame sync. -func undoUnsynchronisation(b []byte) []byte { - out := make([]byte, 0, len(b)) - for i := 0; i < len(b); i++ { - out = append(out, b[i]) - if b[i] == 0xFF && i+1 < len(b) && b[i+1] == 0x00 { - i++ - } - } - return out -} diff --git a/internal/library/leveled.go b/internal/library/leveled.go index d13360f7..770e3548 100644 --- a/internal/library/leveled.go +++ b/internal/library/leveled.go @@ -19,6 +19,8 @@ import ( "time" "golang.org/x/sync/singleflight" + + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // Leveled streams. @@ -242,9 +244,11 @@ func (r *LeveledRenderer) Prerender(src LeveledSource, g LeveledGain) bool { defer func() { <-r.prerenders }() ctx, cancel := context.WithTimeout(context.Background(), loudnessTimeout(src.DurationMs)) defer cancel() - if _, err := r.Path(ctx, src, g); err != nil { - r.logger.Warn("leveled: prerender failed", "track", src.TrackID, "err", err) - } + periodic.Safe(ctx, r.logger, "leveled prerender", func(ctx context.Context) { + if _, err := r.Path(ctx, src, g); err != nil { + r.logger.Warn("leveled: prerender failed", "track", src.TrackID, "err", err) + } + }) }() return true } diff --git a/internal/library/library_paths.go b/internal/library/library_paths.go index fe0a9a5f..33735b51 100644 --- a/internal/library/library_paths.go +++ b/internal/library/library_paths.go @@ -12,7 +12,8 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // The library's folders. They are set in Settings and changed without @@ -80,13 +81,13 @@ func (s *Scanner) SetRoots(ctx context.Context, changes []RootChange) (RerootRes q := dbq.New(s.pool) // A scan walking the old folders would put their paths back, or mark the // moved rows missing when it reconciles. - _, err = q.GetInFlightScanRun(ctx) - if err == nil { - return RerootResult{}, badRoots("A library scan is running; save again once it finishes.") - } - if !errors.Is(err, pgx.ErrNoRows) { + running, err := scanRunning(ctx, q) + if err != nil { return RerootResult{}, fmt.Errorf("in-flight scan check: %w", err) } + if running { + return RerootResult{}, badRoots("A library scan is running; save again once it finishes.") + } for _, m := range moves { if err := checkMove(ctx, q, m); err != nil { return RerootResult{}, err @@ -99,7 +100,7 @@ func (s *Scanner) SetRoots(ctx context.Context, changes []RootChange) (RerootRes for _, m := range moves { n, err := tq.RerootTrackPaths(ctx, dbq.RerootTrackPathsParams{NewRoot: m.Path, OldRoot: m.Was}) if err != nil { - if isUniqueViolation(err) { + if db.IsUniqueViolation(err) { return badRoots("Some tracks under %s are already in the library at %s, "+ "so its tracks cannot move there.", m.Was, m.Path) } @@ -109,12 +110,6 @@ func (s *Scanner) SetRoots(ctx context.Context, changes []RootChange) (RerootRes if _, err := tq.RerootAlbumCoverPaths(ctx, dbq.RerootAlbumCoverPathsParams{NewRoot: m.Path, OldRoot: m.Was}); err != nil { return fmt.Errorf("reroot covers: %w", err) } - if _, err := tq.RerootGrabDestinations(ctx, dbq.RerootGrabDestinationsParams{NewRoot: m.Path, OldRoot: m.Was}); err != nil { - return fmt.Errorf("reroot downloads: %w", err) - } - if _, err := tq.RerootImportRoot(ctx, dbq.RerootImportRootParams{NewRoot: m.Path, OldRoot: m.Was}); err != nil { - return fmt.Errorf("reroot import folder: %w", err) - } } _, err := tq.UpdateLibraryScanPaths(ctx, roots) return err diff --git a/internal/library/library_paths_test.go b/internal/library/library_paths_test.go index aa3cd5e2..fd9d367f 100644 --- a/internal/library/library_paths_test.go +++ b/internal/library/library_paths_test.go @@ -13,7 +13,8 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func mkdir(t *testing.T, parts ...string) string { @@ -84,7 +85,7 @@ func clearSavedRoots(t *testing.T, pool *pgxpool.Pool) { } func TestSetRoots_TracksMoveWithTheirFolder_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) clearSavedRoots(t, pool) ctx := context.Background() base := t.TempDir() @@ -126,7 +127,7 @@ func TestSetRoots_TracksMoveWithTheirFolder_Integration(t *testing.T) { } func TestSetRoots_RefusesAMoveToAFolderWithoutTheFiles_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) clearSavedRoots(t, pool) ctx := context.Background() base := t.TempDir() diff --git a/internal/library/loudness.go b/internal/library/loudness.go index ac6c8daa..b719c690 100644 --- a/internal/library/loudness.go +++ b/internal/library/loudness.go @@ -16,8 +16,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Loudness analysis. diff --git a/internal/library/loudness_backfill.go b/internal/library/loudness_backfill.go index afcae46f..ef3c8806 100644 --- a/internal/library/loudness_backfill.go +++ b/internal/library/loudness_backfill.go @@ -10,7 +10,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // Loudness backfill. @@ -92,27 +93,11 @@ func NewLoudnessBackfillWorker( // Run blocks until ctx is cancelled: one pass at start, then one per tick. func (w *LoudnessBackfillWorker) Run(ctx context.Context) { - w.runOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.runOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "loudness backfill", w.tick, w.runOnce) } -// runOnce contains a pass so that nothing it does (an error, a panic) can stop -// the next tick from firing. +// runOnce runs one pass and logs what it did. periodic.Run contains a panic. func (w *LoudnessBackfillWorker) runOnce(ctx context.Context) { - defer func() { - if r := recover(); r != nil { - w.logger.Error("loudness backfill: pass panicked", "panic", r) - } - }() res, err := w.pass(ctx) if err != nil && ctx.Err() == nil { w.logger.Warn("loudness backfill: pass failed", "err", err, "processed", res.Processed) diff --git a/internal/library/loudness_backfill_test.go b/internal/library/loudness_backfill_test.go index b650f733..8d70c09f 100644 --- a/internal/library/loudness_backfill_test.go +++ b/internal/library/loudness_backfill_test.go @@ -10,15 +10,16 @@ import ( "sync" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // TestLoudnessBackfill_Integration pins which tracks a pass measures, what it // stores for each kind of result, that a pass ends, and that the gauge counts // what the passes wrote. func TestLoudnessBackfill_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -230,7 +231,7 @@ func TestLoudnessBackfill_Integration(t *testing.T) { // The Go defaults must match the migration's, or a database that cannot be // read would analyze differently from a fresh install. func TestLoudnessSettings_DefaultsMatchMigration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s, err := NewLoudnessSettingsService(context.Background(), pool) if err != nil { t.Fatalf("load: %v", err) diff --git a/internal/library/loudness_settings.go b/internal/library/loudness_settings.go index 21fe1bad..360d49b9 100644 --- a/internal/library/loudness_settings.go +++ b/internal/library/loudness_settings.go @@ -9,7 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // Loudness analysis settings: a database row, changed without a restart. One @@ -29,7 +29,7 @@ type LoudnessSettings struct { UpdatedAt time.Time } -// DefaultLoudnessSettings mirrors migrations 0065 and 0068's column defaults, +// DefaultLoudnessSettings mirrors loudness_settings's column defaults, // so a database that cannot be read still analyzes the way a fresh install // does. var DefaultLoudnessSettings = LoudnessSettings{ @@ -38,14 +38,14 @@ var DefaultLoudnessSettings = LoudnessSettings{ LeveledCacheMB: 2048, } -// The leveled-stream cache's bounds, as migration 0068's CHECK has them. +// The leveled-stream cache's bounds, as loudness_settings's CHECK has them. const ( minLeveledCacheMB = 256 maxLeveledCacheMB = 65536 ) -// ErrLoudnessSettingOutOfRange is returned by Set for a value migration 0065's -// CHECK would reject, so the API answers 400 naming the field. +// ErrLoudnessSettingOutOfRange is returned by Set for a value loudness_settings's +// CHECKs would reject, so the API answers 400 naming the field. var ErrLoudnessSettingOutOfRange = errors.New("loudness setting out of range") // LoudnessSettingsService caches the settings and owns their persistence. diff --git a/internal/library/mbidbackfill.go b/internal/library/mbidbackfill.go index 2ebffced..90852eee 100644 --- a/internal/library/mbidbackfill.go +++ b/internal/library/mbidbackfill.go @@ -2,30 +2,18 @@ package library import ( "context" - "errors" "fmt" "log/slog" "os" - "github.com/dhowden/tag" - "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/tagread" ) -// pgUniqueViolation is the SQLSTATE for a unique-constraint conflict. -const pgUniqueViolation = "23505" - -// isUniqueViolation reports whether err is a Postgres unique-constraint -// conflict. Used to distinguish "another row already owns this MBID" (a -// duplicate album/artist row in our DB, for an admin to merge) from genuine -// write failures. -func isUniqueViolation(err error) bool { - var pgErr *pgconn.PgError - return errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation -} - // BackfillMBIDsResult tallies what the one-shot worker did. type BackfillMBIDsResult struct { Processed int // Albums considered (mbid IS NULL). @@ -80,7 +68,7 @@ func BackfillMBIDs(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, if err := q.SetAlbumMbidIfNull(ctx, dbq.SetAlbumMbidIfNullParams{ ID: r.AlbumID, Mbid: &m, }); err != nil { - if isUniqueViolation(err) { + if db.IsUniqueViolation(err) { // Another album row already owns this MBID — i.e. our DB // has two rows for the same MusicBrainz release (split by // title/artist disagreements during the pre-MBID scan). @@ -103,19 +91,27 @@ func BackfillMBIDs(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, continue } + // The album's mbid is part of what the library sync sends, so an app + // hears about the heal through the change log. + if err := syncpkg.LogChange(ctx, pool, syncpkg.EntityAlbum, syncpkg.FormatUUID(r.AlbumID), syncpkg.OpUpsert); err != nil { + logger.Warn("mbid backfill: log album change failed", "album_id", r.AlbumID, "err", err) + } + // Heal artist (if we got one). if artistMBID != "" { am := artistMBID if err := q.SetArtistMbidIfNull(ctx, dbq.SetArtistMbidIfNullParams{ ID: r.ArtistID, Mbid: &am, }); err != nil { - if isUniqueViolation(err) { + if db.IsUniqueViolation(err) { logger.Info("mbid backfill: duplicate artist mbid (canonical row already owns it)", "artist_id", r.ArtistID, "mbid", artistMBID) } else { logger.Warn("mbid backfill: set artist mbid failed", "artist_id", r.ArtistID, "err", err) } + } else if err := syncpkg.LogChange(ctx, pool, syncpkg.EntityArtist, syncpkg.FormatUUID(r.ArtistID), syncpkg.OpUpsert); err != nil { + logger.Warn("mbid backfill: log artist change failed", "artist_id", r.ArtistID, "err", err) } } @@ -160,7 +156,7 @@ func readMBIDsForFile(path string, logger *slog.Logger) (albumMBID, artistMBID s } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { logger.Warn("mbid backfill: tag read failed", "path", path, "err", err) return "", "" @@ -254,7 +250,7 @@ func readRecordingMBIDForFile(path string, logger *slog.Logger) string { } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { logger.Warn("track mbid backfill: tag read failed", "path", path, "err", err) return "" diff --git a/internal/library/mbidbackfill_test.go b/internal/library/mbidbackfill_test.go index 990d6e45..86e3d6ec 100644 --- a/internal/library/mbidbackfill_test.go +++ b/internal/library/mbidbackfill_test.go @@ -9,14 +9,15 @@ import ( "strings" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // The MBID backfills read tags from files, so a track whose file is gone has // nothing to give them: they skip it rather than log an "open failed" warning // per missing track on every scan. func TestMBIDBackfill_SkipsMissingTracks_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/mbids.go b/internal/library/mbids.go index 85bad411..e8c64027 100644 --- a/internal/library/mbids.go +++ b/internal/library/mbids.go @@ -12,9 +12,14 @@ import ( type TagMBIDs struct { // Release is musicbrainz_albumid: one edition, what albums.mbid stores. Release string - Artist string - // ReleaseGroup is musicbrainz_releasegroupid. Wants name albums by - // release group, so re-acquisition and request completion key on it. + // Artist is the track's own artist (musicbrainz_artistid). + Artist string + // AlbumArtist is musicbrainz_albumartistid: who the album is filed + // under, which on a compilation or a track with a featured artist is + // not the track's artist. + AlbumArtist string + // ReleaseGroup is musicbrainz_releasegroupid. The duplicate resolver + // reads an album's MusicBrainz track lists by it. ReleaseGroup string // Recording is what tracks.mbid stores and the ListenBrainz Labs // similar-recordings API keys on. @@ -40,6 +45,7 @@ func ReadTagMBIDs(m tag.Metadata) TagMBIDs { ids := TagMBIDs{ Release: cleanMBID(info.Get(mbz.Album)), Artist: cleanMBID(info.Get(mbz.Artist)), + AlbumArtist: cleanMBID(info.Get(mbz.AlbumArtist)), ReleaseGroup: cleanMBID(info.Get(mbz.ReleaseGroup)), Recording: cleanMBID(info.Get(mbz.Recording)), } diff --git a/internal/library/mbids_test.go b/internal/library/mbids_test.go index 7f3471d4..640e127c 100644 --- a/internal/library/mbids_test.go +++ b/internal/library/mbids_test.go @@ -31,215 +31,65 @@ func (s stubMeta) Lyrics() string { return "" } func (s stubMeta) Comment() string { return "" } func (s stubMeta) Raw() map[string]interface{} { return s.raw } -func TestExtractMBIDs_Vorbis(t *testing.T) { - // dhowden lowercases all Vorbis comment keys at parse time. - m := stubMeta{ - format: tag.VORBIS, - raw: map[string]interface{}{ - "musicbrainz_albumid": "abc", - "musicbrainz_artistid": "def", - }, - } - ids := ReadTagMBIDs(m) - a, ar := ids.Release, ids.Artist - if a != "abc" || ar != "def" { - t.Errorf("got (%q, %q), want (\"abc\", \"def\")", a, ar) - } -} - -func TestExtractMBIDs_ID3v2(t *testing.T) { - // dhowden stores TXXX frames under bare "TXXX"/"TXXX_N" keys with - // *tag.Comm values whose Description holds the Picard tag name. - m := stubMeta{ - format: tag.ID3v2_4, - raw: map[string]interface{}{ - "TXXX": &tag.Comm{ - Description: "MusicBrainz Album Id", - Text: "abc-123", - }, - "TXXX_0": &tag.Comm{ - Description: "MusicBrainz Artist Id", - Text: "def-456", - }, - }, - } - ids := ReadTagMBIDs(m) - a, ar := ids.Release, ids.Artist - if a != "abc-123" || ar != "def-456" { - t.Errorf("got (%q, %q), want (\"abc-123\", \"def-456\")", a, ar) - } -} - -func TestExtractMBIDs_MP4(t *testing.T) { - // dhowden stores freeform iTunes atoms under their bare sub-name. - // mbz.Extract maps the human-readable form back to its lowercase key. - m := stubMeta{ - format: tag.MP4, - raw: map[string]interface{}{ - "MusicBrainz Album Id": "abc", - "MusicBrainz Artist Id": "def", - }, - } - ids := ReadTagMBIDs(m) - a, ar := ids.Release, ids.Artist - if a != "abc" || ar != "def" { - t.Errorf("got (%q, %q), want (\"abc\", \"def\")", a, ar) - } -} - -func TestExtractMBIDs_MissingTagsReturnEmpty(t *testing.T) { - m := stubMeta{format: tag.VORBIS, raw: map[string]interface{}{}} - ids := ReadTagMBIDs(m) - a, ar := ids.Release, ids.Artist - if a != "" || ar != "" { - t.Errorf("got (%q, %q), want empty", a, ar) - } -} - -func TestExtractMBIDs_VorbisUppercaseKeysMiss(t *testing.T) { - // Real dhowden never produces uppercase Vorbis keys. Looking up - // "MUSICBRAINZ_ALBUMID" directly would find nothing, and every album - // would be skipped; this test keeps that lookup returning empty. - m := stubMeta{ - format: tag.VORBIS, - raw: map[string]interface{}{ - "MUSICBRAINZ_ALBUMID": "wrong-case", - "MUSICBRAINZ_ARTISTID": "wrong-case", - }, - } - ids := ReadTagMBIDs(m) - a, ar := ids.Release, ids.Artist - if a != "" || ar != "" { - t.Errorf("uppercase Vorbis keys must not match dhowden output; got (%q, %q)", a, ar) - } -} - -func TestExtractMBIDs_ID3v2StripsTrailingNUL(t *testing.T) { - // dhowden's readTextWithDescrFrame leaves the ID3v2.4 frame- - // terminator NUL on TXXX values. Postgres rejects NULs in text - // columns (SQLSTATE 22021), so we must strip them. - m := stubMeta{ - format: tag.ID3v2_4, - raw: map[string]interface{}{ - "TXXX": &tag.Comm{ - Description: "MusicBrainz Album Id", - Text: "abc-123\x00", - }, - "TXXX_0": &tag.Comm{ - Description: "MusicBrainz Artist Id", - Text: "def-456\x00", - }, - }, - } - ids := ReadTagMBIDs(m) - a, ar := ids.Release, ids.Artist - if a != "abc-123" || ar != "def-456" { - t.Errorf("got (%q, %q), want trailing NUL stripped", a, ar) - } -} - -func TestExtractMBIDs_ID3v2MultiValueTakesFirst(t *testing.T) { - // Some Picard configs emit multi-value TXXX:MusicBrainz Artist Id - // for collaborations, NUL-separated. Minstrel uses the primary - // release artist for MBCAA, so first wins. - m := stubMeta{ - format: tag.ID3v2_4, - raw: map[string]interface{}{ - "TXXX": &tag.Comm{ - Description: "MusicBrainz Artist Id", - Text: "primary-mbid\x00collab-mbid", - }, - }, - } - ar := ReadTagMBIDs(m).Artist - if ar != "primary-mbid" { - t.Errorf("got %q, want %q", ar, "primary-mbid") - } -} - -func TestCleanMBID_OnlyNULReturnsEmpty(t *testing.T) { - // Defensive: a TXXX value that is purely NULs (or empty after - // trimming) must round-trip to empty so the caller skips the row - // instead of writing a NUL-only string to Postgres. - if got := cleanMBID("\x00\x00"); got != "" { - t.Errorf("got %q, want empty", got) - } - if got := cleanMBID(""); got != "" { - t.Errorf("got %q, want empty", got) - } -} - -// The release-group id is read beside the release id, from each -// format's own key, and the two are never confused. -func TestExtractReleaseGroupMBID(t *testing.T) { - cases := []struct { +// ReadTagMBIDs reads each MusicBrainz id from each format's own Picard key, +// in dhowden/tag's Raw() shape for that format: Vorbis keys lowercased, ID3 +// TXXX frames under "TXXX"/"TXXX_N" with the Picard name in the Description, +// MP4 freeform atoms under their bare name. The release and the release +// group, and the recording and the release track, are never confused. +func TestReadTagMBIDs(t *testing.T) { + all := TagMBIDs{Release: "rel-1", Artist: "ar-1", AlbumArtist: "aa-1", ReleaseGroup: "rg-1", Recording: "rec-1"} + txxx := func(name, text string) *tag.Comm { return &tag.Comm{Description: name, Text: text} } + for _, tc := range []struct { name string meta stubMeta + want TagMBIDs }{ {"vorbis", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{ - "musicbrainz_albumid": "release-1", - "musicbrainz_releasegroupid": "group-1", - }}}, + "musicbrainz_albumid": "rel-1", "musicbrainz_artistid": "ar-1", "musicbrainz_albumartistid": "aa-1", + "musicbrainz_releasegroupid": "rg-1", + // Picard calls the recording MUSICBRAINZ_TRACKID in Vorbis, the + // name mbz gives the release track. + "musicbrainz_trackid": "rec-1", "musicbrainz_releasetrackid": "reltrack-1", + }}, all}, + // dhowden leaves ID3v2.4's terminating NUL on TXXX values, and + // Postgres rejects NULs in text (SQLSTATE 22021). {"id3v2", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{ - "TXXX": &tag.Comm{Description: "MusicBrainz Album Id", Text: "release-1"}, - "TXXX_0": &tag.Comm{Description: "MusicBrainz Release Group Id", Text: "group-1\x00"}, - }}}, - {"mp4", stubMeta{format: tag.MP4, raw: map[string]interface{}{ - "MusicBrainz Album Id": "release-1", - "MusicBrainz Release Group Id": "group-1", - }}}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - if got := ReadTagMBIDs(c.meta).ReleaseGroup; got != "group-1" { - t.Errorf("release group = %q, want group-1", got) - } - if album := ReadTagMBIDs(c.meta).Release; album != "release-1" { - t.Errorf("album (release) = %q, want release-1", album) - } - }) - } - - none := stubMeta{format: tag.VORBIS, raw: map[string]interface{}{"musicbrainz_albumid": "release-1"}} - if got := ReadTagMBIDs(none).ReleaseGroup; got != "" { - t.Errorf("untagged release group = %q, want empty", got) - } -} - -// Each format's recording id lands in Recording, and the release-track -// id never does. Picard calls the recording MUSICBRAINZ_TRACKID in Vorbis -// comments, the name mbz gives the release track. -func TestReadTagMBIDs_Recording(t *testing.T) { - cases := []struct { - name string - meta stubMeta - }{ - {"vorbis", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{ - "musicbrainz_trackid": "rec-1", - "musicbrainz_releasetrackid": "reltrack-1", - }}}, - {"id3v2 ufid", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{ + "TXXX": txxx("MusicBrainz Album Id", "rel-1\x00"), + "TXXX_0": txxx("MusicBrainz Artist Id", "ar-1"), + "TXXX_1": txxx("MusicBrainz Album Artist Id", "aa-1\x00"), + "TXXX_2": txxx("MusicBrainz Release Group Id", "rg-1\x00"), + "TXXX_3": txxx("MusicBrainz Release Track Id", "reltrack-1\x00"), "UFID": &tag.UFID{Provider: "http://musicbrainz.org", Identifier: []byte("rec-1")}, - "TXXX_0": &tag.Comm{Description: "MusicBrainz Release Track Id", Text: "reltrack-1\x00"}, - }}}, + }}, all}, {"mp4", stubMeta{format: tag.MP4, raw: map[string]interface{}{ - "MusicBrainz Track Id": "rec-1", - "MusicBrainz Release Track Id": "reltrack-1", - }}}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - if got := ReadTagMBIDs(c.meta).Recording; got != "rec-1" { - t.Errorf("recording = %q, want rec-1", got) + "MusicBrainz Album Id": "rel-1", "MusicBrainz Artist Id": "ar-1", "MusicBrainz Album Artist Id": "aa-1", + "MusicBrainz Release Group Id": "rg-1", "MusicBrainz Track Id": "rec-1", "MusicBrainz Release Track Id": "reltrack-1", + }}, all}, + {"untagged", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{}}, TagMBIDs{}}, + // dhowden never produces uppercase Vorbis keys; a lookup by the + // uppercase name would find nothing in a real file. + {"uppercase vorbis keys", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{ + "MUSICBRAINZ_ALBUMID": "wrong-case", "MUSICBRAINZ_ARTISTID": "wrong-case", + }}, TagMBIDs{}}, + {"a vorbis release track is not a recording", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{ + "musicbrainz_releasetrackid": "reltrack-1", + }}, TagMBIDs{}}, + // Some Picard configs write collaborations NUL-separated; Minstrel + // uses the primary artist, so the first value wins. + {"id3 multi-value takes the first", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{ + "TXXX": txxx("MusicBrainz Artist Id", "primary-mbid\x00collab-mbid"), + }}, TagMBIDs{Artist: "primary-mbid"}}, + // A value that is only NULs is absent, not a NUL string for Postgres. + {"id3 value of only NULs", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{ + "TXXX": txxx("MusicBrainz Album Id", "\x00\x00"), + }}, TagMBIDs{}}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := ReadTagMBIDs(tc.meta); got != tc.want { + t.Errorf("got %+v\nwant %+v", got, tc.want) } }) } - - // A Vorbis file carrying only the release-track id has no recording id. - only := stubMeta{format: tag.VORBIS, raw: map[string]interface{}{"musicbrainz_releasetrackid": "reltrack-1"}} - if got := ReadTagMBIDs(only).Recording; got != "" { - t.Errorf("release track only: recording = %q, want empty", got) - } } // A Vorbis TRACKNUMBER of "3/20" is track 3: dhowden/tag reads it as 0. diff --git a/internal/library/missing_pairs.go b/internal/library/missing_pairs.go index bcde5643..95e02692 100644 --- a/internal/library/missing_pairs.go +++ b/internal/library/missing_pairs.go @@ -10,7 +10,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // Missing-pair folding. diff --git a/internal/library/missing_pairs_test.go b/internal/library/missing_pairs_test.go index 7e2b24fc..4d16b3ec 100644 --- a/internal/library/missing_pairs_test.go +++ b/internal/library/missing_pairs_test.go @@ -13,9 +13,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) func TestPairStillHolds(t *testing.T) { @@ -114,7 +114,7 @@ func (f pairFixture) count(sql string, args ...any) int { // On rows: each rule folds the pair it should, history moves onto // the replacement, and every shape the pass must leave alone is left alone. func TestPairMissingTracks_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Pair Artist", SortName: "Pair Artist"}) @@ -236,7 +236,7 @@ func TestPairMissingTracks_Integration(t *testing.T) { // arrives at a new path with no recording MBID, so move adoption has nothing to // match. The scan must still end with one row, carrying the old row's history. func TestScanner_FoldsUpgradedFile_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) diff --git a/internal/library/moved.go b/internal/library/moved.go index 55b5eb99..67de68eb 100644 --- a/internal/library/moved.go +++ b/internal/library/moved.go @@ -5,8 +5,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Move detection. diff --git a/internal/library/moved_test.go b/internal/library/moved_test.go index 0c32383a..03d31491 100644 --- a/internal/library/moved_test.go +++ b/internal/library/moved_test.go @@ -6,9 +6,7 @@ import ( "errors" "testing" - "github.com/jackc/pgx/v5/pgtype" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // fakeAdopter answers the audio-hash lookup only for the hash it holds, the way @@ -68,238 +66,79 @@ func hashRow(n byte, path string) dbq.FindMissingTrackByAudioHashRow { func audioHash(b byte) []byte { return bytes.Repeat([]byte{b}, 32) } const ( - oldPath = "/music/Linkin Park/Minutes to Midnight/02 - Bleed It Out.mp3" - newPath = "/music/Linkin Park/Minutes to Midnight/04 - Bleed It Out.mp3" + oldPath = "/music/Lincoln Yard/Minutes to Noon/02 - Ring It Out.mp3" + newPath = "/music/Lincoln Yard/Minutes to Noon/04 - Ring It Out.mp3" ) -func TestAdoptMovedTrack_MatchesByMbid(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(7, oldPath)}, adoptRows: 1} - - if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(1), "rec-mbid") { - t.Fatal("expected the moved track to be adopted") - } - if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(7) || q.adopted[0].FilePath != newPath { - t.Fatalf("adopted = %+v, want row 7 at %q", q.adopted, newPath) - } - // MBID matched, so the weaker signal should not have been consulted. - if len(q.hashQueried) != 0 { - t.Errorf("queried the audio hash despite an MBID match") - } -} - -func TestAdoptMovedTrack_FallsBackToAudioHash(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{hash: audioHash(3), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(3, oldPath)}, adoptRows: 1} - - // No MBID: an untagged file, which is exactly what the fallback is for. - if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(3), "") { - t.Fatal("expected adoption via the audio hash") - } - if len(q.mbidQueried) != 0 { - t.Errorf("queried by MBID with no MBID available") - } - if len(q.hashQueried) != 1 || !bytes.Equal(q.hashQueried[0], audioHash(3)) { - t.Fatalf("hash queried = %x, want exactly the file's hash", q.hashQueried) - } - if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(3) { - t.Errorf("adopted = %+v, want row 3", q.adopted) - } -} - -// An unrelated file that happens to share a size and a duration with a missing -// track is not adopted. Size and duration are not inputs at all; only the -// audio itself can match, and a different recording has a different hash. -func TestAdoptMovedTrack_DifferentAudioIsNotAdopted(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{hash: audioHash(0xAA), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1} - - if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(0xBB), "") { - t.Fatal("adopted a missing track whose audio differs") - } - if len(q.adopted) != 0 { - t.Errorf("adopted = %+v, want none", q.adopted) - } -} - -// Two missing rows carrying the same recording MBID means real duplicates. -// Adopting one arbitrarily would attach this file's future history to a coin -// flip, so it must insert fresh instead. -func TestAdoptMovedTrack_RefusesAmbiguousMbidMatch(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{ - mbidRow(1, "/music/a.mp3"), - mbidRow(2, "/music/b.mp3"), - }, adoptRows: 1} - - if s.adoptMovedTrack(context.Background(), q, newPath, nil, "rec-mbid") { - t.Fatal("expected refusal on an ambiguous MBID match") - } - if len(q.adopted) != 0 { - t.Errorf("adopted despite ambiguity: %+v", q.adopted) - } -} - -// An ambiguous MBID may still be resolvable by the audio hash, which is a -// narrower signal — so falling through is allowed to succeed. -func TestAdoptMovedTrack_AmbiguousMbidFallsThroughToAudioHash(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{ - byMbid: []dbq.FindMissingTrackByMbidRow{ - mbidRow(1, "/music/a.mp3"), - mbidRow(2, "/music/b.mp3"), - }, - hash: audioHash(2), - byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(2, "/music/b.mp3")}, - adoptRows: 1, - } - - if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(2), "rec-mbid") { - t.Fatal("expected the audio hash to disambiguate") - } - if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(2) { - t.Errorf("adopted = %+v, want row 2", q.adopted) - } -} - -// Two missing tracks with identical audio are duplicates of each other; a new -// file matching both cannot be assigned to either. -func TestAdoptMovedTrack_RefusesAmbiguousAudioHashMatch(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{hash: audioHash(5), byHash: []dbq.FindMissingTrackByAudioHashRow{ - hashRow(1, "/music/a.mp3"), - hashRow(2, "/music/b.mp3"), - }, adoptRows: 1} - - if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(5), "") { - t.Fatal("expected refusal on an ambiguous audio-hash match") - } - if len(q.adopted) != 0 { - t.Errorf("adopted despite ambiguity: %+v", q.adopted) - } -} - -// No hash means it could not be taken. An empty hash must never be looked up: -// every unhashable file would pair with every other. -func TestAdoptMovedTrack_SkipsAudioHashWhenAbsent(t *testing.T) { - for name, hash := range map[string][]byte{"nil": nil, "empty": {}} { - t.Run(name, func(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{hash: hash, byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1} - if s.adoptMovedTrack(context.Background(), q, newPath, hash, "") { - t.Error("adopted without an audio hash") - } - if len(q.hashQueried) != 0 { - t.Error("looked up an absent audio hash") - } - }) - } -} - -func TestAdoptMovedTrack_NoCandidates(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{adoptRows: 1} - - if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(9), "rec-mbid") { - t.Fatal("expected no adoption when nothing matches") - } - if len(q.adopted) != 0 { - t.Errorf("adopted with no candidates: %+v", q.adopted) - } -} - -// The row's mark was cleared between lookup and update — another file adopted -// it first. AdoptTrackPath's `missing_since IS NOT NULL` predicate reports 0 -// rows. -func TestAdoptMovedTrack_LostRaceReportsNotAdopted(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{ - byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(5, oldPath)}, - adoptRows: 0, - } - - if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(5), "rec-mbid") { - t.Fatal("expected not-adopted when the update matched no rows") - } -} - -// Failing to detect a move must never fail the file: the caller falls back to -// inserting a fresh row. -func TestAdoptMovedTrack_ToleratesQueryErrors(t *testing.T) { +// A new file is adopted as a missing track that moved when its recording MBID +// names exactly one missing track, or failing that its audio hash does. Size +// and duration are not inputs: only identity can match. Anything ambiguous, or +// any failure, inserts the file fresh instead: adopting by coin flip would +// attach the wrong history, and failing to detect a move must never fail the +// file. +func TestAdoptMovedTrack(t *testing.T) { sentinel := errors.New("db down") - tests := []struct { + twoMbid := []dbq.FindMissingTrackByMbidRow{mbidRow(1, "/music/a.mp3"), mbidRow(2, "/music/b.mp3")} + for _, tc := range []struct { name string q *fakeAdopter + hash []byte + mbid string + // want is the adopted row's id byte; 0 means nothing adopted. + want byte + // noHashLookup: the audio hash must not be looked up at all. + noHashLookup bool }{ - {"mbid lookup fails", &fakeAdopter{mbidErr: sentinel}}, - {"audio hash lookup fails", &fakeAdopter{hashErr: sentinel}}, - {"adopt fails", &fakeAdopter{ - byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(1, oldPath)}, - adoptErr: sentinel, - }}, - } - for _, tc := range tests { + {name: "by MBID, without consulting the hash", hash: audioHash(1), mbid: "rec-mbid", want: 7, noHashLookup: true, + q: &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(7, oldPath)}, adoptRows: 1}}, + {name: "by audio hash when untagged", hash: audioHash(3), want: 3, + q: &fakeAdopter{hash: audioHash(3), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(3, oldPath)}, adoptRows: 1}}, + {name: "different audio", hash: audioHash(0xBB), + q: &fakeAdopter{hash: audioHash(0xAA), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}}, + {name: "two missing tracks share the MBID", mbid: "rec-mbid", + q: &fakeAdopter{byMbid: twoMbid, adoptRows: 1}}, + {name: "an ambiguous MBID settled by the hash", hash: audioHash(2), mbid: "rec-mbid", want: 2, + q: &fakeAdopter{byMbid: twoMbid, hash: audioHash(2), + byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(2, "/music/b.mp3")}, adoptRows: 1}}, + {name: "two missing tracks share the audio", hash: audioHash(5), + q: &fakeAdopter{hash: audioHash(5), byHash: []dbq.FindMissingTrackByAudioHashRow{ + hashRow(1, "/music/a.mp3"), hashRow(2, "/music/b.mp3")}, adoptRows: 1}}, + // Every unhashable file would pair with every other. + {name: "no hash taken (nil)", hash: nil, noHashLookup: true, + q: &fakeAdopter{hash: nil, byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}}, + {name: "no hash taken (empty)", hash: []byte{}, noHashLookup: true, + q: &fakeAdopter{hash: []byte{}, byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}}, + {name: "no candidates", hash: audioHash(9), mbid: "rec-mbid", + q: &fakeAdopter{adoptRows: 1}}, + // Another file adopted the row between lookup and update; the + // missing_since predicate matches no row. + {name: "lost the race", hash: audioHash(5), mbid: "rec-mbid", + q: &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(5, oldPath)}, adoptRows: 0}}, + {name: "the hash lookup fails", hash: audioHash(1), mbid: "rec-mbid", + q: &fakeAdopter{hashErr: sentinel}}, + {name: "the adopt fails", hash: audioHash(1), mbid: "rec-mbid", + q: &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(1, oldPath)}, adoptErr: sentinel}}, + {name: "an MBID lookup error still tries the hash", hash: audioHash(9), mbid: "rec-mbid", want: 9, + q: &fakeAdopter{mbidErr: sentinel, hash: audioHash(9), + byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(9, oldPath)}, adoptRows: 1}}, + } { t.Run(tc.name, func(t *testing.T) { s := testScanner(t) - if s.adoptMovedTrack(context.Background(), tc.q, newPath, audioHash(1), "rec-mbid") { - t.Error("reported adoption despite a query error") + got := s.adoptMovedTrack(context.Background(), tc.q, newPath, tc.hash, tc.mbid) + if got != (tc.want != 0) { + t.Fatalf("adopted = %v, want %v", got, tc.want != 0) + } + if tc.want != 0 { + if n := len(tc.q.adopted); n == 0 || tc.q.adopted[n-1].ID != testUUID(tc.want) || tc.q.adopted[n-1].FilePath != newPath { + t.Errorf("adopted %+v, want row %d at %q", tc.q.adopted, tc.want, newPath) + } + } + if tc.mbid == "" && len(tc.q.mbidQueried) != 0 { + t.Error("queried by MBID with no MBID available") + } + if tc.noHashLookup && len(tc.q.hashQueried) != 0 { + t.Errorf("looked up the audio hash: %x", tc.q.hashQueried) } }) } } - -// A failed MBID lookup must not stop the audio hash from being tried. -func TestAdoptMovedTrack_MbidErrorStillTriesAudioHash(t *testing.T) { - s := testScanner(t) - q := &fakeAdopter{ - mbidErr: errors.New("db hiccup"), - hash: audioHash(9), - byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(9, oldPath)}, - adoptRows: 1, - } - - if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(9), "rec-mbid") { - t.Fatal("expected the audio hash to be tried after an MBID lookup error") - } - if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(9) { - t.Errorf("adopted = %+v, want row 9", q.adopted) - } -} - -func TestUniqueMatch(t *testing.T) { - s := testScanner(t) - if _, ok := s.uniqueMatch(nil, newPath, "mbid"); ok { - t.Error("empty candidate set matched") - } - c, ok := s.uniqueMatch([]candidate{{id: testUUID(4), filePath: oldPath}}, newPath, "mbid") - if !ok { - t.Fatal("single candidate did not match") - } - if c.id != testUUID(4) || c.filePath != oldPath { - t.Errorf("candidate = %+v, want id 4 at %q", c, oldPath) - } - if _, ok := s.uniqueMatch([]candidate{ - {id: testUUID(1)}, {id: testUUID(2)}, - }, newPath, "mbid"); ok { - t.Error("multiple candidates matched") - } -} - -func TestRowConverters(t *testing.T) { - got := rowsFromMbid([]dbq.FindMissingTrackByMbidRow{mbidRow(1, "/a"), mbidRow(2, "/b")}) - if len(got) != 2 || got[0].id != testUUID(1) || got[1].filePath != "/b" { - t.Errorf("rowsFromMbid = %+v", got) - } - got = rowsFromAudioHash([]dbq.FindMissingTrackByAudioHashRow{hashRow(3, "/c")}) - if len(got) != 1 || got[0].id != testUUID(3) || got[0].filePath != "/c" { - t.Errorf("rowsFromAudioHash = %+v", got) - } -} - -// pgtype.UUID zero value must not be mistaken for a real id. -func TestUniqueMatch_ZeroUUIDNotValid(t *testing.T) { - var zero pgtype.UUID - if zero.Valid { - t.Fatal("zero pgtype.UUID should not be Valid") - } -} diff --git a/internal/library/mp4genre.go b/internal/library/mp4genre.go index 94204997..56f3326b 100644 --- a/internal/library/mp4genre.go +++ b/internal/library/mp4genre.go @@ -74,9 +74,92 @@ func findMP4Child(rs io.ReadSeeker, start, end int64, kind string) (mp4Atom, boo // readMP4GenreValues returns every ©gen value, in file order. rs is seeked // as needed, so it is safe to call after dhowden/tag has consumed the reader. func readMP4GenreValues(rs io.ReadSeeker) ([]string, error) { + ilst, found, err := findMP4Ilst(rs) + if err != nil || !found { + return nil, err + } + var out []string + err = eachMP4Item(rs, ilst, func(kind string, body []byte) bool { + if kind != "\xa9gen" { + return true + } + values, ok := mp4DataValues(body) + out = append(out, values...) + return ok + }) + return out, err +} + +// readMP4FreeformValues returns the values of the freeform "----" item called +// name (com.apple.iTunes:ARTISTS is Picard's), in file order. Names compare +// case-insensitively, as taggers differ in case. +func readMP4FreeformValues(rs io.ReadSeeker, name string) ([]string, error) { + ilst, found, err := findMP4Ilst(rs) + if err != nil || !found { + return nil, err + } + var out []string + err = eachMP4Item(rs, ilst, func(kind string, body []byte) bool { + if kind != "----" || !strings.EqualFold(mp4FreeformName(body), name) { + return true + } + values, ok := mp4DataValues(body) + out = append(out, values...) + return ok + }) + return out, err +} + +// mp4FreeformName is the text of the "name" atom in a freeform item's body: +// size, "name", four bytes of version and flags, then the name. +func mp4FreeformName(b []byte) string { + for len(b) >= 8 { + size := binary.BigEndian.Uint32(b[0:4]) + if size < 8 || uint64(size) > uint64(len(b)) { + return "" + } + if string(b[4:8]) == "name" && size >= 12 { + return string(b[12:size]) + } + b = b[size:] + } + return "" +} + +// eachMP4Item calls fn with the kind and body of each item in ilst, in file +// order, until fn returns false (a malformed body). Each body is capped at +// maxMP4GenreAtomSize. +func eachMP4Item(rs io.ReadSeeker, ilst mp4Atom, fn func(kind string, body []byte) bool) error { + for pos := ilst.body; pos+8 <= ilst.limit; { + a, err := readMP4Atom(rs, pos, ilst.limit) + if err != nil { + return errNoGenreFrame + } + pos = a.limit + n := a.limit - a.body + if n > maxMP4GenreAtomSize { + return errNoGenreFrame + } + if _, err := rs.Seek(a.body, io.SeekStart); err != nil { + return errNoGenreFrame + } + body := make([]byte, n) + if _, err := io.ReadFull(rs, body); err != nil { + return errNoGenreFrame + } + if !fn(a.kind, body) { + return errNoGenreFrame + } + } + return nil +} + +// findMP4Ilst finds the iTunes item list, moov > udta > meta > ilst. +// found is false for a file with no iTunes metadata. +func findMP4Ilst(rs io.ReadSeeker) (ilst mp4Atom, found bool, err error) { end, err := rs.Seek(0, io.SeekEnd) if err != nil { - return nil, err + return mp4Atom{}, false, err } // moov may sit after mdat; walking headers and seeking past bodies finds // it either way without reading the audio. @@ -84,10 +167,10 @@ func readMP4GenreValues(rs io.ReadSeeker) ([]string, error) { for _, kind := range []string{"moov", "udta", "meta"} { next, found, err := findMP4Child(rs, cur.body, cur.limit, kind) if err != nil { - return nil, errNoGenreFrame + return mp4Atom{}, false, errNoGenreFrame } if !found { - return nil, nil // no iTunes metadata at all + return mp4Atom{}, false, nil // no iTunes metadata at all } cur = next } @@ -95,54 +178,24 @@ func readMP4GenreValues(rs io.ReadSeeker) ([]string, error) { // children in the ISO layout. QuickTime-style files omit them, so the // first child (hdlr) starts straight away. Look before skipping. if _, err := rs.Seek(cur.body, io.SeekStart); err != nil { - return nil, errNoGenreFrame + return mp4Atom{}, false, errNoGenreFrame } var peek [8]byte if _, err := io.ReadFull(rs, peek[:]); err != nil { - return nil, errNoGenreFrame + return mp4Atom{}, false, errNoGenreFrame } if string(peek[4:8]) != "hdlr" { cur.body += 4 } - ilst, found, err := findMP4Child(rs, cur.body, cur.limit, "ilst") + ilst, found, err = findMP4Child(rs, cur.body, cur.limit, "ilst") if err != nil { - return nil, errNoGenreFrame + return mp4Atom{}, false, errNoGenreFrame } - if !found { - return nil, nil - } - - var out []string - for pos := ilst.body; pos+8 <= ilst.limit; { - a, err := readMP4Atom(rs, pos, ilst.limit) - if err != nil { - return nil, errNoGenreFrame - } - pos = a.limit - if a.kind != "\xa9gen" { - continue - } - n := a.limit - a.body - if n > maxMP4GenreAtomSize { - return nil, errNoGenreFrame - } - if _, err := rs.Seek(a.body, io.SeekStart); err != nil { - return nil, errNoGenreFrame - } - body := make([]byte, n) - if _, err := io.ReadFull(rs, body); err != nil { - return nil, errNoGenreFrame - } - values, ok := mp4DataValues(body) - if !ok { - return nil, errNoGenreFrame - } - out = append(out, values...) - } - return out, nil + return ilst, found, nil } -// mp4DataValues reads the "data" atoms in a ©gen body. Each is: size, "data", +// mp4DataValues reads the "data" atoms in a ©gen or freeform item's body; +// a freeform item's "mean" and "name" atoms are skipped. Each is: size, "data", // a 4-byte type indicator (1 = UTF-8 text), a 4-byte locale, then the value. // Atoms of other types carry no text and are skipped. func mp4DataValues(b []byte) ([]string, bool) { diff --git a/internal/library/new_music_test.go b/internal/library/new_music_test.go new file mode 100644 index 00000000..0a330d2e --- /dev/null +++ b/internal/library/new_music_test.go @@ -0,0 +1,96 @@ +package library + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "path/filepath" + "testing" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/notifications" +) + +// newMusicNotices returns user's unread new_music notices' payloads. +func newMusicNotices(t *testing.T, q *dbq.Queries, user dbq.User) []notifications.Payload { + t.Helper() + rows, err := q.ListNotifications(context.Background(), dbq.ListNotificationsParams{UserID: user.ID, PageLimit: 50}) + if err != nil { + t.Fatalf("list notifications: %v", err) + } + var out []notifications.Payload + for _, r := range rows { + if r.ReadAt.Valid || r.Kind != string(notifications.KindNewMusic) { + continue + } + var p notifications.Payload + if err := json.Unmarshal(r.Payload, &p); err != nil { + t.Fatalf("payload: %v", err) + } + out = append(out, p) + } + return out +} + +// Every user hears about an album new to the library, once. The first import +// into an empty library is the library being set up, and an album that only +// formed because tracks already held were retagged into it is not new music. +func TestAnnounceNewAlbums_TellsEveryoneOfEachNewAlbumOnce(t *testing.T) { + pool := dbtest.Pool(t) + admin := notifyingAdmin(t, pool) + ctx := context.Background() + q := dbq.New(pool) + listener, err := q.CreateUser(ctx, dbq.CreateUserParams{ + Username: dbtest.TestUserPrefix + "listener", PasswordHash: "x", ApiTokenHash: "listener", + }) + if err != nil { + t.Fatal(err) + } + s := New(pool, slog.New(slog.NewTextHandler(io.Discard, nil)), nil, nil) + dir := t.TempDir() + + // First import: claimed, not announced. + held, _, artist := seedTrack(t, pool, filepath.Join(dir, "a.mp3")) + s.announceNewAlbums(ctx) + if got := newMusicNotices(t, q, admin); len(got) != 0 { + t.Fatalf("the first import was announced: %+v", got) + } + + // A new album with its own new track. + arrived, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Geomantic", SortTitle: "Geomantic", ArtistID: artist.ID}) + if err != nil { + t.Fatal(err) + } + if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ + Title: "Music Is Maps", AlbumID: arrived.ID, ArtistID: artist.ID, + DurationMs: 1000, FilePath: filepath.Join(dir, "b.mp3"), FileSize: 100, FileFormat: "mp3", + }); err != nil { + t.Fatal(err) + } + // And an album formed by retagging a track the library already held. + retagged, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Retitled", SortTitle: "Retitled", ArtistID: artist.ID}) + if err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE tracks SET album_id = $2 WHERE id = $1`, held.ID, retagged.ID); err != nil { + t.Fatal(err) + } + + s.announceNewAlbums(ctx) + for _, u := range []dbq.User{admin, listener} { + got := newMusicNotices(t, q, u) + if len(got) != 1 || got[0].Count != 1 || len(got[0].Albums) != 1 || + got[0].Albums[0].Title != "Geomantic" || got[0].Albums[0].AlbumID != arrived.ID.String() || + got[0].Albums[0].Artist != "Delete Test Artist" { + t.Fatalf("%s's notices = %+v, want one naming Geomantic alone", u.Username, got) + } + } + + // Nothing new since: nothing more to say. + s.announceNewAlbums(ctx) + if got := newMusicNotices(t, q, listener); len(got) != 1 { + t.Fatalf("an announced album was announced again: %+v", got) + } +} diff --git a/internal/library/normalization_prefs.go b/internal/library/normalization_prefs.go index 2a1b1585..1df13951 100644 --- a/internal/library/normalization_prefs.go +++ b/internal/library/normalization_prefs.go @@ -9,7 +9,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // NormalizationPrefs is one user's loudness-normalization preference. It lives @@ -26,7 +26,7 @@ type NormalizationPrefs struct { Boost string `json:"boost"` } -// The accepted values. Migration 0067's CHECKs hold the same lists. +// The accepted values. user_normalization_prefs's CHECKs hold the same lists. var ( NormalizationModes = []string{"off", "auto", "track", "album"} NormalizationTargets = []int16{-18, -16, -14} @@ -34,7 +34,7 @@ var ( ) // DefaultNormalizationPrefs applies to a user who has never chosen. It must -// equal migration 0067's column defaults; a test holds them together. +// equal user_normalization_prefs's column defaults; a test holds them together. var DefaultNormalizationPrefs = NormalizationPrefs{Mode: "auto", TargetLUFS: -18, Boost: "headroom"} // ErrNormalizationPrefsInvalid is returned for a value outside the lists. diff --git a/internal/library/normalization_prefs_test.go b/internal/library/normalization_prefs_test.go index 6dd54616..1a208091 100644 --- a/internal/library/normalization_prefs_test.go +++ b/internal/library/normalization_prefs_test.go @@ -5,8 +5,8 @@ import ( "errors" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func TestNormalizationPrefs_Validate(t *testing.T) { @@ -30,7 +30,7 @@ func TestNormalizationPrefs_Validate(t *testing.T) { // migration's defaults for any column the insert left out; the two must // agree, or a user would hear a different level after their first save. func TestNormalizationPrefs_DefaultsAndRoundTrip_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) user, err := q.CreateUser(ctx, dbq.CreateUserParams{ diff --git a/internal/library/notify.go b/internal/library/notify.go index cee533dd..423e42de 100644 --- a/internal/library/notify.go +++ b/internal/library/notify.go @@ -6,8 +6,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) // Package-level notifier for library-health notices to admins: a @@ -39,13 +39,50 @@ func notifyAdmins(ctx context.Context, kind notifications.Kind, p notifications. // keeps the newest ten across a coalesced burst. const notifyItems = 10 -// TrackLabel names a track as a notice does: "Artist – Title", or the title -// alone when the artist is unknown. -func TrackLabel(artist, title string) string { - if artist == "" { - return title +// announceNewAlbums claims the albums no scan has announced yet and tells +// every user about the ones that are new music. Called when a scan or a +// watcher batch has finished adding files, so an album is announced whole. +// The first import into an empty library is claimed without a notice. +func (s *Scanner) announceNewAlbums(ctx context.Context) { + if ctx.Err() != nil { + return } - return artist + " – " + title + q := dbq.New(s.pool) + announcedBefore, err := q.AnyAlbumAnnounced(ctx) + if err != nil { + s.logger.Warn("library scan: reading announced albums failed", "err", err) + return + } + rows, err := q.ClaimUnannouncedAlbums(ctx) + if err != nil { + s.logger.Warn("library scan: claiming new albums failed", "err", err) + return + } + if !announcedBefore { + return + } + var p notifications.Payload + for _, r := range rows { + if !r.Arrived { + continue + } + p.Count++ + if len(p.Albums) < notifications.AlbumsKept { + p.Albums = append(p.Albums, notifications.Arrival{ + Artist: r.ArtistName, + Title: r.Title, + ArtistID: r.ArtistID.String(), + AlbumID: r.ID.String(), + }) + } + } + if p.Count == 0 { + return + } + notifierMu.RLock() + n := notifier + notifierMu.RUnlock() + n.NotifyLogged(ctx, notifications.KindNewMusic, notifications.ToEveryone(), p.Map()) } // notifyStillMissing tells admins which of the tracks a scan marked missing @@ -66,7 +103,7 @@ func (s *Scanner) notifyStillMissing(ctx context.Context, marked []pgtype.UUID) } items := make([]string, 0, min(len(rows), notifyItems)) for _, r := range rows[:min(len(rows), notifyItems)] { - items = append(items, TrackLabel(r.ArtistName, r.Title)) + items = append(items, notifications.TrackLabel(r.ArtistName, r.Title)) } notifyAdmins(ctx, notifications.KindTracksMissing, notifications.Payload{Count: int64(len(rows)), Items: items}) } diff --git a/internal/library/notify_test.go b/internal/library/notify_test.go index 1885f878..9c62c60c 100644 --- a/internal/library/notify_test.go +++ b/internal/library/notify_test.go @@ -12,9 +12,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) // notifyingAdmin wires a real notifier for the test and returns an admin whose @@ -62,7 +62,7 @@ func unreadNotices(t *testing.T, pool *pgxpool.Pool, user dbq.User) []notice { } func TestNotifyScanFinished_FailuresCoalesceAndShutdownIsSilent(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) ctx := context.Background() @@ -91,7 +91,7 @@ func TestNotifyScanFinished_FailuresCoalesceAndShutdownIsSilent(t *testing.T) { // it has adopted moves and folded replacements, so a file it marked and then // healed is never reported as lost. func TestReconcileMissing_RecordsTheMarksWithoutNotifying(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) s := testScanner(t, populatedRoot(t)) @@ -117,7 +117,7 @@ func TestReconcileMissing_RecordsTheMarksWithoutNotifying(t *testing.T) { } func TestNotifyStillMissing_NamesOnlyTheTracksStillGone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) ctx := context.Background() q := dbq.New(pool) @@ -158,7 +158,7 @@ func TestNotifyStillMissing_NamesOnlyTheTracksStillGone(t *testing.T) { // it for them. A group the resolver settles or links is never news, and a // group already seen by an earlier pass is not news again. func TestResolveDuplicates_TellsAdminsOnlyOfNewGroupsLeftForThem(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) ctx := context.Background() q := dbq.New(pool) @@ -186,7 +186,7 @@ func TestResolveDuplicates_TellsAdminsOnlyOfNewGroupsLeftForThem(t *testing.T) { t.Fatal(err) } - if _, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil { + if _, err := ResolveDuplicates(ctx, pool, nil, true); err != nil { t.Fatal(err) } got := unreadNotices(t, pool, admin) @@ -198,7 +198,7 @@ func TestResolveDuplicates_TellsAdminsOnlyOfNewGroupsLeftForThem(t *testing.T) { if _, err := q.MarkAllNotificationsRead(ctx, dbq.MarkAllNotificationsReadParams{UserID: admin.ID}); err != nil { t.Fatal(err) } - if _, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil { + if _, err := ResolveDuplicates(ctx, pool, nil, true); err != nil { t.Fatal(err) } if got := unreadNotices(t, pool, admin); len(got) != 0 { diff --git a/internal/library/reconcile.go b/internal/library/reconcile.go index 18e05b9b..1d654677 100644 --- a/internal/library/reconcile.go +++ b/internal/library/reconcile.go @@ -8,8 +8,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // trackReconciler is the slice of dbq.Queries reconcileMissing needs. Narrowed diff --git a/internal/library/reconcile_test.go b/internal/library/reconcile_test.go index 5d043565..c14a0719 100644 --- a/internal/library/reconcile_test.go +++ b/internal/library/reconcile_test.go @@ -2,7 +2,6 @@ package library import ( "context" - "errors" "fmt" "io" "log/slog" @@ -12,7 +11,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // fakeReconciler records what reconcileMissing decided to do, so the guards can @@ -99,13 +98,15 @@ func testScanner(t *testing.T, roots ...string) *Scanner { } } +// A row the walk did not see is marked missing, and the mark reaches clients +// as a change row. Without one the mark is invisible: /api/library/sync is a +// change-log feed, so a plain UPDATE never reaches anyone. func TestReconcileMissing_MarksRowsTheWalkDidNotSee(t *testing.T) { root := populatedRoot(t) s := testScanner(t, root) // 10 rows with 2 absent — 20%, deliberately under missingMarkMaxFraction so - // this exercises marking rather than the cap. (An earlier version of this - // test used 2-of-4 and was really testing the guard by accident.) + // this exercises marking rather than the cap. rows := make([]dbq.ListTrackPathsForReconcileRow, 0, 10) seen := map[string]struct{}{} for i := 0; i < 10; i++ { @@ -121,11 +122,8 @@ func TestReconcileMissing_MarksRowsTheWalkDidNotSee(t *testing.T) { if err := s.reconcileMissing(context.Background(), q, seen, &stats); err != nil { t.Fatalf("reconcile: %v", err) } - if len(q.marked) != 2 { - t.Fatalf("marked %d rows, want 2", len(q.marked)) - } - if q.marked[0] != testUUID(0) || q.marked[1] != testUUID(1) { - t.Errorf("marked the wrong rows: %v", q.marked) + if len(q.marked) != 2 || q.marked[0] != testUUID(0) || q.marked[1] != testUUID(1) { + t.Fatalf("marked %v, want rows 0 and 1", q.marked) } if stats.Missing != 2 { t.Errorf("stats.Missing = %d, want 2", stats.Missing) @@ -133,8 +131,20 @@ func TestReconcileMissing_MarksRowsTheWalkDidNotSee(t *testing.T) { if len(q.cleared) != 0 { t.Errorf("cleared %d rows, want 0", len(q.cleared)) } + if len(q.loggedChanges) != 1 { + t.Fatalf("want one batch of change rows, got %d", len(q.loggedChanges)) + } + got := q.loggedChanges[0] + // Upsert, not delete: the track still exists and keeps its history. A + // delete would tell clients to drop the row, and a missing file is + // expected to come back. + if got.EntityType != "track" || got.Op != "upsert" || len(got.EntityIds) != 2 { + t.Errorf("change rows = (%s, %s, %d ids), want an upsert of both tracks", got.EntityType, got.Op, len(got.EntityIds)) + } } +// A file coming back clears its mark and reaches clients too, or a restored +// track stays greyed out on every device until something unrelated touches it. func TestReconcileMissing_ClearsRowsWhoseFileReturned(t *testing.T) { root := populatedRoot(t) s := testScanner(t, root) @@ -160,6 +170,9 @@ func TestReconcileMissing_ClearsRowsWhoseFileReturned(t *testing.T) { if len(q.marked) != 0 { t.Errorf("marked %d rows, want 0", len(q.marked)) } + if len(q.loggedChanges) != 1 || q.loggedChanges[0].Op != "upsert" { + t.Errorf("change rows = %+v, want one upsert batch for the restored track", q.loggedChanges) + } } // An already-marked row must not be re-marked: the timestamp is the "how long @@ -242,67 +255,50 @@ func TestReconcileMissing_ClearsEvenWhenMarkCapTrips(t *testing.T) { } } -func TestReconcileMissing_RefusesOnEmptyWalk(t *testing.T) { - root := populatedRoot(t) - s := testScanner(t, root) - q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{ - row(1, "/music/a.mp3", false), - }} - - var stats Stats - if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{}, &stats); err == nil { - t.Fatal("expected refusal when the walk saw no files") +// A walk that cannot be trusted changes nothing, neither marking nor clearing: +// one that saw no files, a root that is not mounted (absent), a mount point +// with nothing on it (present but empty, which os.Stat alone would pass), one +// detached root among several, or no roots configured at all. The walk below +// would otherwise mark one track of ten, under missingMarkMaxFraction, and +// clear a returned one, so only these checks can refuse it. +func TestReconcileMissing_RefusesWhenAVolumeLooksAbsent(t *testing.T) { + rows := []dbq.ListTrackPathsForReconcileRow{row(99, "/music/back.mp3", true)} + walked := map[string]struct{}{"/music/back.mp3": {}} + for i := 0; i < 10; i++ { + p := fmt.Sprintf("/music/track-%02d.mp3", i) + rows = append(rows, row(byte(i), p, false)) + if i > 0 { + walked[p] = struct{}{} + } } - if len(q.marked) != 0 { - t.Errorf("marked rows on an empty walk: %v", q.marked) - } -} - -// The unmounted-volume case: the configured root doesn't exist at all. -func TestReconcileMissing_RefusesWhenRootMissing(t *testing.T) { - s := testScanner(t, filepath.Join(t.TempDir(), "not-mounted")) - q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{ - row(1, "/music/a.mp3", false), - }} - - var stats Stats - if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats); err == nil { - t.Fatal("expected refusal when a scan root is absent") - } - if len(q.marked) != 0 { - t.Errorf("marked rows with an absent root: %v", q.marked) - } -} - -// A mount point that exists but has nothing mounted on it: os.Stat succeeds on -// the bare directory, which is why emptiness is checked separately. -func TestReconcileMissing_RefusesWhenRootEmpty(t *testing.T) { - s := testScanner(t, t.TempDir()) - q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{ - row(1, "/music/a.mp3", false), - }} - - var stats Stats - if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats); err == nil { - t.Fatal("expected refusal when a scan root is empty") - } -} - -// Several roots, one detached. Marking must not proceed on partial evidence -// just because the other roots looked fine. -func TestReconcileMissing_RefusesWhenAnyRootMissing(t *testing.T) { - good := populatedRoot(t) - s := testScanner(t, good, filepath.Join(t.TempDir(), "detached")) - q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{ - row(1, "/music/a.mp3", false), - }} - - var stats Stats - if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats); err == nil { - t.Fatal("expected refusal when one of several roots is absent") + for _, tc := range []struct { + name string + roots func(t *testing.T) []string + seen map[string]struct{} + }{ + {"the walk saw no files", func(t *testing.T) []string { return []string{populatedRoot(t)} }, map[string]struct{}{}}, + {"a root is absent", func(t *testing.T) []string { return []string{filepath.Join(t.TempDir(), "not-mounted")} }, walked}, + {"a root is empty", func(t *testing.T) []string { return []string{t.TempDir()} }, walked}, + {"one of several roots is absent", func(t *testing.T) []string { + return []string{populatedRoot(t), filepath.Join(t.TempDir(), "detached")} + }, walked}, + {"no roots configured", func(*testing.T) []string { return nil }, walked}, + } { + t.Run(tc.name, func(t *testing.T) { + s := testScanner(t, tc.roots(t)...) + q := &fakeReconciler{rows: rows} + var stats Stats + if err := s.reconcileMissing(context.Background(), q, tc.seen, &stats); err == nil { + t.Fatal("reconcile went ahead; want a refusal") + } + if len(q.marked) != 0 || len(q.cleared) != 0 { + t.Errorf("marked %v, cleared %v; want nothing changed", q.marked, q.cleared) + } + }) } } +// A fresh install has no tracks yet; its first scan must not fail. func TestReconcileMissing_NoRowsIsNotAnError(t *testing.T) { root := populatedRoot(t) s := testScanner(t, root) @@ -313,88 +309,3 @@ func TestReconcileMissing_NoRowsIsNotAnError(t *testing.T) { t.Fatalf("empty library should reconcile cleanly, got %v", err) } } - -func TestReconcileMissing_PropagatesListError(t *testing.T) { - root := populatedRoot(t) - s := testScanner(t, root) - sentinel := errors.New("boom") - q := &fakeReconciler{listErr: sentinel} - - var stats Stats - err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats) - if !errors.Is(err, sentinel) { - t.Fatalf("err = %v, want it to wrap %v", err, sentinel) - } -} - -func TestVerifyRootsPresent_NoRootsConfigured(t *testing.T) { - s := testScanner(t) - if err := s.verifyRootsPresent(); err == nil { - t.Fatal("expected an error with no scan roots configured") - } -} - -// Without a change row the mark is invisible to every client: -// /api/library/sync is a change-log feed, so a plain UPDATE never reaches -// anyone, and the wire field would exist with nothing ever telling a client to -// re-read the track. -func TestReconcileMissing_MarkingEmitsSyncChanges(t *testing.T) { - s := testScanner(t, populatedRoot(t)) - - // 10 rows, 2 absent — under the cap, so this exercises marking. - rows := make([]dbq.ListTrackPathsForReconcileRow, 0, 10) - seen := map[string]struct{}{} - for i := 0; i < 10; i++ { - path := fmt.Sprintf("/music/track-%02d.mp3", i) - rows = append(rows, row(byte(i), path, false)) - if i >= 2 { - seen[path] = struct{}{} - } - } - q := &fakeReconciler{rows: rows} - var stats Stats - - if err := s.reconcileMissing(context.Background(), q, seen, &stats); err != nil { - t.Fatalf("reconcile: %v", err) - } - - if len(q.loggedChanges) != 1 { - t.Fatalf("want one batch of change rows, got %d", len(q.loggedChanges)) - } - got := q.loggedChanges[0] - if got.EntityType != "track" { - t.Errorf("entity_type = %q, want track", got.EntityType) - } - // Upsert, not delete: the track still exists and keeps its history. A - // delete would tell clients to drop the row, and a missing file is - // expected to come back. - if got.Op != "upsert" { - t.Errorf("op = %q, want upsert — the row survives, only its state changed", got.Op) - } - if len(got.EntityIds) != 2 { - t.Errorf("want both missing tracks logged, got %d ids", len(got.EntityIds)) - } -} - -// A file coming back must reach clients too, or a restored track stays -// greyed out on every device until something unrelated touches it. -func TestReconcileMissing_RestoringEmitsSyncChanges(t *testing.T) { - s := testScanner(t, populatedRoot(t)) - q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{ - row(1, "/music/back.mp3", true), - }} - var stats Stats - - if err := s.reconcileMissing( - context.Background(), q, map[string]struct{}{"/music/back.mp3": {}}, &stats, - ); err != nil { - t.Fatalf("reconcile: %v", err) - } - - if len(q.loggedChanges) != 1 { - t.Fatalf("a restored file must produce a change row, got %d batches", len(q.loggedChanges)) - } - if q.loggedChanges[0].Op != "upsert" { - t.Errorf("op = %q, want upsert", q.loggedChanges[0].Op) - } -} diff --git a/internal/library/remove.go b/internal/library/remove.go new file mode 100644 index 00000000..8195f5b1 --- /dev/null +++ b/internal/library/remove.go @@ -0,0 +1,104 @@ +package library + +import ( + "context" + "errors" + "fmt" + "log/slog" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" +) + +// RemovedFor is the Collection queue a track's file was removed from. Every +// queue ends the same way: the bad file goes and the track waits, missing, +// for a good copy (tracks.removed_reason). +type RemovedFor string + +const ( + RemovedForReport RemovedFor = "report" + RemovedForDuplicate RemovedFor = "duplicate" + RemovedForSuspect RemovedFor = "suspect" +) + +// RemoveFileParams is one track whose file an admin is removing. +type RemoveFileParams struct { + TrackID pgtype.UUID + // ActorID is the admin removing it. + ActorID pgtype.UUID + Reason RemovedFor + // ForgetMBID drops the track's recording MBID. Set it when the file was + // not the track's song, or its tags are not to be trusted: the MBID came + // from that file, and a good copy carrying the real song's MBID must not + // be kept from folding in by it, nor the slot folded into another song. + ForgetMBID bool + // Within runs on the same transaction as the marking, for what the + // caller's queue records about the removal (a report's history row). An + // error from it undoes the marking, though not the removed file. + Within func(ctx context.Context, tq *dbq.Queries) error +} + +// RemoveFile removes a track's file from disk and keeps the track: it is +// marked missing, with its likes, plays and playlist places, and the queue it +// was removed from. A good copy that lands in the library later is adopted +// into it (moved.go) or folded into it (missing_pairs.go), so the track comes +// back with its history. +// +// The file goes first. If it cannot, nothing is marked and a +// *FileRemoveError comes back. A file that is already gone is not a failure. +func RemoveFile(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, p RemoveFileParams) (dbq.Track, error) { + if logger == nil { + logger = slog.Default() + } + q := dbq.New(pool) + track, err := q.GetTrackByID(ctx, p.TrackID) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return dbq.Track{}, ErrTrackNotFound + } + return dbq.Track{}, fmt.Errorf("get track: %w", err) + } + if err := removeTrackFileOnDisk(track.FilePath); err != nil { + return dbq.Track{}, err + } + err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { + tq := dbq.New(tx) + ids := []pgtype.UUID{p.TrackID} + if err := markRemoved(ctx, tq, ids, p.Reason, p.ActorID); err != nil { + return err + } + if p.ForgetMBID { + if err := tq.ClearTrackMbids(ctx, ids); err != nil { + return fmt.Errorf("clear mbid: %w", err) + } + } + if p.Within != nil { + return p.Within(ctx, tq) + } + return nil + }) + if err != nil { + return dbq.Track{}, err + } + logger.Info("library: removed a file and kept its track", + "track_id", track.ID.String(), "file_path", track.FilePath, "reason", string(p.Reason)) + return track, nil +} + +// markRemoved marks tracks whose files were removed on purpose, and tells +// clients they are no longer playable. actorID is invalid when the +// duplicate resolver removed them on its own. +func markRemoved(ctx context.Context, tq *dbq.Queries, ids []pgtype.UUID, reason RemovedFor, actorID pgtype.UUID) error { + if _, err := tq.MarkTracksRemoved(ctx, dbq.MarkTracksRemovedParams{ + Reason: string(reason), RemovedBy: actorID, Ids: ids, + }); err != nil { + return fmt.Errorf("mark removed: %w", err) + } + if err := logTrackChanges(ctx, tq, ids); err != nil { + return fmt.Errorf("log changes: %w", err) + } + return nil +} diff --git a/internal/library/remove_test.go b/internal/library/remove_test.go new file mode 100644 index 00000000..42b62753 --- /dev/null +++ b/internal/library/remove_test.go @@ -0,0 +1,164 @@ +package library + +import ( + "context" + "errors" + "io" + "log/slog" + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/jackc/pgx/v5/pgtype" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" +) + +// A removed file's track stays, missing, with its likes and plays and the +// reason it waits, and the good copy that lands later takes its history over. +func TestRemoveFile_KeepsTheTrackUntilAGoodCopyLands(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + q := dbq.New(pool) + admin, err := q.CreateUser(ctx, dbq.CreateUserParams{ + Username: dbtest.TestUserPrefix + "remover", PasswordHash: "x", ApiTokenHash: "remover", IsAdmin: true, + }) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + bad := filepath.Join(dir, "01 bad.mp3") + if err := os.WriteFile(bad, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + track, album, artist := seedTrack(t, pool, bad) + mbid := "rec-kept" + if _, err := pool.Exec(ctx, `UPDATE tracks SET mbid = $2, mbid_source = 'tag' WHERE id = $1`, track.ID, mbid); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, admin.ID, track.ID); err != nil { + t.Fatal(err) + } + + if _, err := RemoveFile(ctx, pool, slog.New(slog.NewTextHandler(io.Discard, nil)), RemoveFileParams{ + TrackID: track.ID, ActorID: admin.ID, Reason: RemovedForReport, + }); err != nil { + t.Fatalf("RemoveFile: %v", err) + } + if _, err := os.Stat(bad); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the file is still there: %v", err) + } + waiting, err := q.GetTrackByID(ctx, track.ID) + if err != nil { + t.Fatalf("the track went with its file: %v", err) + } + if !waiting.MissingSince.Valid || waiting.RemovedReason == nil || *waiting.RemovedReason != "report" || + waiting.RemovedBy != admin.ID { + t.Fatalf("waiting track = missing %v, reason %v, by %v; want missing, report, the admin", + waiting.MissingSince.Valid, waiting.RemovedReason, waiting.RemovedBy) + } + if waiting.Mbid == nil || *waiting.Mbid != mbid { + t.Fatalf("mbid = %v, want %q kept for a report that does not doubt it", waiting.Mbid, mbid) + } + + // A good copy lands on the album under the song's title. + good, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ + Title: track.Title, AlbumID: album.ID, ArtistID: artist.ID, + DurationMs: 1000, FilePath: filepath.Join(dir, "01 good.flac"), FileSize: 100, FileFormat: "flac", + }) + if err != nil { + t.Fatal(err) + } + if _, err := PairMissingTracks(ctx, pool, nil); err != nil { + t.Fatalf("PairMissingTracks: %v", err) + } + var likes int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM general_likes WHERE track_id = $1`, good.ID).Scan(&likes); err != nil { + t.Fatal(err) + } + if likes != 1 { + t.Fatalf("the good copy has %d likes, want the removed track's one", likes) + } +} + +// ForgetMBID drops the recording MBID that came from a file that was not the +// track's song. +func TestRemoveFile_ForgetsADoubtedMBID(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + path := filepath.Join(t.TempDir(), "rip.mp3") + if err := os.WriteFile(path, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + track, _, _ := seedTrack(t, pool, path) + if _, err := pool.Exec(ctx, `UPDATE tracks SET mbid = 'rec-wrong', mbid_source = 'tag' WHERE id = $1`, track.ID); err != nil { + t.Fatal(err) + } + if _, err := RemoveFile(ctx, pool, nil, RemoveFileParams{ + TrackID: track.ID, Reason: RemovedForSuspect, ForgetMBID: true, + }); err != nil { + t.Fatalf("RemoveFile: %v", err) + } + got, err := dbq.New(pool).GetTrackByID(ctx, track.ID) + if err != nil { + t.Fatal(err) + } + if got.Mbid != nil { + t.Fatalf("mbid = %q, want it forgotten", *got.Mbid) + } +} + +// A file that cannot be removed leaves the track as it was. +func TestRemoveFile_FailedRemovalMarksNothing(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + path := filepath.Join(t.TempDir(), "stuck.mp3") + if err := os.WriteFile(path, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + track, _, _ := seedTrack(t, pool, path) + stubRemoveFile(t, func(p string) error { + return &os.PathError{Op: "remove", Path: p, Err: syscall.EROFS} + }) + _, err := RemoveFile(ctx, pool, nil, RemoveFileParams{TrackID: track.ID, Reason: RemovedForReport}) + var fre *FileRemoveError + if !errors.As(err, &fre) { + t.Fatalf("err = %v, want a FileRemoveError", err) + } + got, err := dbq.New(pool).GetTrackByID(ctx, track.ID) + if err != nil { + t.Fatal(err) + } + if got.MissingSince.Valid || got.RemovedReason != nil { + t.Fatalf("a track whose file stayed was marked: missing %v, reason %v", got.MissingSince.Valid, got.RemovedReason) + } +} + +// The reason describes one missing spell: a file back at its path clears it +// with the missing mark. +func TestRemoveFile_ReasonGoesWhenTheFileIsBack(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + path := filepath.Join(t.TempDir(), "back.mp3") + if err := os.WriteFile(path, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + track, _, _ := seedTrack(t, pool, path) + if _, err := RemoveFile(ctx, pool, nil, RemoveFileParams{TrackID: track.ID, Reason: RemovedForReport}); err != nil { + t.Fatalf("RemoveFile: %v", err) + } + q := dbq.New(pool) + if _, err := q.ClearTracksMissing(ctx, []pgtype.UUID{track.ID}); err != nil { + t.Fatalf("ClearTracksMissing: %v", err) + } + got, err := q.GetTrackByID(ctx, track.ID) + if err != nil { + t.Fatal(err) + } + if got.MissingSince.Valid || got.RemovedReason != nil || got.RemovedBy.Valid { + t.Fatalf("back track = missing %v, reason %v, by %v; want all cleared", + got.MissingSince.Valid, got.RemovedReason, got.RemovedBy.Valid) + } +} diff --git a/internal/library/replace.go b/internal/library/replace.go index 344b03d6..26e98ed3 100644 --- a/internal/library/replace.go +++ b/internal/library/replace.go @@ -10,9 +10,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" ) // Replacing a track with a better copy. diff --git a/internal/library/replaygain.go b/internal/library/replaygain.go index 04e7af35..d7386f17 100644 --- a/internal/library/replaygain.go +++ b/internal/library/replaygain.go @@ -6,7 +6,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // ReplayGain delivery. diff --git a/internal/library/replaygain_test.go b/internal/library/replaygain_test.go index ae18d735..54ef7a3a 100644 --- a/internal/library/replaygain_test.go +++ b/internal/library/replaygain_test.go @@ -8,7 +8,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func TestGainDBAndLinearPeak(t *testing.T) { @@ -45,7 +46,7 @@ func TestGainDBAndLinearPeak(t *testing.T) { } func TestReplayGainForTracks_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/scanner.go b/internal/library/scanner.go index f2cff895..feb6887c 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -15,13 +15,14 @@ import ( "sync" "time" - "github.com/dhowden/tag" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/db" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" + "github.com/Fabled-Sword/minstrel/internal/tagread" ) // audioExtensions is the set the scanner indexes. Keep in sync with @@ -42,7 +43,7 @@ var audioExtensions = map[string]bool{ // tagReadVersion is the version of this package's tag-extraction logic. Rows // whose tracks.tag_read_version is lower get their tags re-read on the next // scan even when the file itself hasn't changed, so a fix reaches an existing -// library without anyone rebuilding it (migration 0054). +// library without anyone rebuilding it. // // Bump this whenever a change to tag extraction should reach already-indexed // files, and say why below. @@ -57,9 +58,9 @@ var audioExtensions = map[string]bool{ // to new files only because taste_profile.sql reads tracks.genre directly, // so a half-repaired library would carry both spellings as separate tags. // 3: the MusicBrainz release-group id is read into albums.release_group_mbid. -// Wants name albums by release group, not by the release id -// albums.mbid holds, so re-acquisition and request completion need it for -// the albums already in the library, not only for files added from now on. +// The duplicate resolver reads an album's track lists by release group, +// not by the release id albums.mbid holds, so it needs it for the albums +// already in the library, not only for files added from now on. // 4: every value of a repeated genre field is read for FLAC, Ogg Vorbis, Opus // and MP4. dhowden/tag kept only the last, and most FLACs that carry // genres declare more than one. @@ -78,7 +79,18 @@ var audioExtensions = map[string]bool{ // 8: a file tagged with no release group joins the same-named album that // already holds a track from its folder. Under 7 it took the oldest row, // which could file a bonus track on a later album of the same name. -const tagReadVersion int16 = 8 +// 9: an album is filed under its album artist (ALBUMARTIST / TPE2 / aART, +// with its MusicBrainz id) when the file names one, not under the +// track's artist. A compilation, or an album with one featured-artist +// track, was split into an album per track artist; a re-read files each +// track back on the one album, and the scan's tidy-up removes the rows +// it leaves empty. +// 10: a credit that names a guest ("X feat. Y") or lists several artists +// (Picard's ARTISTS) is filed under its first artist and kept as the +// track's credit, rather than becoming an artist of its own; the scan's +// tidy-up removes the credit-named artists it leaves empty. A Vorbis +// file's artist id is its first, not its last. +const tagReadVersion int16 = 10 type Stats struct { Scanned int `json:"scanned"` @@ -134,6 +146,10 @@ func New(pool *pgxpool.Pool, logger *slog.Logger, paths []string, settings *Fing // processed file. Used by the orchestrator to drive partial-tally writes. func (s *Scanner) Scan(ctx context.Context, progressCb func(Stats)) (Stats, error) { var stats Stats + if err := filesGate.acquire(ctx, filesWaitLimit); err != nil { + return stats, fmt.Errorf("library scan: %w", err) + } + defer filesGate.release() q := dbq.New(s.pool) start := time.Now() @@ -213,9 +229,46 @@ func (s *Scanner) Scan(ctx context.Context, progressCb func(Stats)) (Stats, erro // Told only now, so a file that moved or was upgraded, which this scan // marked and then healed, is not reported as lost. s.notifyStillMissing(ctx, stats.marked) + s.announceNewAlbums(ctx) + s.tidyEmptyRows(ctx) return stats, nil } +// tidyEmptyRows removes the album rows no track points to any more, and the +// artists left with neither albums nor tracks. Re-filing a track (a re-read +// under a new tag-read version, a moved file, a merged duplicate) can leave +// its old album empty, and an empty album would otherwise still show in +// album lists. An album whose tracks are only missing keeps its row: those +// tracks wait in Needs a file. Not fatal; the next scan tries again. +func (s *Scanner) tidyEmptyRows(ctx context.Context) { + q := dbq.New(s.pool) + albums, err := q.DeleteEmptyAlbums(ctx) + if err != nil { + s.logger.Warn("library scan: removing empty albums failed", "err", err) + return + } + artists, err := q.DeleteEmptyArtists(ctx) + if err != nil { + s.logger.Warn("library scan: removing empty artists failed", "err", err) + } + if len(albums) == 0 && len(artists) == 0 { + return + } + s.logger.Info("library scan: removed empty rows", "albums", len(albums), "artists", len(artists)) + for _, c := range []struct { + entity syncpkg.EntityType + ids []pgtype.UUID + }{{syncpkg.EntityAlbum, albums}, {syncpkg.EntityArtist, artists}} { + ids := make([]string, len(c.ids)) + for i, id := range c.ids { + ids[i] = syncpkg.FormatUUID(id) + } + if err := syncpkg.LogChanges(ctx, s.pool, c.entity, ids, syncpkg.OpDelete); err != nil { + s.logger.Warn("library scan: logging removed rows failed", "entity", c.entity, "err", err) + } + } +} + // enumerate walks every configured root and returns the audio paths found, in // walk order, plus a count of walk errors. // @@ -243,6 +296,12 @@ func (s *Scanner) enumerate( } return nil } + if path != root && hiddenName(d.Name()) { + if d.IsDir() { + return fs.SkipDir + } + return nil + } if d.IsDir() { return nil } @@ -256,6 +315,22 @@ func (s *Scanner) enumerate( return paths, errs } +// clearReturned takes the missing mark (and any removal reason) off a track +// whose file is back at its path, and tells clients it plays again. Counted +// as Restored, like the reconcile pass's clears. +func (s *Scanner) clearReturned(ctx context.Context, q *dbq.Queries, id pgtype.UUID, stats *Stats) error { + ids := []pgtype.UUID{id} + if err := logTrackChanges(ctx, q, ids); err != nil { + return fmt.Errorf("log returned change: %w", err) + } + n, err := q.ClearTracksMissing(ctx, ids) + if err != nil { + return fmt.Errorf("clear missing mark: %w", err) + } + stats.Restored += int(n) + return nil +} + // scanFile upserts a single audio file. Returns the album ID the track // belongs to and whether the file was added/updated (false = skipped as // unchanged), so watcher-driven callers can enrich just the changed albums. @@ -275,6 +350,16 @@ func (s *Scanner) scanFile( if err != nil && !errors.Is(err, pgx.ErrNoRows) { return pgtype.UUID{}, false, fmt.Errorf("lookup: %w", err) } + // A file at the path of a track waiting for one is that track's file + // back. The full scan's reconcile clears these too, but the watcher scans + // single files and never reconciles, and a file restored with its old + // mtime takes the skip below, so without this the track would wait for the + // next full scan. + if knownTrack && existing.MissingSince.Valid { + if err := s.clearReturned(ctx, q, existing.ID, stats); err != nil { + return pgtype.UUID{}, false, err + } + } // Incremental skip: only when the file hasn't changed AND we already have a // real duration AND the row's tag-derived columns were written by the // current extraction logic. The duration clause backfills rows that @@ -293,18 +378,19 @@ func (s *Scanner) scanFile( } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { return pgtype.UUID{}, false, fmt.Errorf("tag read: %w", err) } ids := ReadTagMBIDs(meta) - albumMBID, artistMBID := ids.Release, ids.Artist + albumMBID := ids.Release recordingMBID, releaseGroupMBID := ids.Recording, ids.ReleaseGroup - artistName := meta.Artist() - if artistName == "" { - artistName = "Unknown Artist" - } + // A guest or a second artist in the credit does not get an artist of + // their own: the track is filed under the first, and the full credit is + // kept to show with it (artistcredit.go). + credit := readArtistCredit(meta, f, ids) + artistName := credit.Name albumTitle := meta.Album() if albumTitle == "" { albumTitle = "Unknown Album" @@ -314,11 +400,22 @@ func (s *Scanner) scanFile( trackTitle = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) } - artist, err := s.resolveArtist(ctx, q, artistName, artistMBID) + artist, err := s.resolveArtist(ctx, q, artistName, credit.MBID) if err != nil { return pgtype.UUID{}, false, fmt.Errorf("artist: %w", err) } - album, err := s.resolveAlbum(ctx, q, artist.ID, albumTitle, meta.Year(), albumMBID, releaseGroupMBID, filepath.Dir(path)) + // The album belongs to its album artist when the file names one: every + // track of a compilation, or of an album with a featured guest, then + // lands on one album instead of one per track artist. The track keeps + // its own artist. + albumArtist := artist + if name := withoutGuests(strings.TrimSpace(meta.AlbumArtist())); name != "" && name != artistName { + albumArtist, err = s.resolveArtist(ctx, q, name, ids.AlbumArtist) + if err != nil { + return pgtype.UUID{}, false, fmt.Errorf("album artist: %w", err) + } + } + album, err := s.resolveAlbum(ctx, q, albumArtist.ID, albumTitle, meta.Year(), albumMBID, releaseGroupMBID, filepath.Dir(path)) if err != nil { return pgtype.UUID{}, false, fmt.Errorf("album: %w", err) } @@ -399,6 +496,10 @@ func (s *Scanner) scanFile( // Stamped so a future extraction fix can find this row again. TagReadVersion: tagReadVersion, } + if credit.Credit != "" { + c := credit.Credit + params.ArtistCredit = &c + } if trackNum > 0 { v := int32(trackNum) params.TrackNumber = &v @@ -473,15 +574,20 @@ func (s *Scanner) scanFile( // album IDs whose tracks were added or updated, so the caller can enrich // just those albums inline rather than waiting for a batch pass. func (s *Scanner) ScanFiles(ctx context.Context, paths []string) ([]pgtype.UUID, error) { + if err := filesGate.acquire(ctx, filesWaitLimit); err != nil { + return nil, fmt.Errorf("library watch: %w", err) + } + defer filesGate.release() q := dbq.New(s.pool) seen := make(map[[16]byte]struct{}) changed := make([]pgtype.UUID, 0) var stats Stats + roots := s.Roots() for _, path := range paths { if ctx.Err() != nil { return changed, ctx.Err() } - if !audioExtensions[strings.ToLower(filepath.Ext(path))] { + if !audioExtensions[strings.ToLower(filepath.Ext(path))] || hiddenInLibrary(roots, path) { continue } albumID, didChange, err := s.scanFile(ctx, q, path, &stats) @@ -496,10 +602,11 @@ func (s *Scanner) ScanFiles(ctx context.Context, paths []string) ([]pgtype.UUID, } } } - if stats.Added > 0 || stats.Updated > 0 { + if stats.Added > 0 || stats.Updated > 0 || stats.Restored > 0 { s.logger.Info("library watch: scan batch", "added", stats.Added, "updated", stats.Updated, + "restored", stats.Restored, "skipped", stats.Skipped, "errored", stats.Errored, ) @@ -509,6 +616,9 @@ func (s *Scanner) ScanFiles(ctx context.Context, paths []string) ([]pgtype.UUID, s.logger.Warn("library watch: missing-pair pass failed", "err", err) } } + if stats.Added > 0 { + s.announceNewAlbums(ctx) + } return changed, nil } @@ -522,7 +632,7 @@ func (s *Scanner) resolveArtist(ctx context.Context, q *dbq.Queries, name, mbid ID: existing.ID, Mbid: &m, }); uerr != nil { - if isUniqueViolation(uerr) { + if db.IsUniqueViolation(uerr) { // Another artist row already owns this MBID — two rows that // should be merged (usually two spellings of one name). // Expected, not a fault: leave NULL and let an admin @@ -593,7 +703,7 @@ func (s *Scanner) resolveAlbum(ctx context.Context, q *dbq.Queries, artistID pgt ID: existing.ID, Mbid: &m, }); uerr != nil { - if isUniqueViolation(uerr) { + if db.IsUniqueViolation(uerr) { // Another album row already owns this MBID — duplicate // release in the DB. Leave NULL; operator merges later. s.logger.Info("library scan: duplicate album mbid (canonical row already owns it)", @@ -704,16 +814,6 @@ func probeDurationMs(ctx context.Context, path string) (int32, error) { return int32(ms), nil } -// ProbeDurationMs is a file's length in milliseconds, read by ffprobe. -func ProbeDurationMs(ctx context.Context, path string) (int32, error) { - return probeDurationMs(ctx, path) -} - -// IsAudioFile reports whether the scanner reads a file with this name. -func IsAudioFile(path string) bool { - return audioExtensions[strings.ToLower(filepath.Ext(path))] -} - // Roots are the folders the scanner reads: the library. func (s *Scanner) Roots() []string { if s == nil { diff --git a/internal/library/scanner_test.go b/internal/library/scanner_test.go index fbceb4dc..d8d371c9 100644 --- a/internal/library/scanner_test.go +++ b/internal/library/scanner_test.go @@ -10,10 +10,10 @@ import ( "path/filepath" "testing" - "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5/pgtype" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func TestReleaseDateFromYear(t *testing.T) { @@ -44,24 +44,10 @@ func TestReleaseDateFromYear(t *testing.T) { // TestScanner_Integration exercises walk → tag-parse → upsert → incremental // skip against a real Postgres. Gated on MINSTREL_TEST_DATABASE_URL. func TestScanner_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) @@ -220,33 +206,19 @@ func writeTestMP3(t *testing.T, path string, frames map[string]string) { // reconcile would refuse to mark, adoption could not fire, and the file would // fork. See the "reconcile skipped" warning in Scan. func TestScanner_AdoptsMovedFile_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } root := t.TempDir() const movedMBID = "11111111-2222-3333-4444-555555555555" - movedFrom := filepath.Join(root, "artistM/albumM/04 - Bleed It Out.mp3") + movedFrom := filepath.Join(root, "artistM/albumM/04 - Ring It Out.mp3") writeTestMP3(t, movedFrom, map[string]string{ - "TIT2": "Bleed It Out", "TPE1": "Artist M", "TALB": "Album M", "TRCK": "4", + "TIT2": "Ring It Out", "TPE1": "Artist M", "TALB": "Album M", "TRCK": "4", // dhowden surfaces TXXX as a Comm whose Description is the Picard tag // name; "MusicBrainz Track Id" is mbz.Recording. "TXXX": "MusicBrainz Track Id\x00" + movedMBID, @@ -274,7 +246,7 @@ func TestScanner_AdoptsMovedFile_Integration(t *testing.T) { } // Renumber the file, exactly as a tag editor would. - movedTo := filepath.Join(root, "artistM/albumM/02 - Bleed It Out.mp3") + movedTo := filepath.Join(root, "artistM/albumM/02 - Ring It Out.mp3") if err := os.Rename(movedFrom, movedTo); err != nil { t.Fatalf("rename: %v", err) } @@ -314,24 +286,10 @@ func TestScanner_AdoptsMovedFile_Integration(t *testing.T) { // read existed gets it on the next scan, through the tagReadVersion bump, // without its file changing. func TestScanner_ReleaseGroupMBID_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } @@ -387,27 +345,13 @@ func TestScanner_ReleaseGroupMBID_Integration(t *testing.T) { } // Two albums of one name by one artist, in different release groups, are two -// albums, as Weezer's self-titled albums are. A +// albums, as Glasshouse's self-titled albums are. A // track of the same group joins its album, and a track filed under the other // album's row by the old lookup moves to its own on the tagReadVersion re-read. func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } @@ -420,14 +364,14 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing. tagged := func(rel, title, group string) string { p := filepath.Join(root, rel) writeTestMP3(t, p, map[string]string{ - "TIT2": title, "TPE1": "Weezer", "TALB": "Weezer", + "TIT2": title, "TPE1": "Glasshouse", "TALB": "Glasshouse", "TXXX": "MusicBrainz Release Group Id\x00" + group, }) return p } - tagged("Weezer (1994)/01.mp3", "My Name Is Jonas", blue) - tagged("Weezer (1994)/02.mp3", "No One Else", blue) - greenPath := tagged("Weezer (2001)/01.mp3", "Don't Let Go", green) + tagged("Glasshouse (1994)/01.mp3", "My Name Is Tobias", blue) + tagged("Glasshouse (1994)/02.mp3", "No One Near", blue) + greenPath := tagged("Glasshouse (2001)/01.mp3", "Don't Look Down", green) scanner := New(pool, logger, []string{root}, nil) if _, err := scanner.Scan(ctx, nil); err != nil { @@ -436,7 +380,7 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing. albumsByGroup := func() map[string]int { t.Helper() rows, err := pool.Query(ctx, `SELECT a.release_group_mbid, count(t.id) FROM albums a - JOIN tracks t ON t.album_id = a.id WHERE a.title = 'Weezer' GROUP BY a.id, a.release_group_mbid`) + JOIN tracks t ON t.album_id = a.id WHERE a.title = 'Glasshouse' GROUP BY a.id, a.release_group_mbid`) if err != nil { t.Fatal(err) } @@ -461,8 +405,8 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing. // A bonus track tagged with no release group joins the album its folder // holds, whichever row is older. - writeTestMP3(t, filepath.Join(root, "Weezer (2001)/02.mp3"), map[string]string{ - "TIT2": "Photograph (live)", "TPE1": "Weezer", "TALB": "Weezer", + writeTestMP3(t, filepath.Join(root, "Glasshouse (2001)/02.mp3"), map[string]string{ + "TIT2": "Polaroid (live)", "TPE1": "Glasshouse", "TALB": "Glasshouse", }) if _, err := scanner.Scan(ctx, nil); err != nil { t.Fatalf("scan the bonus track: %v", err) @@ -485,3 +429,198 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing. t.Errorf("after the re-read, albums by group = %v, want the green track on its own album", got) } } + +// TestScanFiles_ClearsTheMarkWhenAFileReturnsToItsPath_Integration: a file +// put back at the path of a track waiting for one (an admin removed it, or it +// went missing) brings the track back as soon as the watcher scans it, even +// with its old mtime, which takes the unchanged-file skip. The track keeps its +// id, and clients are told it plays again. +func TestScanFiles_ClearsTheMarkWhenAFileReturnsToItsPath_Integration(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + + root := t.TempDir() + path := filepath.Join(root, "Artist R/Album R/03 - Returning.mp3") + writeTestMP3(t, path, map[string]string{ + "TIT2": "Returning", "TPE1": "Artist R", "TALB": "Album R", "TRCK": "3", + }) + scanner := New(pool, logger, []string{root}, nil) + if _, err := scanner.ScanFiles(ctx, []string{path}); err != nil { + t.Fatalf("first scan: %v", err) + } + q := dbq.New(pool) + before, err := q.GetTrackByPath(ctx, path) + if err != nil { + t.Fatalf("track not indexed: %v", err) + } + + // Removed from Reports: the row waits, and the file is back unchanged. + if _, err := q.MarkTracksRemoved(ctx, dbq.MarkTracksRemovedParams{ + Reason: string(RemovedForReport), Ids: []pgtype.UUID{before.ID}, + }); err != nil { + t.Fatalf("mark removed: %v", err) + } + var changesBefore int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM library_changes").Scan(&changesBefore); err != nil { + t.Fatalf("count changes: %v", err) + } + + if _, err := scanner.ScanFiles(ctx, []string{path}); err != nil { + t.Fatalf("watcher scan: %v", err) + } + + after, err := q.GetTrackByID(ctx, before.ID) + if err != nil { + t.Fatalf("track gone: %v", err) + } + if after.MissingSince.Valid { + t.Errorf("track still waits for a file it has: missing_since=%v", after.MissingSince.Time) + } + if after.RemovedReason != nil { + t.Errorf("removed_reason = %q, want none once the file is back", *after.RemovedReason) + } + if after.FilePath != path { + t.Errorf("file_path = %q, want %q", after.FilePath, path) + } + var changesAfter int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM library_changes").Scan(&changesAfter); err != nil { + t.Fatalf("count changes: %v", err) + } + if changesAfter <= changesBefore { + t.Error("no library change logged, so clients would still show the track as unplayable") + } +} + +// An album is filed under its album artist: a compilation's tracks by +// different artists, and an album with one featured-artist track, are each +// one album, and every track keeps its own artist. The row the old filing +// left behind is removed by the scan's tidy-up once a re-read empties it. +func TestScanner_AlbumArtistKeepsAnAlbumTogether_Integration(t *testing.T) { + ctx := context.Background() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + pool := dbtest.Open(t) + if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { + t.Fatalf("truncate: %v", err) + } + + root := t.TempDir() + song := func(rel, title, artist, albumArtist, album string) string { + p := filepath.Join(root, rel) + frames := map[string]string{"TIT2": title, "TPE1": artist, "TALB": album} + if albumArtist != "" { + frames["TPE2"] = albumArtist + } + writeTestMP3(t, p, frames) + return p + } + song("Summer Hits/01.mp3", "Wave", "Low Tide Choir", "Various Artists", "Summer Hits") + song("Summer Hits/02.mp3", "Glass", "Paper Lanterns", "Various Artists", "Summer Hits") + song("Night Drive/01.mp3", "Neon", "Paper Lanterns", "Paper Lanterns", "Night Drive") + guest := song("Night Drive/02.mp3", "Static", "Paper Lanterns feat. Low Tide Choir", "Paper Lanterns", "Night Drive") + + scanner := New(pool, logger, []string{root}, nil) + if _, err := scanner.Scan(ctx, nil); err != nil { + t.Fatalf("scan: %v", err) + } + + type filing struct{ tracks, trackArtists int } + albums := func() map[string]filing { + t.Helper() + rows, err := pool.Query(ctx, ` + SELECT a.title, ar.name, count(t.id), count(DISTINCT t.artist_id) + FROM albums a JOIN artists ar ON ar.id = a.artist_id + LEFT JOIN tracks t ON t.album_id = a.id + GROUP BY a.id, a.title, ar.name`) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + out := map[string]filing{} + names := map[string]string{} + for rows.Next() { + var title, artist string + var tracks, trackArtists int + if err := rows.Scan(&title, &artist, &tracks, &trackArtists); err != nil { + t.Fatal(err) + } + if _, dup := out[title]; dup { + t.Fatalf("album %q has more than one row", title) + } + names[title] = artist + out[title] = filing{tracks: tracks, trackArtists: trackArtists} + } + if names["Summer Hits"] != "Various Artists" || names["Night Drive"] != "Paper Lanterns" { + t.Fatalf("album artists = %v, want Summer Hits by Various Artists and Night Drive by Paper Lanterns", names) + } + return out + } + got := albums() + if got["Summer Hits"].tracks != 2 || got["Summer Hits"].trackArtists != 2 { + t.Errorf("Summer Hits = %+v, want 2 tracks by 2 artists on one album", got["Summer Hits"]) + } + // The guest is a credit on the track, not an artist of their own. + if got["Night Drive"].tracks != 2 || got["Night Drive"].trackArtists != 1 { + t.Errorf("Night Drive = %+v, want 2 tracks, both filed under Paper Lanterns", got["Night Drive"]) + } + const guestCredit = "Paper Lanterns feat. Low Tide Choir" + creditOf := func() (artist string, credit *string) { + t.Helper() + if err := pool.QueryRow(ctx, ` + SELECT ar.name, t.artist_credit FROM tracks t JOIN artists ar ON ar.id = t.artist_id + WHERE t.file_path = $1`, guest).Scan(&artist, &credit); err != nil { + t.Fatal(err) + } + return artist, credit + } + if artist, credit := creditOf(); artist != "Paper Lanterns" || credit == nil || *credit != guestCredit { + t.Errorf("guest track filed under %q with credit %v, want Paper Lanterns with credit %q", artist, credit, guestCredit) + } + creditArtists := func() int { + t.Helper() + var n int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM artists WHERE name = $1`, guestCredit).Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + if n := creditArtists(); n != 0 { + t.Errorf("%d artists named %q, want none", n, guestCredit) + } + + // The guest track as the old filing left it: under an artist named for + // the whole credit, on an album of its own, both made long enough ago for + // the tidy-up, under an older tag-read version. + if _, err := pool.Exec(ctx, ` + WITH ar AS (INSERT INTO artists (name, sort_name, created_at) + VALUES ($2, lower($2), now() - interval '1 day') RETURNING id), + a AS (INSERT INTO albums (title, sort_title, artist_id, created_at) + SELECT 'Night Drive', 'night drive', id, now() - interval '1 day' FROM ar + RETURNING id) + UPDATE tracks SET album_id = (SELECT id FROM a), artist_id = (SELECT id FROM ar), + artist_credit = NULL, tag_read_version = 8 + WHERE file_path = $1`, guest, guestCredit); err != nil { + t.Fatal(err) + } + if _, err := scanner.Scan(ctx, nil); err != nil { + t.Fatalf("rescan: %v", err) + } + if got := albums(); got["Night Drive"].tracks != 2 || got["Night Drive"].trackArtists != 1 { + t.Errorf("after the re-read, Night Drive = %+v, want both tracks back on one album under Paper Lanterns", got["Night Drive"]) + } + if artist, credit := creditOf(); artist != "Paper Lanterns" || credit == nil || *credit != guestCredit { + t.Errorf("after the re-read, guest track filed under %q with credit %v, want Paper Lanterns with credit %q", artist, credit, guestCredit) + } + if n := creditArtists(); n != 0 { + t.Errorf("after the re-read, %d artists named %q, want the tidy-up to remove it", n, guestCredit) + } + var empty int + if err := pool.QueryRow(ctx, + `SELECT count(*) FROM albums a WHERE NOT EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)`, + ).Scan(&empty); err != nil { + t.Fatal(err) + } + if empty != 0 { + t.Errorf("%d empty album rows left after the scan, want the tidy-up to remove them", empty) + } +} diff --git a/internal/library/scanrecover_test.go b/internal/library/scanrecover_test.go new file mode 100644 index 00000000..9ef426e8 --- /dev/null +++ b/internal/library/scanrecover_test.go @@ -0,0 +1,57 @@ +package library + +import ( + "context" + "errors" + "testing" + + "github.com/jackc/pgx/v5/pgtype" +) + +// A scan the last shutdown cut off is closed at startup with the reason, so +// it no longer reads as a scan in progress. +func TestRecoverScanRuns_ClosesARunTheLastShutdownCutOff_Integration(t *testing.T) { + pool := triggerTestPool(t) + ctx := context.Background() + var id pgtype.UUID + if err := pool.QueryRow(ctx, + `INSERT INTO scan_runs (started_at) VALUES (now() - interval '5 minutes') RETURNING id`).Scan(&id); err != nil { + t.Fatal(err) + } + + RecoverScanRuns(ctx, pool, quietLogger()) + + var finished bool + var reason *string + if err := pool.QueryRow(ctx, + `SELECT finished_at IS NOT NULL, error_message FROM scan_runs WHERE id = $1`, id).Scan(&finished, &reason); err != nil { + t.Fatal(err) + } + if !finished || reason == nil || *reason == "" { + t.Errorf("finished %v, reason %v; want the run closed with why", finished, reason) + } +} + +// Saving library folders waits for a scan that is running, but not for an +// unfinished run older than StuckScanThreshold: that one is dead. +func TestSetRoots_OnlyALiveScanHoldsUpSavingFolders_Integration(t *testing.T) { + pool := triggerTestPool(t) + clearSavedRoots(t, pool) + ctx := context.Background() + s := New(pool, quietLogger(), nil, nil) + + if _, err := pool.Exec(ctx, `INSERT INTO scan_runs (started_at) VALUES (now() - interval '2 hours')`); err != nil { + t.Fatal(err) + } + if _, err := s.SetRoots(ctx, []RootChange{{Path: t.TempDir()}}); err != nil { + t.Errorf("a dead scan blocked saving folders: %v", err) + } + + if _, err := pool.Exec(ctx, `INSERT INTO scan_runs (started_at) VALUES (now())`); err != nil { + t.Fatal(err) + } + var re *RootsError + if _, err := s.SetRoots(ctx, []RootChange{{Path: t.TempDir()}}); !errors.As(err, &re) { + t.Errorf("err %v; want a refusal while a scan is running", err) + } +} diff --git a/internal/library/scanrun.go b/internal/library/scanrun.go index 752b8bd2..8e864170 100644 --- a/internal/library/scanrun.go +++ b/internal/library/scanrun.go @@ -10,8 +10,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) // LibraryStageTallies wires the scanner.Stats shape into the scan_runs jsonb diff --git a/internal/library/song_link_test.go b/internal/library/song_link_test.go index f42581ca..d20e9376 100644 --- a/internal/library/song_link_test.go +++ b/internal/library/song_link_test.go @@ -9,8 +9,8 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // songLinkFixture is the single and the album it came from: one song on two @@ -42,7 +42,7 @@ func newSongLinkFixture(t *testing.T, pool *pgxpool.Pool) songLinkFixture { t.Fatal(err) } tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ - Title: "Feel Good Inc.", AlbumID: a.ID, ArtistID: artist.ID, + Title: "Feel Fine Ltd.", AlbumID: a.ID, ArtistID: artist.ID, DurationMs: 1000, FilePath: path, FileSize: 100, FileFormat: "mp3", }) if err != nil { @@ -51,8 +51,8 @@ func newSongLinkFixture(t *testing.T, pool *pgxpool.Pool) songLinkFixture { return tr } f := songLinkFixture{ - single: track("Feel Good Inc. (single)", "/music/Link Artist/Feel Good Inc/01 Feel Good Inc.mp3"), - albumCut: track("Demon Days", "/music/Link Artist/Demon Days/06 Feel Good Inc.mp3"), + single: track("Feel Fine Ltd. (single)", "/music/Link Artist/Feel Fine Ltd/01 Feel Fine Ltd.mp3"), + albumCut: track("Ghost Nights", "/music/Link Artist/Ghost Nights/06 Feel Fine Ltd.mp3"), } f.user, err = q.CreateUser(ctx, dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + "song-link", PasswordHash: "x", ApiTokenHash: "song-link-token", @@ -75,12 +75,12 @@ func newSongLinkFixture(t *testing.T, pool *pgxpool.Pool) songLinkFixture { // list shows the song once, a like or unlike on either copy reaches both, and // "not the same song" undoes the link. func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) f := newSongLinkFixture(t, pool) - res, err := ResolveDuplicates(ctx, pool, nil, "", true) + res, err := ResolveDuplicates(ctx, pool, nil, true) if err != nil { t.Fatal(err) } @@ -99,15 +99,6 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) { if len(liked) != 2 { t.Errorf("liked track ids = %d, want both copies", len(liked)) } - var logged int - if err := pool.QueryRow(ctx, - `SELECT count(*) FROM library_changes WHERE entity_type = 'like_track' AND op = 'upsert'`, - ).Scan(&logged); err != nil { - t.Fatal(err) - } - if logged != 1 { - t.Errorf("logged %d shared likes, want 1 (the album cut)", logged) - } if n, err := q.CountLikedTracks(ctx, f.user.ID); err != nil || n != 1 { t.Errorf("CountLikedTracks = %d (%v), want 1 song", n, err) } @@ -120,7 +111,7 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) { } // A second pass changes nothing. - if res, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil || res.SongsLinked != 0 { + if res, err := ResolveDuplicates(ctx, pool, nil, true); err != nil || res.SongsLinked != 0 { t.Errorf("second pass linked %d (%v), want 0", res.SongsLinked, err) } @@ -151,28 +142,13 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) { } } -// With auto-resolve off the resolver links nothing. -func TestCrossReleaseLinkNeedsAutoResolve_Integration(t *testing.T) { - pool := newPool(t) - ctx := context.Background() - q := dbq.New(pool) - f := newSongLinkFixture(t, pool) - if _, err := ResolveDuplicates(ctx, pool, nil, "", false); err != nil { - t.Fatal(err) - } - keys := songKeys(t, q, f.single.ID, f.albumCut.ID) - if keys[0] == keys[1] { - t.Error("linked with auto-resolve off") - } -} - // A merge keeps the removed copy's link to the song on another release, // whichever copy's id names the song. That copy has no song_id of its own, // and its link must survive whichever way the random ids fall, including when // they make it the key. func TestMergeInheritsSongLink_Integration(t *testing.T) { for _, removeAlbumCut := range []bool{true, false} { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) f := newSongLinkFixture(t, pool) @@ -221,16 +197,16 @@ func songKeys(t *testing.T, q *dbq.Queries, ids ...pgtype.UUID) []pgtype.UUID { return out } -// A cross-release group whose album holds the song twice (Humanz: Saturnz -// Barz as a FLAC and a YouTube mp3, beside the single): the album's -// extra copy is merged into its FLAC, the single stays, and the two copies -// left are linked as one song. -func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integration(t *testing.T) { - pool := newPool(t) +// A cross-release group whose album holds the song twice (Mammalz: Neptunez +// Barz as a FLAC and an mp3, beside the single): every file stays, since +// another program may have filed any of them, and all three count as one +// song. Thinning the album's copies is an admin's merge. +func TestResolveDuplicates_KeepsEveryCopyInACrossReleaseGroup_Integration(t *testing.T) { + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() - artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Gorillaz", SortName: "Gorillaz"}) + artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Plastic Apes", SortName: "Plastic Apes"}) if err != nil { t.Fatal(err) } @@ -254,7 +230,7 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio t.Fatal(err) } tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ - Title: "Saturnz Barz", AlbumID: a.ID, ArtistID: artist.ID, + Title: "Neptunez Barz", AlbumID: a.ID, ArtistID: artist.ID, DurationMs: 181000, FilePath: path, FileSize: 100, FileFormat: format, }) if err != nil { @@ -262,12 +238,12 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio } return tr } - flac := track("Humanz", "04 Saturnz Barz.flac", "flac") - mp3 := track("Humanz", "06 Saturnz Barz (feat. Popcaan).mp3", "mp3") - single := track("Saturnz Barz", "01 Saturnz Barz.mp3", "mp3") + flac := track("Mammalz", "04 Neptunez Barz.flac", "flac") + mp3 := track("Mammalz", "06 Neptunez Barz (feat. Popkern).mp3", "mp3") + single := track("Neptunez Barz", "01 Neptunez Barz.mp3", "mp3") var groupID pgtype.UUID if err := pool.QueryRow(ctx, - `INSERT INTO duplicate_groups (member_key, tier) VALUES ('humanz-saturnz', 'exact') RETURNING id`, + `INSERT INTO duplicate_groups (member_key, tier) VALUES ('mammalz-neptunez', 'exact') RETURNING id`, ).Scan(&groupID); err != nil { t.Fatal(err) } @@ -276,18 +252,18 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio t.Fatal(err) } - res, err := ResolveDuplicates(ctx, pool, nil, "", true) + res, err := ResolveDuplicates(ctx, pool, nil, true) if err != nil { t.Fatal(err) } - if res.Merged != 1 || exists(mp3.FilePath) || !exists(flac.FilePath) || !exists(single.FilePath) { - t.Fatalf("result %+v, mp3 %v flac %v single %v; want only the album's mp3 merged away", - res, exists(mp3.FilePath), exists(flac.FilePath), exists(single.FilePath)) - } - if _, err := q.GetTrackByID(ctx, mp3.ID); err == nil { - t.Error("the album's extra copy is still a track") + if !exists(mp3.FilePath) || !exists(flac.FilePath) || !exists(single.FilePath) { + t.Fatalf("mp3 %v flac %v single %v; want every file left in place", + exists(mp3.FilePath), exists(flac.FilePath), exists(single.FilePath)) } if res.SongsLinked != 1 { - t.Errorf("songs linked = %d, want the FLAC and the single linked as one song", res.SongsLinked) + t.Errorf("songs linked = %d, want the group linked as one song", res.SongsLinked) + } + if keys := songKeys(t, q, flac.ID, mp3.ID, single.ID); keys[0] != keys[1] || keys[1] != keys[2] { + t.Errorf("song keys %v, want all three copies one song", keys) } } diff --git a/internal/library/source_markers.go b/internal/library/source_markers.go index dec5ecf1..bec7de39 100644 --- a/internal/library/source_markers.go +++ b/internal/library/source_markers.go @@ -24,7 +24,7 @@ type sourceMarker struct { // suspectSourceMarkers was calibrated against a real library. Two candidates // were left out on purpose: // - "live in"/"live at": nearly all from real live albums. -// - a bare "reaction": it caught Beck's "Chain Reaction". The marker below +// - a bare "reaction": it caught songs called "Chain Reaction". The marker below // wants the phrases a reaction video actually uses. var suspectSourceMarkers = []sourceMarker{ {"music video", `official[^a-zA-Z]*(music[^a-zA-Z]*)?video|music[^a-zA-Z]*video`}, diff --git a/internal/library/source_markers_test.go b/internal/library/source_markers_test.go index 6eb5086d..d374555d 100644 --- a/internal/library/source_markers_test.go +++ b/internal/library/source_markers_test.go @@ -5,32 +5,32 @@ import ( "testing" ) -// Real basenames, each with the -// labels it should carry. The negatives are the near misses that shaped the +// Basenames in the shapes real files take, each with the labels it should +// carry. Every artist and title is invented. The negatives are the near misses that shaped the // list: a song called "Chain Reaction", a live album, an ordinary track. func TestSourceMarkersFor(t *testing.T) { cases := []struct { base string want []string }{ - {"Daft Punk - Random Access Memories - 06 - Daft Punk - Doin' It Right (Music Video) ft. Panda Bear.mp3", []string{"music video"}}, - {"Gorillaz - Humanz - 03 - Gorillaz - Saturnz Barz (Official Video).mp3", []string{"music video"}}, - {"Gorillaz - Humanz - 05 - Gorillaz - Andromeda (Official Audio).mp3", []string{"official audio"}}, - {"Gorillaz - Gorillaz - 06 - Gorillaz - P45 (Visualizer).mp3", []string{"visualiser"}}, - {"Gorillaz - Demon Days - 16 - Gorillaz - Don Quixote's Christmas Bonanza (Visualiser).mp3", []string{"visualiser"}}, + {"Deft Monks - Random Access Dreams - 06 - Deft Monks - Doin' It Twice (Music Video) ft. Koala Bear.mp3", []string{"music video"}}, + {"Plastic Apes - Mammalz - 03 - Plastic Apes - Neptunez Barz (Official Video).mp3", []string{"music video"}}, + {"Plastic Apes - Mammalz - 05 - Plastic Apes - Cassiopeia (Official Audio).mp3", []string{"official audio"}}, + {"Plastic Apes - Plastic Apes - 06 - Plastic Apes - Q46 (Visualizer).mp3", []string{"visualiser"}}, + {"Plastic Apes - Ghost Nights - 16 - Plastic Apes - Sancho's Holiday Bonanza (Visualiser).mp3", []string{"visualiser"}}, {"Artist - Album - 01 - Artist - Song (Lyric Video).mp3", []string{"lyric video"}}, - {"Gorillaz - Humanz - 02 - FIRST TIME HEARING Gorillaz - Ascension REACTION.mp3", []string{"reaction"}}, - {"Watsky - INTENTION - 05 - MANIAC Reacts to Watsky - AWW SHiT.mp3", []string{"reaction"}}, - {"米津玄師 - diorama - 09 - 【MV】米津玄師 - 恋と病熱.mp3", []string{"MV"}}, - {"Andora - Ego - 01 - Andora - Ego (feat. Will Stetson) MV.mp3", []string{"MV"}}, - {"Jimmy Eat World - Something(s) Loud - 05 - Jimmy Eat World - Call to Love (Audio).mp3", []string{"[Audio]"}}, + {"Plastic Apes - Mammalz - 02 - FIRST TIME HEARING Plastic Apes - Elevation REACTION.mp3", []string{"reaction"}}, + {"Lantern Fox - INTENTIONS - 05 - MANIAC Reacts to Lantern Fox - Paper Cuts.mp3", []string{"reaction"}}, + {"月見草 - 箱庭 - 09 - 【MV】月見草 - 夜の灯.mp3", []string{"MV"}}, + {"Velmara - Ego - 01 - Velmara - Ego (feat. Ivo Brand) MV.mp3", []string{"MV"}}, + {"Porch Light Parade - Something(s) Loud - 05 - Porch Light Parade - Call to Love (Audio).mp3", []string{"[Audio]"}}, {"Record Heat - World War IV - 03 - Record Heat - Front Seat Feelin' [Audio].mp3", []string{"[Audio]"}}, - {"Aphex Twin - Come To Daddy - 03 - Aphex Twin - Bucephalus Bouncing Ball (HQ).mp3", []string{"[HD]"}}, + {"Apex Sibling - Come To Mother - 03 - Apex Sibling - Pegasus Bouncing Ball (HQ).mp3", []string{"[HD]"}}, {"Artist - Album - 01 - Artist - Song (Official Lyric Video) [4K].mp3", []string{"lyric video", "[HD]"}}, - {"Beck - Guero - 15 - Beck - Chain Reaction.mp3", nil}, - {"Nirvana - MTV Unplugged in New York - 01 - About a Girl (live in New York).flac", nil}, - {"Boards of Canada - Music Has the Right to Children - 05 - Roygbiv.flac", nil}, + {"Odd Hollow - Gringo Days - 15 - Odd Hollow - Chain Reaction.mp3", nil}, + {"Kettle Saints - Unplugged in Old York - 01 - About a Ghost (live in New York).flac", nil}, + {"Fields of Ontario - Music Has the Right to Wander - 05 - Prismatic.flac", nil}, {"Artist - Album - 01 - Mvula.flac", nil}, } for _, c := range cases { diff --git a/internal/library/stage_publisher_test.go b/internal/library/stage_publisher_test.go index f04e651e..4e883171 100644 --- a/internal/library/stage_publisher_test.go +++ b/internal/library/stage_publisher_test.go @@ -25,22 +25,29 @@ func newTestPublisher(t *testing.T, flushEvery int, flushPeriod time.Duration) ( return pub, &marshalCalls, &persistCalls } -func TestStagePublisher_Tick_FlushesAtCountThreshold(t *testing.T) { - pub, _, persists := newTestPublisher(t, 3, 1*time.Hour) // huge time so only count fires - - for i := 0; i < 3; i++ { - pub.Tick() +// Progress is persisted every flushEvery ticks, and a Flush persists at once +// and starts the count again. +func TestStagePublisher_FlushesEveryNTicksAndOnFlush(t *testing.T) { + pub, _, persists := newTestPublisher(t, 5, time.Hour) // a long period, so only the count fires + tick := func(n int, want int32) { + t.Helper() + for range n { + pub.Tick() + } + if got := persists.Load(); got != want { + t.Fatalf("persists = %d, want %d", got, want) + } } - if persists.Load() != 1 { - t.Errorf("persists after 3 ticks = %d, want 1", persists.Load()) + tick(5, 1) + tick(4, 1) + if err := pub.Flush(); err != nil { + t.Fatal(err) } - - for i := 0; i < 3; i++ { - pub.Tick() - } - if persists.Load() != 2 { - t.Errorf("persists after 6 ticks = %d, want 2", persists.Load()) + if got := persists.Load(); got != 2 { + t.Fatalf("persists after Flush = %d, want 2", got) } + tick(4, 2) // the count restarted at the Flush + tick(1, 3) } func TestStagePublisher_Tick_FlushesOnTimeout(t *testing.T) { @@ -58,78 +65,22 @@ func TestStagePublisher_Tick_FlushesOnTimeout(t *testing.T) { } } -func TestStagePublisher_Flush_AlwaysPersists(t *testing.T) { - pub, _, persists := newTestPublisher(t, 1000, 1*time.Hour) - - pub.Tick() // doesn't flush — count too low, time too long - - if err := pub.Flush(); err != nil { - t.Errorf("Flush() err = %v, want nil", err) - } - if persists.Load() != 1 { - t.Errorf("persists after Flush = %d, want 1", persists.Load()) - } -} - -func TestStagePublisher_Tick_SwallowsPersistErrors(t *testing.T) { - persistCalls := atomic.Int32{} - pub := newStagePublisher(context.Background(), 1, 1*time.Hour, +// A failed persist doesn't stop later ticks from persisting (a scan carries +// on through a database hiccup), but Flush, the final write, reports it. +func TestStagePublisher_PersistErrors(t *testing.T) { + wantErr := errors.New("simulated DB failure") + var calls atomic.Int32 + pub := newStagePublisher(context.Background(), 1, time.Hour, func() []byte { return []byte(`{}`) }, - func(_ []byte) error { - persistCalls.Add(1) - return errors.New("simulated DB failure") - }, + func([]byte) error { calls.Add(1); return wantErr }, ) - - // Ticks should not panic, should keep firing the persist (which keeps - // erroring). - for i := 0; i < 5; i++ { + for range 5 { pub.Tick() } - if persistCalls.Load() != 5 { - t.Errorf("persistCalls after 5 ticks = %d, want 5 (errors should not stop subsequent ticks)", persistCalls.Load()) + if calls.Load() != 5 { + t.Errorf("persist calls after 5 ticks = %d, want 5", calls.Load()) } -} - -func TestStagePublisher_Flush_PropagatesPersistError(t *testing.T) { - wantErr := errors.New("DB exploded") - pub := newStagePublisher(context.Background(), 1, 1*time.Hour, - func() []byte { return []byte(`{}`) }, - func(_ []byte) error { return wantErr }, - ) - if err := pub.Flush(); !errors.Is(err, wantErr) { t.Errorf("Flush() err = %v, want %v", err, wantErr) } } - -func TestStagePublisher_FlushResetsCounters(t *testing.T) { - pub, _, persists := newTestPublisher(t, 5, 1*time.Hour) - - for i := 0; i < 4; i++ { - pub.Tick() - } - if persists.Load() != 0 { - t.Errorf("persists at 4 ticks = %d, want 0", persists.Load()) - } - - if err := pub.Flush(); err != nil { - t.Fatal(err) - } - if persists.Load() != 1 { - t.Fatalf("persists after Flush = %d, want 1", persists.Load()) - } - - // After Flush, the counter resets — need 5 more ticks to flush again. - for i := 0; i < 4; i++ { - pub.Tick() - } - if persists.Load() != 1 { - t.Errorf("persists after Flush + 4 ticks = %d, want 1 (counter should have reset)", persists.Load()) - } - - pub.Tick() // 5th tick after reset → flush - if persists.Load() != 2 { - t.Errorf("persists after Flush + 5 ticks = %d, want 2", persists.Load()) - } -} diff --git a/internal/library/trigger.go b/internal/library/trigger.go index 52c3e8bd..f97b8b76 100644 --- a/internal/library/trigger.go +++ b/internal/library/trigger.go @@ -10,8 +10,9 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // StuckScanThreshold is the age past which an in-flight scan_runs row is @@ -20,6 +21,33 @@ import ( // duration so a normally-running scan is never reaped accidentally. const StuckScanThreshold = 1 * time.Hour +// RecoverScanRuns closes the scan runs a stopped server left unfinished. It +// runs once at startup, before the first scan: none can be running yet. +func RecoverScanRuns(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) { + n, err := dbq.New(pool).FailUnfinishedScanRuns(ctx) + if err != nil { + logger.Warn("scan: recover unfinished runs", "err", err) + return + } + if n > 0 { + logger.Warn("scan: a run was cut off by the last shutdown", "runs", n) + } +} + +// scanRunning reports whether a library scan is running now: an unfinished +// run that started within StuckScanThreshold. An older unfinished run is a +// dead one, and doesn't hold anything up. +func scanRunning(ctx context.Context, q *dbq.Queries) (bool, error) { + run, err := q.GetInFlightScanRun(ctx) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + return time.Since(run.StartedAt.Time) <= StuckScanThreshold, nil +} + // TryStartScan attempts to start a new scan, with built-in handling for // stuck/stale in-flight rows. // @@ -56,10 +84,10 @@ func TryStartScan(ctx context.Context, pool *pgxpool.Pool, } // No in-flight (or just reaped). Start RunScan detached. - go func() { + go periodic.Safe(ctx, logger, "scan run", func(ctx context.Context) { if _, runErr := RunScan(ctx, pool, scanner, enricher, logger, cfg); runErr != nil { logger.Warn("scan run failed", "err", runErr) } - }() + }) return true, nil, nil } diff --git a/internal/library/trigger_test.go b/internal/library/trigger_test.go index 24f20049..37bd49ee 100644 --- a/internal/library/trigger_test.go +++ b/internal/library/trigger_test.go @@ -2,30 +2,21 @@ package library import ( "context" - "errors" "io" "log/slog" - "os" "testing" "time" - "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) -// triggerTestPool returns a pool against MINSTREL_TEST_DATABASE_URL or skips. +// triggerTestPool opens the test database with no scan runs recorded. func triggerTestPool(t *testing.T) *pgxpool.Pool { t.Helper() - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) // Reset scan_runs so each test starts clean. if _, err := pool.Exec(context.Background(), `DELETE FROM scan_runs`); err != nil { t.Fatalf("reset: %v", err) @@ -38,128 +29,61 @@ func quietLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } -func TestTryStartScan_NoInFlight_Starts(t *testing.T) { - pool := triggerTestPool(t) +// A scan starts unless another is running. A run that has been "running" for +// two hours is a crashed one: it is closed as reaped and a new scan starts. +func TestTryStartScan_StartsUnlessAFreshScanIsRunning(t *testing.T) { + for _, tc := range []struct { + name string + inFlightAge string // "" seeds no run + wantStarted bool + }{ + {"nothing running", "", true}, + {"a fresh run", "0 seconds", false}, + {"a stale run", "2 hours", true}, + } { + t.Run(tc.name, func(t *testing.T) { + pool := triggerTestPool(t) + ctx := context.Background() + var seeded pgtype.UUID + if tc.inFlightAge != "" { + if err := pool.QueryRow(ctx, + `INSERT INTO scan_runs (started_at) VALUES (now() - $1::interval) RETURNING id`, tc.inFlightAge, + ).Scan(&seeded); err != nil { + t.Fatalf("seed: %v", err) + } + } - started, existing, err := TryStartScan( - context.Background(), pool, - nil, nil, // scanner/enricher: nil OK because the goroutine that uses them is detached and we don't await it. - quietLogger(), RunScanConfig{}, - ) - if err != nil { - t.Fatalf("err = %v, want nil", err) - } - if !started { - t.Errorf("started = false, want true") - } - if existing != nil { - t.Errorf("existing = %v, want nil", existing) - } - // Give the detached goroutine a moment. - time.Sleep(50 * time.Millisecond) -} - -func TestTryStartScan_FreshInFlight_Skips(t *testing.T) { - pool := triggerTestPool(t) - - // Seed a fresh in-flight row. - var rowID pgtype.UUID - if err := pool.QueryRow(context.Background(), - `INSERT INTO scan_runs (started_at) VALUES (now()) RETURNING id`, - ).Scan(&rowID); err != nil { - t.Fatalf("seed: %v", err) - } - - started, existing, err := TryStartScan( - context.Background(), pool, - nil, nil, - quietLogger(), RunScanConfig{}, - ) - if err != nil { - t.Fatalf("err = %v, want nil", err) - } - if started { - t.Errorf("started = true, want false") - } - if existing == nil { - t.Fatal("existing = nil, want non-nil") - } - if existing.ID != rowID { - t.Errorf("existing.ID = %v, want %v", existing.ID, rowID) - } -} - -func TestTryStartScan_StaleInFlight_Reaps(t *testing.T) { - pool := triggerTestPool(t) - - // Seed a stale in-flight row (started 2 hours ago). - var staleID pgtype.UUID - if err := pool.QueryRow(context.Background(), - `INSERT INTO scan_runs (started_at) VALUES (now() - interval '2 hours') RETURNING id`, - ).Scan(&staleID); err != nil { - t.Fatalf("seed: %v", err) - } - - started, existing, err := TryStartScan( - context.Background(), pool, - nil, nil, - quietLogger(), RunScanConfig{}, - ) - if err != nil { - t.Fatalf("err = %v, want nil", err) - } - if !started { - t.Errorf("started = false, want true (stale row should reap and proceed)") - } - if existing != nil { - t.Errorf("existing = %v, want nil", existing) - } - - // Verify the stale row was reaped: finished_at non-NULL, error_message - // contains "reaped". - var finishedAt pgtype.Timestamptz - var errMsg *string - if err := pool.QueryRow(context.Background(), - `SELECT finished_at, error_message FROM scan_runs WHERE id = $1`, staleID, - ).Scan(&finishedAt, &errMsg); err != nil { - t.Fatalf("verify reap: %v", err) - } - if !finishedAt.Valid { - t.Errorf("finished_at = NULL, want non-NULL after reap") - } - if errMsg == nil || *errMsg != "reaped (stale)" { - t.Errorf("error_message = %v, want 'reaped (stale)'", errMsg) - } - - time.Sleep(50 * time.Millisecond) -} - -func TestTryStartScan_DBError_Propagates(t *testing.T) { - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } - pool.Close() // close immediately to force errors on subsequent queries - - started, existing, err := TryStartScan( - context.Background(), pool, - nil, nil, - quietLogger(), RunScanConfig{}, - ) - if err == nil { - t.Errorf("err = nil, want non-nil for closed pool") - } - if errors.Is(err, pgx.ErrNoRows) { - t.Errorf("err is ErrNoRows; want a different DB error type") - } - if started { - t.Errorf("started = true, want false on DB error") - } - if existing != nil { - t.Errorf("existing = %v, want nil on DB error", existing) + // scanner/enricher nil: the goroutine that uses them is detached + // and not awaited. + started, existing, err := TryStartScan(ctx, pool, nil, nil, quietLogger(), RunScanConfig{}) + if err != nil { + t.Fatalf("err = %v, want nil", err) + } + if started != tc.wantStarted { + t.Errorf("started = %v, want %v", started, tc.wantStarted) + } + if tc.wantStarted && existing != nil { + t.Errorf("existing = %v, want nil", existing) + } + if !tc.wantStarted && (existing == nil || existing.ID != seeded) { + t.Errorf("existing = %v, want the running row %v", existing, seeded) + } + if tc.name == "a stale run" { + var finishedAt pgtype.Timestamptz + var errMsg *string + if err := pool.QueryRow(ctx, + `SELECT finished_at, error_message FROM scan_runs WHERE id = $1`, seeded, + ).Scan(&finishedAt, &errMsg); err != nil { + t.Fatalf("verify reap: %v", err) + } + if !finishedAt.Valid || errMsg == nil || *errMsg != "reaped (stale)" { + t.Errorf("stale row finished=%v message=%v, want closed as 'reaped (stale)'", finishedAt.Valid, errMsg) + } + } + if started { + // Give the detached goroutine a moment. + time.Sleep(50 * time.Millisecond) + } + }) } } diff --git a/internal/library/vorbisgenre.go b/internal/library/vorbisgenre.go index 590ba10c..2a3666fd 100644 --- a/internal/library/vorbisgenre.go +++ b/internal/library/vorbisgenre.go @@ -7,6 +7,8 @@ import ( "errors" "io" "strings" + + "github.com/Fabled-Sword/minstrel/internal/tagread" ) // Why this file exists: Vorbis comments (FLAC, Ogg Vorbis, Opus) say a field @@ -22,7 +24,9 @@ import ( // other seven would never be seen by browse or the taste profile. // // The comment block is read here directly, as the ID3v2 genre frame is in -// id3v2genre.go. Every other field still comes from dhowden/tag. +// id3v2genre.go, for the fields where a repeat matters: GENRE, and the +// ARTISTS and MUSICBRAINZ_ARTISTID lists an artist credit is read from +// (artistcredit.go). Every other field still comes from dhowden/tag. // maxVorbisCommentSize caps a comment block or packet. Comments are kilobytes; // an embedded METADATA_BLOCK_PICTURE can take them to a few megabytes. The cap @@ -32,9 +36,17 @@ const maxVorbisCommentSize = 16 << 20 var errMalformedComment = errors.New("library: malformed Vorbis comment") // readFLACGenreValues returns every GENRE value in a FLAC file's comment block. -// (nil, nil) means the file is readable and declares no genre. rs is seeked to -// the start, so it is safe to call after dhowden/tag has consumed the reader. -func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) { +// (nil, nil) means the file is readable and declares no genre. +func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) { return readFLACValues(rs, "GENRE") } + +// readOggGenreValues returns every GENRE value in an Ogg Vorbis or Opus file. +func readOggGenreValues(rs io.ReadSeeker) ([]string, error) { return readOggValues(rs, "GENRE") } + +// readFLACValues returns every value of the comment field key in a FLAC +// file's comment block, in file order. (nil, nil) means the file is readable +// and has no such field. rs is seeked to the start, so it is safe to call after +// dhowden/tag has consumed the reader. +func readFLACValues(rs io.ReadSeeker, key string) ([]string, error) { if _, err := rs.Seek(0, io.SeekStart); err != nil { return nil, err } @@ -49,7 +61,7 @@ func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) { if _, err := io.ReadFull(rs, rest[:]); err != nil { return nil, errNoGenreFrame } - size := syncsafeInt(rest[2:6]) + size := tagread.SyncsafeInt(rest[2:6]) if size < 0 { return nil, errNoGenreFrame } @@ -82,7 +94,7 @@ func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) { if _, err := io.ReadFull(rs, body); err != nil { return nil, errNoGenreFrame } - return vorbisCommentGenres(body) + return vorbisCommentValues(body, key) case 127: // invalid by spec; nothing after it can be trusted return nil, errNoGenreFrame } @@ -95,11 +107,12 @@ func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) { } } -// readOggGenreValues returns every GENRE value in an Ogg Vorbis or Opus file. -// The comments are the stream's second packet, which can span several pages -// when it carries cover art, so pages are reassembled until it is complete. -// Only the first logical stream is read; pages of any other are skipped. -func readOggGenreValues(rs io.ReadSeeker) ([]string, error) { +// readOggValues returns every value of the comment field key in an Ogg Vorbis +// or Opus file. The comments are the stream's second packet, which can span +// several pages when it carries cover art, so pages are reassembled until it +// is complete. Only the first logical stream is read; pages of any other are +// skipped. +func readOggValues(rs io.ReadSeeker, key string) ([]string, error) { if _, err := rs.Seek(0, io.SeekStart); err != nil { return nil, err } @@ -149,7 +162,7 @@ func readOggGenreValues(rs io.ReadSeeker) ([]string, error) { continue // the packet carries on in the next segment } if packetIdx == 1 { - return oggCommentGenres(packet) + return oggCommentValues(packet, key) } packetIdx++ packet = packet[:0] @@ -157,24 +170,24 @@ func readOggGenreValues(rs io.ReadSeeker) ([]string, error) { } } -// oggCommentGenres strips the codec's comment-packet prefix. Ogg FLAC and Speex +// oggCommentValues strips the codec's comment-packet prefix. Ogg FLAC and Speex // are rare enough to leave to dhowden/tag. -func oggCommentGenres(packet []byte) ([]string, error) { +func oggCommentValues(packet []byte, key string) ([]string, error) { switch { case bytes.HasPrefix(packet, []byte("\x03vorbis")): - return vorbisCommentGenres(packet[7:]) + return vorbisCommentValues(packet[7:], key) case bytes.HasPrefix(packet, []byte("OpusTags")): - return vorbisCommentGenres(packet[8:]) + return vorbisCommentValues(packet[8:], key) } return nil, errNoGenreFrame } -// vorbisCommentGenres reads a comment block (vendor string, then a count of +// vorbisCommentValues reads a comment block (vendor string, then a count of // length-prefixed "KEY=value" entries, little-endian lengths throughout) and -// returns the GENRE values in file order. Field names are case-insensitive by -// spec. Anything after the last entry, such as Vorbis's framing bit, is -// ignored. -func vorbisCommentGenres(b []byte) ([]string, error) { +// returns the values of field key in file order. Field names are +// case-insensitive by spec. Anything after the last entry, such as Vorbis's +// framing bit, is ignored. +func vorbisCommentValues(b []byte, key string) ([]string, error) { next := func() ([]byte, bool) { if len(b) < 4 { return nil, false @@ -203,8 +216,8 @@ func vorbisCommentGenres(b []byte) ([]string, error) { if !ok { return nil, errMalformedComment } - key, value, found := strings.Cut(string(field), "=") - if !found || !strings.EqualFold(key, "GENRE") { + name, value, found := strings.Cut(string(field), "=") + if !found || !strings.EqualFold(name, key) { continue } if value = strings.TrimSpace(value); value != "" { diff --git a/internal/library/vorbisgenre_test.go b/internal/library/vorbisgenre_test.go index 9277c92c..8ba624e3 100644 --- a/internal/library/vorbisgenre_test.go +++ b/internal/library/vorbisgenre_test.go @@ -5,8 +5,6 @@ import ( "encoding/binary" "strings" "testing" - - "github.com/dhowden/tag" ) // vorbisComment builds a comment block: vendor, count, then each "KEY=value". @@ -161,28 +159,6 @@ func genreFields(values ...string) []string { return out } -// Shaped like a real multi-genre FLAC: -// eight GENRE fields, of which dhowden/tag keeps the last. -func TestExtractGenres_FLACRepeatedFields(t *testing.T) { - data := buildFLAC(false, append([]string{"TITLE=Eons"}, genreFields(lifeForms...)...)...) - rs := bytes.NewReader(data) - meta, err := tag.ReadFrom(rs) - if err != nil { - t.Fatalf("tag.ReadFrom: %v", err) - } - // Confirm the upstream behaviour this reader works around is still present. - if got := meta.Genre(); got != "Instrumental Hip Hop" { - t.Logf("note: dhowden/tag no longer keeps only the last GENRE (got %q)", got) - } - genres, fellBack := extractGenres(meta, rs) - if fellBack { - t.Error("fellBack = true, want false") - } - if !equalStrings(genres, lifeForms) { - t.Errorf("genres = %q, want %q", genres, lifeForms) - } -} - func TestReadFLACGenreValues(t *testing.T) { tests := []struct { name string @@ -196,6 +172,7 @@ func TestReadFLACGenreValues(t *testing.T) { {"empty values dropped", buildFLAC(false, "GENRE= ", "GENRE=Rock"), []string{"Rock"}, false}, {"a key that only starts with GENRE", buildFLAC(false, "GENRES=Rock", "GENRE=Jazz"), []string{"Jazz"}, false}, {"not a FLAC", []byte("RIFF....WAVEfmt "), nil, true}, + {"a cut-off comment block", func() []byte { d := buildFLAC(false, "GENRE=Jazz", "GENRE=Bop"); return d[:len(d)-2] }(), nil, true}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -210,44 +187,28 @@ func TestReadFLACGenreValues(t *testing.T) { } } -func TestReadFLACGenreValues_TruncatedCommentIsAnError(t *testing.T) { - data := buildFLAC(false, "GENRE=Jazz", "GENRE=Bop") - if _, err := readFLACGenreValues(bytes.NewReader(data[:len(data)-2])); err == nil { - t.Error("err = nil for a cut-off comment block") - } -} - -func TestExtractGenres_OggVorbisRepeatedFields(t *testing.T) { - comment := append([]byte("\x03vorbis"), vorbisComment(genreFields("Shoegaze", "Dream Pop")...)...) - comment = append(comment, 1) // framing bit - rs := bytes.NewReader(buildOgg(7, vorbisIdent(), comment)) - meta, err := tag.ReadFrom(rs) - if err != nil { - t.Fatalf("tag.ReadFrom: %v", err) - } - genres, fellBack := extractGenres(meta, rs) - if fellBack || !equalStrings(genres, []string{"Shoegaze", "Dream Pop"}) { - t.Errorf("genres = %q (fellBack %v), want [Shoegaze Dream Pop]", genres, fellBack) - } -} - -func TestReadOggGenreValues_Opus(t *testing.T) { - head := append([]byte("OpusHead"), make([]byte, 11)...) - tags := append([]byte("OpusTags"), vorbisComment(genreFields("Ambient", "Drone")...)...) - got, err := readOggGenreValues(bytes.NewReader(buildOgg(3, head, tags))) - if err != nil || !equalStrings(got, []string{"Ambient", "Drone"}) { - t.Errorf("got %q, %v; want [Ambient Drone]", got, err) - } -} - -// Cover art makes the comment packet span pages. A reader that stopped at the -// first page boundary would read a truncated block. -func TestReadOggGenreValues_PacketSpansPages(t *testing.T) { - fields := append([]string{"METADATA_BLOCK_PICTURE=" + strings.Repeat("A", 70000)}, genreFields("Jazz", "Bop")...) - comment := append([]byte("\x03vorbis"), vorbisComment(fields...)...) - got, err := readOggGenreValues(bytes.NewReader(buildOgg(9, vorbisIdent(), comment))) - if err != nil || !equalStrings(got, []string{"Jazz", "Bop"}) { - t.Errorf("got %q, %v; want [Jazz Bop]", got, err) +// Ogg genres are read from Vorbis and Opus comment packets. Cover art makes +// the comment packet span pages, so a reader that stopped at the first page +// boundary would read a truncated block. +func TestReadOggGenreValues(t *testing.T) { + opusHead := append([]byte("OpusHead"), make([]byte, 11)...) + opusTags := append([]byte("OpusTags"), vorbisComment(genreFields("Ambient", "Drone")...)...) + bigFields := append([]string{"METADATA_BLOCK_PICTURE=" + strings.Repeat("A", 70000)}, genreFields("Jazz", "Bop")...) + bigComment := append([]byte("\x03vorbis"), vorbisComment(bigFields...)...) + for _, tc := range []struct { + name string + data []byte + want []string + }{ + {"opus", buildOgg(3, opusHead, opusTags), []string{"Ambient", "Drone"}}, + {"a packet spanning pages", buildOgg(9, vorbisIdent(), bigComment), []string{"Jazz", "Bop"}}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := readOggGenreValues(bytes.NewReader(tc.data)) + if err != nil || !equalStrings(got, tc.want) { + t.Errorf("got %q, %v; want %q", got, err, tc.want) + } + }) } } @@ -274,15 +235,3 @@ func TestReadMP4GenreValues(t *testing.T) { }) } } - -func TestExtractGenres_MP4MultiValue(t *testing.T) { - rs := bytes.NewReader(buildMP4(true, mp4Box("\xa9gen", mp4Text("Hip Hop"), mp4Text("Lo-Fi")))) - meta, err := tag.ReadFrom(rs) - if err != nil { - t.Fatalf("tag.ReadFrom: %v", err) - } - genres, fellBack := extractGenres(meta, rs) - if fellBack || !equalStrings(genres, []string{"Hip Hop", "Lo-Fi"}) { - t.Errorf("genres = %q (fellBack %v), want [Hip Hop Lo-Fi]", genres, fellBack) - } -} diff --git a/internal/library/watcher.go b/internal/library/watcher.go index c22a4c87..960bc3de 100644 --- a/internal/library/watcher.go +++ b/internal/library/watcher.go @@ -11,7 +11,7 @@ import ( "github.com/fsnotify/fsnotify" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" + "github.com/Fabled-Sword/minstrel/internal/coverart" ) // watcherDebounce is the quiet period after the last filesystem event before @@ -176,6 +176,9 @@ func (w *Watcher) eventLoop(ctx context.Context, fsw *fsnotify.Watcher, batches func (w *Watcher) handleEvent( fsw *fsnotify.Watcher, event fsnotify.Event, pending map[string]struct{}, ) bool { + if hiddenInLibrary(w.scanner.Roots(), event.Name) { + return false + } info, err := os.Stat(event.Name) isDir := err == nil && info.IsDir() isAudio := audioExtensions[strings.ToLower(filepath.Ext(event.Name))] @@ -230,13 +233,17 @@ func (w *Watcher) process(ctx context.Context, paths []string) { } } -// addRecursive adds an fsnotify watch for root and every subdirectory under it. -// Per-directory failures (inotify limits, permissions) are logged and skipped. +// addRecursive adds an fsnotify watch for root and every subdirectory under it +// that is not hidden. Per-directory failures (inotify limits, permissions) are +// logged and skipped. func (w *Watcher) addRecursive(fsw *fsnotify.Watcher, root string) { _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil || !d.IsDir() { return nil //nolint:nilerr // tolerate unreadable subtrees } + if path != root && hiddenName(d.Name()) { + return fs.SkipDir + } if aerr := fsw.Add(path); aerr != nil { w.logger.Warn("library watcher: add watch failed", "path", path, "err", aerr) } @@ -249,9 +256,18 @@ func (w *Watcher) addRecursive(fsw *fsnotify.Watcher, root string) { func (w *Watcher) enqueueDirAudio(dir string, pending map[string]struct{}) bool { added := false _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { - if err != nil || d.IsDir() { + if err != nil { return nil //nolint:nilerr // tolerate unreadable subtrees } + if path != dir && hiddenName(d.Name()) { + if d.IsDir() { + return fs.SkipDir + } + return nil + } + if d.IsDir() { + return nil + } if audioExtensions[strings.ToLower(filepath.Ext(path))] { pending[path] = struct{}{} added = true diff --git a/internal/lifecycle/lifecycle.go b/internal/lifecycle/lifecycle.go deleted file mode 100644 index 23102f4d..00000000 --- a/internal/lifecycle/lifecycle.go +++ /dev/null @@ -1,682 +0,0 @@ -// Package lifecycle looks after a download from the grab to its removal. -// -// - A download the client has failed is given up at once. -// - One nobody has shared, or still fetching its file list, after the -// stall setting is retried: the trackers asked again and the files -// re-read, three times a pass apart. Then it is given up. -// - Giving up removes the download with its files, holds the release back -// for a week, ends the grab and searches for the album again. There is -// no limit per album: what stops it churning is the hold on each release. -// - A running download the client no longer lists, for half an hour, ends -// and its album is searched again. The release is not held back: nothing -// was wrong with it. -// - An imported download seeds (its files were copied) until its share -// ratio reaches the setting or its days are up, then is removed. -// -// Every condition and every act goes in the intervention ledger, one open -// row per (client, download, condition), so the Activity tab can say what -// is wrong with a download and what was done. -package lifecycle - -import ( - "context" - "errors" - "fmt" - "log/slog" - "strings" - "sync" - "time" - - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/indexer" -) - -// Conditions, matching download_interventions_trigger_check. -const ( - NoPeers = "no_peers" - NoMetadata = "no_metadata" - ClientError = "client_error" - ClientUnreachable = "client_unreachable" - Gone = "gone" - NotRemoved = "not_removed" -) - -// Acts, matching download_interventions_action_check. -const ( - actRetried = "retried" - actGivenUp = "given_up" - actRemoved = "removed" -) - -// End reasons a grab is given with, matching grabs_end_reason_check. -const ( - EndStalled = "stalled" - EndFailed = "failed" - EndAbandoned = "abandoned" - EndGone = "gone" -) - -const ( - // interval: three retries a pass apart is half an hour of asking before - // a stalled download is given up. - interval = 10 * time.Minute - passTimeout = 5 * time.Minute - // Retries is how many times one stuck download is nudged first. - Retries = 3 - // StallBlock is how long a release given up on is held back. - StallBlock = 7 * 24 * time.Hour - // goneAfter: a client restarting can answer without a download for a - // while; half an hour missing is gone. - goneAfter = 30 * time.Minute - // goneWindow: a release gone twice within it is held back. - goneWindow = 7 * 24 * time.Hour -) - -// running are the import states of a grab still downloading: the lifecycle -// acts only on these, so an import under way is never pulled from under. -var running = []string{"", "downloading", "waiting"} - -// Settings are the limits, from acquisition_settings. -type Settings struct { - // SeedRatio is the share ratio an imported download seeds to; 0 removes - // it once imported. - SeedRatio float64 - // SeedTime is the longest it seeds; 0 is no limit. - SeedTime time.Duration - // Patience is how long a download may sit with nobody sharing it before - // it is retried, then given up; 0 never gives up for that. - Patience time.Duration -} - -// Defaults are FL's rulings. -var Defaults = Settings{SeedRatio: 2, SeedTime: 14 * 24 * time.Hour, Patience: 6 * time.Hour} - -// Service runs the lifecycle passes. -type Service struct { - pool *pgxpool.Pool - // ClientFor builds a download client by its code. Defaults to - // acquire.DownloadClientFor. - ClientFor func(ctx context.Context, code string) (downloader.Driver, error) - // Now is the clock; nil is time.Now. - Now func() time.Time - logger *slog.Logger - mu sync.Mutex // one pass at a time -} - -// New returns a Service. -func New(pool *pgxpool.Pool, logger *slog.Logger) *Service { - if logger == nil { - logger = slog.Default() - } - return &Service{pool: pool, logger: logger, - ClientFor: func(ctx context.Context, code string) (downloader.Driver, error) { - return acquire.DownloadClientFor(ctx, pool, code) - }} -} - -func (s *Service) now() time.Time { - if s.Now != nil { - return s.Now() - } - return time.Now() -} - -// Run passes a minute after start, then every ten minutes, until ctx ends. -// Each pass is bounded, so a client that never answers costs one pass. -func (s *Service) Run(ctx context.Context) { - first := time.NewTimer(time.Minute) - defer first.Stop() - select { - case <-ctx.Done(): - return - case <-first.C: - } - t := time.NewTicker(interval) - defer t.Stop() - for { - rep := s.Pass(ctx) - if rep.Retried+rep.GivenUp+rep.Gone+rep.Released+rep.Removed > 0 || rep.Error != "" { - s.logger.Info("lifecycle: pass", "retried", rep.Retried, "given_up", rep.GivenUp, "gone", rep.Gone, - "released", rep.Released, "removed", rep.Removed, "raised", rep.Raised, "settled", rep.Settled, - "error", rep.Error) - } - select { - case <-ctx.Done(): - return - case <-t.C: - } - } -} - -// Report is one pass. -type Report struct { - // Raised and Settled count ledger writes; the rest count acts. - Raised, Settled int - Retried, GivenUp, Gone, Released, Removed int - Error string -} - -// Pass looks at every running download, every seeding one and every one -// left behind, once. -func (s *Service) Pass(ctx context.Context) Report { - s.mu.Lock() - defer s.mu.Unlock() - ctx, cancel := context.WithTimeout(ctx, passTimeout) - defer cancel() - var rep Report - q := dbq.New(s.pool) - set := s.settings(ctx, q) - - if _, err := q.DeleteExpiredBlocks(ctx); err != nil { - s.logger.Warn("lifecycle: lift expired holds", "err", err) - } - if n, err := q.SettleEndedGrabs(ctx); err == nil { - rep.Settled += int(n) - } - live, err := q.ListLiveGrabs(ctx) - if err != nil { - rep.Error = err.Error() - return rep - } - seeds, err := q.ListSeedingGrabs(ctx) - if err != nil { - rep.Error = err.Error() - return rep - } - left, err := q.ListLeftovers(ctx) - if err != nil { - rep.Error = err.Error() - return rep - } - - work := map[string]*clientWork{} - var order []string - of := func(code string) *clientWork { - if w, ok := work[code]; ok { - return w - } - order = append(order, code) - work[code] = &clientWork{} - return work[code] - } - for _, g := range live { - if g.InfoHash != "" { - of(g.Client).live = append(of(g.Client).live, g) - } - } - for _, g := range seeds { - if g.InfoHash != "" { - of(g.Client).seeds = append(of(g.Client).seeds, g) - } - } - for _, l := range left { - of(l.Client).left = append(of(l.Client).left, l) - } - for _, code := range order { - if ctx.Err() != nil { - break - } - s.passClient(ctx, q, code, work[code], set, &rep) - } - return rep -} - -type clientWork struct { - live []dbq.ListLiveGrabsRow - seeds []dbq.ListSeedingGrabsRow - left []dbq.DownloadIntervention -} - -func (s *Service) settings(ctx context.Context, q *dbq.Queries) Settings { - row, err := q.GetAcquisitionSettings(ctx) - if err != nil { - // A blip keeps the defaults rather than stopping the pass. - return Defaults - } - return Settings{ - SeedRatio: float64(row.SeedRatio), - SeedTime: time.Duration(row.SeedDays) * 24 * time.Hour, - Patience: time.Duration(row.StallHours) * time.Hour, - } -} - -func (s *Service) passClient(ctx context.Context, q *dbq.Queries, code string, w *clientWork, set Settings, rep *Report) { - d, err := s.ClientFor(ctx, code) - if err != nil { - s.raise(ctx, q, code, "", pgtype.UUID{}, "", ClientUnreachable, firstLine(err.Error()), rep) - return - } - var hashes []string - for _, g := range w.live { - hashes = append(hashes, g.InfoHash) - } - for _, g := range w.seeds { - hashes = append(hashes, g.InfoHash) - } - for _, l := range w.left { - hashes = append(hashes, l.InfoHash) - } - ts, err := d.Torrents(ctx, hashes...) - if err != nil { - // Nothing about any one download is observed through a client that - // cannot answer. - s.raise(ctx, q, code, "", pgtype.UUID{}, "", ClientUnreachable, firstLine(err.Error()), rep) - return - } - for _, t := range ts { - if t.EngineDown != "" { - s.raise(ctx, q, code, "", pgtype.UUID{}, "", ClientUnreachable, t.EngineDown, rep) - return - } - } - s.settle(ctx, q, code, "", ClientUnreachable, rep) - - byHash := make(map[string]downloader.Torrent, len(ts)) - for _, t := range ts { - byHash[indexer.NormalizeHash(t.Hash)] = t - } - // ABSENCE IS ONLY A MEASUREMENT FROM A CLIENT THAT LISTS SOMETHING. An - // engine switched off, or a store that would not read, answers with an - // empty list; then nothing is concluded from what is missing. - listed := len(ts) > 0 - if !listed { - all, err := d.Torrents(ctx) - listed = err == nil && len(all) > 0 - } - - for _, l := range w.left { - t, ok := byHash[indexer.NormalizeHash(l.InfoHash)] - s.removeAgain(ctx, q, d, l, t, ok, listed, rep) - } - for _, g := range w.live { - t, ok := byHash[indexer.NormalizeHash(g.InfoHash)] - s.judge(ctx, q, d, g, t, ok, listed, set, rep) - } - for _, g := range w.seeds { - t, ok := byHash[indexer.NormalizeHash(g.InfoHash)] - s.seed(ctx, q, d, g, t, ok, set, rep) - } -} - -// judge decides what, if anything, is wrong with one running download, and -// answers each condition either way: raised when true, settled when not. -func (s *Service) judge(ctx context.Context, q *dbq.Queries, d downloader.Driver, g dbq.ListLiveGrabsRow, - t downloader.Torrent, ok, listed bool, set Settings, rep *Report) { - if !isRunning(g.ImportState) { - return // the importer's, or a person's - } - if !ok { - if !listed { - return - } - row, raised := s.raise(ctx, q, g.Client, g.InfoHash, g.ID, g.Name, Gone, - "The download client no longer lists it.", rep) - if raised && s.now().Sub(row.FirstSeen.Time) >= goneAfter { - s.endGone(ctx, q, g, rep) - } - return - } - s.settle(ctx, q, g.Client, g.InfoHash, Gone, rep) - - if t.Done() { - // Finished: whatever was wrong while it downloaded is over, and the - // import is the importer's. - for _, c := range []string{ClientError, NoMetadata, NoPeers} { - s.settle(ctx, q, g.Client, g.InfoHash, c, rep) - } - return - } - - // The client's own verdict, given up on at once: it has already made - // the decision a retry would ask about. - if t.Failed() { - why := t.FailReason - if why == "" { - why = fmt.Sprintf("the download client reports it %q", t.State) - } - if _, raised := s.raise(ctx, q, g.Client, g.InfoHash, g.ID, g.Name, ClientError, why, rep); raised { - s.giveUp(ctx, q, d, g, ClientError, EndFailed, why, rep) - } - return - } - s.settle(ctx, q, g.Client, g.InfoHash, ClientError, rep) - - // Below here the stall setting applies, measured from the grab. With it - // off nothing is raised and what was raised clears. - age := s.now().Sub(g.GrabbedAt.Time) - patient := set.Patience > 0 && age > set.Patience - - if patient && t.Fetching() { - row, raised := s.raise(ctx, q, g.Client, g.InfoHash, g.ID, g.Name, NoMetadata, - fmt.Sprintf("Still fetching its file list after %s.", span(age)), rep) - if raised { - s.ladder(ctx, q, d, g, NoMetadata, row.Remediations, age, rep) - } - } else { - s.settle(ctx, q, g.Client, g.InfoHash, NoMetadata, rep) - } - // Not while fetching: a torrent with no file list has no swarm to be - // alone in. - if patient && !t.Fetching() && t.Alone() { - row, raised := s.raise(ctx, q, g.Client, g.InfoHash, g.ID, g.Name, NoPeers, - fmt.Sprintf("Nobody has shared it in %s; %.0f%% downloaded.", span(age), t.Progress*100), rep) - if raised { - s.ladder(ctx, q, d, g, NoPeers, row.Remediations, age, rep) - } - } else { - s.settle(ctx, q, g.Client, g.InfoHash, NoPeers, rep) - } -} - -// ladder retries a stuck download until the retries are spent, then gives -// it up. The rung is the ledger row's, so a restart hands out no more. -func (s *Service) ladder(ctx context.Context, q *dbq.Queries, d downloader.Driver, g dbq.ListLiveGrabsRow, - trigger string, done int32, age time.Duration, rep *Report) { - if int(done) < Retries { - // Counted before it happens: a retry that happened and was not - // counted is a bound that never binds. - n, err := q.CountRemediation(ctx, dbq.CountRemediationParams{ - Client: g.Client, InfoHash: g.InfoHash, Trigger: trigger, Action: actRetried}) - if err != nil { - return - } - // Exchange schedules its own announces and has no recheck: for it a - // retry is the time between passes, and the ladder still climbs. - if err := d.Reannounce(ctx, g.InfoHash); err != nil && !errors.Is(err, downloader.ErrUnsupported) { - s.logger.Warn("lifecycle: reannounce", "grab", g.Name, "err", err) - } - if err := d.Recheck(ctx, g.InfoHash); err != nil && !errors.Is(err, downloader.ErrUnsupported) { - s.logger.Warn("lifecycle: recheck", "grab", g.Name, "err", err) - } - s.logger.Info("lifecycle: retried a stalled download", "grab", g.Name, "trigger", trigger, "attempt", n) - rep.Retried++ - return - } - why := fmt.Sprintf("taken %s ago and never finished: %s", span(age), reasonFor(trigger)) - s.giveUp(ctx, q, d, g, trigger, EndStalled, why, rep) -} - -// giveUp ends the grab, holds the release back for StallBlock, removes the -// download with its files and searches for the album again. -func (s *Service) giveUp(ctx context.Context, q *dbq.Queries, d downloader.Driver, g dbq.ListLiveGrabsRow, - trigger, end, why string, rep *Report) { - until := s.now().Add(StallBlock) - detail := capital(why) + fmt.Sprintf(". Held back until %s; the album is searched for again.", until.Format("2 Jan")) - // The update is the lock: an import that claimed the download meanwhile - // keeps it. - if _, err := q.GiveUpGrab(ctx, dbq.GiveUpGrabParams{ID: g.ID, EndReason: end, EndDetail: detail, States: running}); err != nil { - return - } - // Held back before it is removed: if the pass dies between the two, the - // release is still not taken again. - if err := acquire.NewMemory(s.pool).Block(ctx, dbq.BlockReleaseParams{ - InfoHash: g.InfoHash, Name: g.Name, Reason: acquire.BlockStalled, Detail: capital(why) + ".", - WantID: g.WantID, ExpiresAt: pgtype.Timestamptz{Time: until, Valid: true}, - }); err != nil { - s.logger.Warn("lifecycle: hold the release back", "grab", g.Name, "err", err) - } - removed := s.remove(ctx, q, d, g.Client, g.InfoHash, g.ID, g.Name, rep) - if g.WantID.Valid { - if err := q.SearchWantAgain(ctx, g.WantID); err != nil { - s.logger.Warn("lifecycle: search again", "grab", g.Name, "err", err) - } - } - if _, err := q.CountRemediation(ctx, dbq.CountRemediationParams{ - Client: g.Client, InfoHash: g.InfoHash, Trigger: trigger, Action: actGivenUp}); err != nil { - s.logger.Warn("lifecycle: stamp the ledger", "grab", g.Name, "err", err) - } - if removed { - if n, err := q.SettleInterventionsFor(ctx, dbq.SettleInterventionsForParams{ - Client: g.Client, InfoHash: g.InfoHash}); err == nil { - rep.Settled += int(n) - } - } - s.logger.Info("lifecycle: gave up on a download", "grab", g.Name, "trigger", trigger, "why", why) - rep.GivenUp++ -} - -// endGone ends a grab whose download left the client, and searches again. -// The first time, the release is not held back: nothing was found wrong with -// it. A release that leaves its client again within goneWindow is held back for -// acquire.GoneBlock: whatever keeps the client from listing it would otherwise -// have it taken again on every pass. -func (s *Service) endGone(ctx context.Context, q *dbq.Queries, g dbq.ListLiveGrabsRow, rep *Report) { - detail := "The download client no longer lists it: removed outside Minstrel. The album is searched for again." - before, err := q.CountGoneGrabs(ctx, dbq.CountGoneGrabsParams{ - InfoHash: g.InfoHash, Since: pgtype.Timestamptz{Time: s.now().Add(-goneWindow), Valid: true}}) - if err != nil { - s.logger.Warn("lifecycle: count earlier gone grabs", "grab", g.Name, "err", err) - } - again := before > 0 - until := s.now().Add(acquire.GoneBlock) - if again { - detail = fmt.Sprintf("The download client no longer lists it, again: held back until %s; the album is searched for again.", - until.Format("2 Jan 15:04")) - } - if _, err := q.GiveUpGrab(ctx, dbq.GiveUpGrabParams{ID: g.ID, EndReason: EndGone, EndDetail: detail, States: running}); err != nil { - return - } - if again { - if err := acquire.NewMemory(s.pool).Block(ctx, dbq.BlockReleaseParams{ - InfoHash: g.InfoHash, Name: g.Name, Reason: acquire.BlockGone, - Detail: "It left its download client twice without finishing.", - WantID: g.WantID, ExpiresAt: pgtype.Timestamptz{Time: until, Valid: true}, - }); err != nil { - s.logger.Warn("lifecycle: hold the release back", "grab", g.Name, "err", err) - } - } - if g.WantID.Valid { - if err := q.SearchWantAgain(ctx, g.WantID); err != nil { - s.logger.Warn("lifecycle: search again", "grab", g.Name, "err", err) - } - } - if _, err := q.CountRemediation(ctx, dbq.CountRemediationParams{ - Client: g.Client, InfoHash: g.InfoHash, Trigger: Gone, Action: actGivenUp}); err != nil { - s.logger.Warn("lifecycle: stamp the ledger", "grab", g.Name, "err", err) - } - if n, err := q.SettleInterventionsFor(ctx, dbq.SettleInterventionsForParams{ - Client: g.Client, InfoHash: g.InfoHash}); err == nil { - rep.Settled += int(n) - } - s.logger.Info("lifecycle: a download left its client", "grab", g.Name) - rep.Gone++ -} - -// seed removes an imported download once it has shared enough. -// -// Absence is not a verdict: a restarting client answers with a partial list. -// A seeding download missing from it is left until its time is up, then -// recorded as released; there is nothing to delete. -func (s *Service) seed(ctx context.Context, q *dbq.Queries, d downloader.Driver, g dbq.ListSeedingGrabsRow, - t downloader.Torrent, ok bool, set Settings, rep *Report) { - overdue := set.SeedTime > 0 && g.ImportedAt.Valid && s.now().Sub(g.ImportedAt.Time) >= set.SeedTime - if !ok { - if overdue { - s.release(ctx, q, g.ID, rep) - } - return - } - if err := q.SetGrabRatio(ctx, dbq.SetGrabRatioParams{ID: g.ID, Ratio: float32(t.Ratio)}); err != nil { - s.logger.Warn("lifecycle: record the ratio", "grab", g.Name, "err", err) - } - if t.Ratio < set.SeedRatio && !overdue { - return - } - s.remove(ctx, q, d, g.Client, g.InfoHash, g.ID, g.Name, rep) - s.logger.Info("lifecycle: seeded enough, removed the download", "grab", g.Name, "ratio", t.Ratio, "overdue", overdue) - s.release(ctx, q, g.ID, rep) -} - -func (s *Service) release(ctx context.Context, q *dbq.Queries, id pgtype.UUID, rep *Report) { - if err := q.ReleaseSeed(ctx, id); err != nil { - s.logger.Warn("lifecycle: record the seeding ended", "err", err) - return - } - rep.Released++ -} - -// remove deletes a download and its files. A client that refuses leaves an -// open not_removed row, which every pass tries again. -func (s *Service) remove(ctx context.Context, q *dbq.Queries, d downloader.Driver, code, hash string, - grab pgtype.UUID, name string, rep *Report) bool { - if err := d.Delete(ctx, true, hash); err != nil { - s.logger.Warn("lifecycle: remove the download", "grab", name, "err", err) - s.raise(ctx, q, code, hash, grab, name, NotRemoved, notRemoved(err), rep) - return false - } - return true -} - -// removeAgain asks the client once more to remove a download left behind, -// unless it has been taken again since. -func (s *Service) removeAgain(ctx context.Context, q *dbq.Queries, d downloader.Driver, l dbq.DownloadIntervention, - t downloader.Torrent, ok, listed bool, rep *Report) { - if !ok { - if listed { - s.settle(ctx, q, l.Client, l.InfoHash, NotRemoved, rep) - } - return - } - live, err := q.LiveGrabOnHash(ctx, l.InfoHash) - if err != nil { - return - } - if live { - s.settle(ctx, q, l.Client, l.InfoHash, NotRemoved, rep) - return - } - if err := d.Delete(ctx, true, l.InfoHash); err != nil { - s.raise(ctx, q, l.Client, l.InfoHash, l.GrabID, t.Name, NotRemoved, notRemoved(err), rep) - return - } - if _, err := q.CountRemediation(ctx, dbq.CountRemediationParams{ - Client: l.Client, InfoHash: l.InfoHash, Trigger: NotRemoved, Action: actRemoved}); err != nil { - s.logger.Warn("lifecycle: stamp the ledger", "hash", l.InfoHash, "err", err) - } - s.logger.Info("lifecycle: removed a download left behind", "name", l.Name) - rep.Removed++ -} - -// raise records a condition or agrees with the open row that says it. The -// bool is false when the write failed: then nothing is acted on, since -// without the row's count there is no bound. -func (s *Service) raise(ctx context.Context, q *dbq.Queries, code, hash string, grab pgtype.UUID, name, trigger, - detail string, rep *Report) (dbq.DownloadIntervention, bool) { - row, err := q.RaiseIntervention(ctx, dbq.RaiseInterventionParams{ - Client: code, InfoHash: hash, GrabID: grab, Name: name, Trigger: trigger, Detail: detail}) - if err != nil { - s.logger.Warn("lifecycle: record", "client", code, "hash", hash, "trigger", trigger, "err", err) - return row, false - } - rep.Raised++ - return row, true -} - -func (s *Service) settle(ctx context.Context, q *dbq.Queries, code, hash, trigger string, rep *Report) { - n, err := q.SettleIntervention(ctx, dbq.SettleInterventionParams{Client: code, InfoHash: hash, Trigger: trigger}) - if err != nil { - s.logger.Warn("lifecycle: settle", "client", code, "hash", hash, "trigger", trigger, "err", err) - return - } - rep.Settled += int(n) -} - -// ErrNotAbandonable: the download is not running; an import, or a person's -// decision on one, has it. -var ErrNotAbandonable = errors.New("lifecycle: that download is not running") - -// Abandon is a person giving up on a running download: the release is set -// aside for good (their word about it), the download removed with its files, -// and the album searched for again. -func (s *Service) Abandon(ctx context.Context, grabID, by pgtype.UUID) (dbq.Grab, error) { - q := dbq.New(s.pool) - g, err := q.GetGrab(ctx, grabID) - if err != nil { - return dbq.Grab{}, err - } - if g.EndedAt.Valid || !isRunning(g.ImportState) { - return dbq.Grab{}, ErrNotAbandonable - } - const why = "Given up by you before it finished. The album is searched for again." - ended, err := q.GiveUpGrab(ctx, dbq.GiveUpGrabParams{ID: g.ID, EndReason: EndAbandoned, EndDetail: why, States: running}) - if err != nil { - return dbq.Grab{}, ErrNotAbandonable - } - if g.InfoHash != "" { - if err := acquire.NewMemory(s.pool).Block(ctx, dbq.BlockReleaseParams{ - InfoHash: g.InfoHash, Name: g.Name, Reason: acquire.BlockOperator, Detail: "Given up by you before it finished.", - WantID: g.WantID, BlockedBy: by, - }); err != nil { - s.logger.Warn("lifecycle: set the release aside", "grab", g.Name, "err", err) - } - var rep Report - if d, err := s.ClientFor(ctx, g.Client); err != nil { - s.raise(ctx, q, g.Client, g.InfoHash, g.ID, g.Name, NotRemoved, notRemoved(err), &rep) - } else if s.remove(ctx, q, d, g.Client, g.InfoHash, g.ID, g.Name, &rep) { - _, _ = q.SettleInterventionsFor(ctx, dbq.SettleInterventionsForParams{Client: g.Client, InfoHash: g.InfoHash}) - } - } - if g.WantID.Valid { - if err := q.SearchWantAgain(ctx, g.WantID); err != nil { - s.logger.Warn("lifecycle: search again", "grab", g.Name, "err", err) - } - } - return ended, nil -} - -func isRunning(state string) bool { - for _, r := range running { - if state == r { - return true - } - } - return false -} - -// reasonFor is a condition in a person's words. -func reasonFor(trigger string) string { - switch trigger { - case NoPeers: - return "nobody was sharing it" - case NoMetadata: - return "its file list never arrived" - case ClientError: - return "the download client gave up on it" - } - return "it stalled" -} - -func notRemoved(err error) string { - return "Given up on, but the download client would not remove it: " + firstLine(err.Error()) + - ". Minstrel asks again every ten minutes." -} - -// span is a duration as a person says it. -func span(d time.Duration) string { - switch { - case d < 2*time.Hour: - return fmt.Sprintf("%d minutes", int(d.Minutes())) - case d < 48*time.Hour: - return fmt.Sprintf("%d hours", int(d.Hours())) - } - return fmt.Sprintf("%d days", int(d.Hours()/24)) -} - -func capital(s string) string { - if s == "" { - return s - } - return strings.ToUpper(s[:1]) + s[1:] -} - -func firstLine(s string) string { - if i := strings.IndexByte(s, '\n'); i >= 0 { - return strings.TrimSpace(s[:i]) - } - return strings.TrimSpace(s) -} diff --git a/internal/lifecycle/lifecycle_test.go b/internal/lifecycle/lifecycle_test.go deleted file mode 100644 index b5e9277b..00000000 --- a/internal/lifecycle/lifecycle_test.go +++ /dev/null @@ -1,488 +0,0 @@ -package lifecycle - -import ( - "context" - "errors" - "io" - "log/slog" - "os" - "strings" - "testing" - "time" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/acquire" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" - "git.fabledsword.com/bvandeusen/minstrel/internal/downloader" - "git.fabledsword.com/bvandeusen/minstrel/internal/wanted" -) - -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - -const ( - hash = "0123456789abcdef0123456789abcdef01234567" - other = "fedcba9876543210fedcba9876543210fedcba98" -) - -// fakeClient lists the torrents it holds and records what it is asked. -type fakeClient struct { - downloader.Driver - held map[string]downloader.Torrent - err error - deleteErr error - deleted []string - reannounce int - recheck int -} - -func (c *fakeClient) Torrents(_ context.Context, hashes ...string) ([]downloader.Torrent, error) { - if c.err != nil { - return nil, c.err - } - var out []downloader.Torrent - if len(hashes) == 0 { - for _, t := range c.held { - out = append(out, t) - } - return out, nil - } - for _, h := range hashes { - if t, ok := c.held[h]; ok { - out = append(out, t) - } - } - return out, nil -} - -func (c *fakeClient) Delete(_ context.Context, _ bool, hashes ...string) error { - if c.deleteErr != nil { - return c.deleteErr - } - c.deleted = append(c.deleted, hashes...) - for _, h := range hashes { - delete(c.held, h) - } - return nil -} - -func (c *fakeClient) Reannounce(context.Context, ...string) error { c.reannounce++; return nil } -func (c *fakeClient) Recheck(context.Context, ...string) error { c.recheck++; return nil } - -type stack struct { - q *dbq.Queries - s *Service - client *fakeClient - want dbq.Want - grab dbq.Grab - clock time.Time -} - -// newStack wants RAM and has a grab of it running in a fake client holding -// t under hash. -func newStack(t *testing.T, tor downloader.Torrent) *stack { - t.Helper() - ctx := context.Background() - pool := newPool(t) - q := dbq.New(pool) - w, err := wanted.WantWith(ctx, q, wanted.WantParams{GroupMBID: "rg-ram", ArtistMBID: "mb-dp", ArtistName: "Daft Punk", - Title: "Random Access Memories", PrimaryType: "Album", FirstReleaseDate: "2013-05-17", Reason: wanted.ReasonRequest}) - if err != nil { - t.Fatal(err) - } - g, err := acquire.NewMemory(pool).Grabbed(ctx, dbq.InsertGrabParams{WantID: w.ID, InfoHash: hash, - Name: "Daft Punk - RAM [FLAC]", Key: hash, Client: "qbittorrent", SavePath: "/downloads", Origin: acquire.OriginSchedule}, - pgtype.UUID{}, "") - if err != nil { - t.Fatal(err) - } - if err := q.MarkWantSearched(ctx, w.ID); err != nil { - t.Fatal(err) - } - tor.Hash = hash - st := &stack{q: q, client: &fakeClient{held: map[string]downloader.Torrent{hash: tor}}, want: w, grab: g, - clock: time.Now()} - st.s = New(pool, slog.New(slog.NewTextHandler(io.Discard, nil))) - st.s.ClientFor = func(context.Context, string) (downloader.Driver, error) { return st.client, nil } - st.s.Now = func() time.Time { return st.clock } - return st -} - -func (st *stack) grabNow(t *testing.T) dbq.Grab { - t.Helper() - g, err := st.q.GetGrab(context.Background(), st.grab.ID) - if err != nil { - t.Fatal(err) - } - return g -} - -func (st *stack) searchedAgain(t *testing.T) bool { - t.Helper() - w, err := st.q.GetWantByReleaseGroup(context.Background(), "rg-ram") - if err != nil { - t.Fatal(err) - } - return !w.SearchedAt.Valid -} - -func (st *stack) ledger(t *testing.T) []dbq.DownloadIntervention { - t.Helper() - rows, err := st.s.pool.Query(context.Background(), `SELECT * FROM download_interventions ORDER BY first_seen, id`) - if err != nil { - t.Fatal(err) - } - out, err := pgx.CollectRows(rows, pgx.RowToStructByPos[dbq.DownloadIntervention]) - if err != nil { - t.Fatal(err) - } - return out -} - -func TestLifecycle_AFailedDownloadIsGivenUpAtOnce_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.4, State: "error", - FailReason: "No space left on device"}) - rep := st.s.Pass(context.Background()) - if rep.GivenUp != 1 { - t.Fatalf("pass = %+v", rep) - } - g := st.grabNow(t) - if !g.EndedAt.Valid || g.EndReason != EndFailed { - t.Fatalf("grab ended=%v reason=%q", g.EndedAt.Valid, g.EndReason) - } - if len(st.client.deleted) != 1 || !st.searchedAgain(t) { - t.Errorf("deleted %v, searched again %v", st.client.deleted, st.searchedAgain(t)) - } - blocks, err := st.q.ListReleaseBlocks(context.Background()) - if err != nil || len(blocks) != 1 || blocks[0].Reason != acquire.BlockStalled || !blocks[0].ExpiresAt.Valid { - t.Fatalf("blocks = %+v %v", blocks, err) - } - if d := blocks[0].ExpiresAt.Time.Sub(st.clock); d < StallBlock-time.Minute || d > StallBlock+time.Minute { - t.Errorf("held back for %s", d) - } - rows := st.ledger(t) - if len(rows) != 1 || rows[0].Trigger != ClientError || rows[0].Action != actGivenUp || rows[0].Outcome != "resolved" || - rows[0].Detail != "No space left on device" { - t.Errorf("ledger = %+v", rows) - } -} - -func TestLifecycle_ADownloadNobodySharesIsRetriedThenGivenUp_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.3, State: "stalledDL"}) - ctx := context.Background() - - // Within the stall setting: nothing is wrong yet. - if rep := st.s.Pass(ctx); rep.Retried+rep.GivenUp != 0 || len(st.ledger(t)) != 0 { - t.Fatalf("a young download was judged: %+v", rep) - } - - st.clock = st.clock.Add(7 * time.Hour) - for i := 1; i <= Retries; i++ { - if rep := st.s.Pass(ctx); rep.Retried != 1 || rep.GivenUp != 0 { - t.Fatalf("pass %d = %+v", i, rep) - } - } - if st.client.reannounce != Retries || st.client.recheck != Retries { - t.Errorf("reannounced %d, rechecked %d", st.client.reannounce, st.client.recheck) - } - if st.grabNow(t).EndedAt.Valid { - t.Fatal("given up before the retries ran out") - } - if rep := st.s.Pass(ctx); rep.GivenUp != 1 { - t.Fatalf("last pass = %+v", rep) - } - g := st.grabNow(t) - if g.EndReason != EndStalled || len(st.client.deleted) != 1 || !st.searchedAgain(t) { - t.Errorf("grab %q: %s; deleted %v", g.EndReason, g.EndDetail, st.client.deleted) - } - rows := st.ledger(t) - if len(rows) != 1 || rows[0].Trigger != NoPeers || rows[0].Remediations != Retries+1 || rows[0].Outcome != "resolved" { - t.Errorf("ledger = %+v", rows) - } -} - -func TestLifecycle_AStalledDownloadThatRecoversIsSettled_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.3, State: "stalledDL"}) - ctx := context.Background() - st.clock = st.clock.Add(7 * time.Hour) - st.s.Pass(ctx) - t2 := st.client.held[hash] - t2.NumSeeds = 3 - st.client.held[hash] = t2 - st.s.Pass(ctx) - rows := st.ledger(t) - if len(rows) != 1 || rows[0].Outcome != "resolved" || rows[0].Action != actRetried { - t.Fatalf("ledger = %+v", rows) - } - if st.grabNow(t).EndedAt.Valid { - t.Error("a download that found peers was given up") - } -} - -func TestLifecycle_TheStallSettingOffNeverGivesUp_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.3, State: "stalledDL"}) - ctx := context.Background() - if _, err := st.s.pool.Exec(ctx, `UPDATE acquisition_settings SET stall_hours = 0`); err != nil { - t.Fatal(err) - } - st.clock = st.clock.Add(30 * 24 * time.Hour) - for range Retries + 2 { - if rep := st.s.Pass(ctx); rep.Retried+rep.GivenUp != 0 { - t.Fatalf("pass = %+v", rep) - } - } -} - -func TestLifecycle_ADownloadGoneFromTheClientEndsAfterHalfAnHour_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.3, State: "downloading", NumSeeds: 4}) - ctx := context.Background() - delete(st.client.held, hash) - st.client.held[other] = downloader.Torrent{Hash: other, Name: "Someone else's", Progress: 1, State: "uploading"} - - if rep := st.s.Pass(ctx); rep.Gone != 0 { - t.Fatalf("ended at first sight: %+v", rep) - } - st.clock = st.clock.Add(31 * time.Minute) - if rep := st.s.Pass(ctx); rep.Gone != 1 { - t.Fatalf("pass = %+v", rep) - } - g := st.grabNow(t) - if g.EndReason != EndGone || !st.searchedAgain(t) { - t.Errorf("grab %q, searched again %v", g.EndReason, st.searchedAgain(t)) - } - if blocks, _ := st.q.ListReleaseBlocks(ctx); len(blocks) != 0 { - t.Errorf("a release nothing was wrong with was held back: %+v", blocks) - } -} - -// A release that leaves its client a second time is held back, whatever the -// cause, so it is not taken again on every pass. -func TestLifecycle_AReleaseGoneTwiceIsHeldBack_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.3, State: "downloading", NumSeeds: 4}) - ctx := context.Background() - delete(st.client.held, hash) - st.client.held[other] = downloader.Torrent{Hash: other, Name: "Someone else's", Progress: 1, State: "uploading"} - - st.s.Pass(ctx) - st.clock = st.clock.Add(31 * time.Minute) - if rep := st.s.Pass(ctx); rep.Gone != 1 { - t.Fatalf("first gone: %+v", rep) - } - if blocks, _ := st.q.ListReleaseBlocks(ctx); len(blocks) != 0 { - t.Fatalf("held back after one gone: %+v", blocks) - } - - again, err := acquire.NewMemory(st.s.pool).Grabbed(ctx, dbq.InsertGrabParams{WantID: st.want.ID, InfoHash: hash, - Name: "Daft Punk - RAM [FLAC]", Key: hash, Client: "qbittorrent", SavePath: "/downloads", Origin: acquire.OriginSchedule}, - pgtype.UUID{}, "") - if err != nil { - t.Fatal(err) - } - // first_seen is the database's clock and the test's runs ahead of it, so - // the second grab may end on either pass; count both. - gone := st.s.Pass(ctx).Gone - st.clock = st.clock.Add(31 * time.Minute) - if gone += st.s.Pass(ctx).Gone; gone != 1 { - t.Fatalf("second grab ended gone %d times, want 1", gone) - } - blocks, err := st.q.ListReleaseBlocks(ctx) - if err != nil { - t.Fatal(err) - } - if len(blocks) != 1 || blocks[0].Reason != acquire.BlockGone || !blocks[0].ExpiresAt.Valid { - t.Fatalf("blocks = %+v, want one timed gone block", blocks) - } - g, err := st.q.GetGrab(ctx, again.ID) - if err != nil { - t.Fatal(err) - } - if g.EndReason != EndGone || !strings.Contains(g.EndDetail, "held back until") { - t.Errorf("second grab %q: %s", g.EndReason, g.EndDetail) - } -} - -func TestLifecycle_AnEmptyListIsNotAMeasurement_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.3, State: "downloading"}) - ctx := context.Background() - delete(st.client.held, hash) - st.clock = st.clock.Add(24 * time.Hour) - for range 3 { - if rep := st.s.Pass(ctx); rep.Gone != 0 { - t.Fatalf("pass = %+v", rep) - } - } - if len(st.ledger(t)) != 0 || st.grabNow(t).EndedAt.Valid { - t.Error("a client listing nothing was taken to have lost the download") - } -} - -func TestLifecycle_AnUnreachableClientIsRecordedAndSettled_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.3, State: "stalledDL"}) - ctx := context.Background() - st.clock = st.clock.Add(7 * time.Hour) - st.client.err = errors.New("dial tcp: connection refused") - st.s.Pass(ctx) - down, err := st.q.ListClientsDown(ctx) - if err != nil || len(down) != 1 || down[0].Client != "qbittorrent" { - t.Fatalf("clients down = %+v %v", down, err) - } - if st.client.reannounce != 0 { - t.Error("a download was judged through a client that did not answer") - } - st.client.err = nil - st.s.Pass(ctx) - if down, _ := st.q.ListClientsDown(ctx); len(down) != 0 { - t.Errorf("still down: %+v", down) - } -} - -func TestLifecycle_AnImportedDownloadSeedsThenIsRemoved_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 1, State: "uploading", Ratio: 0.8}) - ctx := context.Background() - if _, err := st.q.RecordImport(ctx, dbq.RecordImportParams{ID: st.grab.ID, ImportState: "imported", - ImportReason: "Imported.", ImportDetail: []byte("{}"), ImportedFiles: 3, EndReason: "imported"}); err != nil { - t.Fatal(err) - } - if !st.grabNow(t).Seeding { - t.Fatal("an import did not leave its download seeding") - } - if rep := st.s.Pass(ctx); rep.Released != 0 || len(st.client.deleted) != 0 { - t.Fatalf("removed before the ratio: %+v", rep) - } - if g := st.grabNow(t); g.Ratio < 0.79 || g.Ratio > 0.81 { - t.Errorf("ratio recorded %v", g.Ratio) - } - tor := st.client.held[hash] - tor.Ratio = 2.1 - st.client.held[hash] = tor - if rep := st.s.Pass(ctx); rep.Released != 1 || len(st.client.deleted) != 1 { - t.Fatalf("pass = %+v, deleted %v", rep, st.client.deleted) - } - if !st.grabNow(t).SeedReleasedAt.Valid { - t.Error("the release was not recorded") - } -} - -func TestLifecycle_AnImportedDownloadIsRemovedWhenItsDaysAreUp_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 1, State: "uploading", Ratio: 0.1}) - ctx := context.Background() - if _, err := st.q.RecordImport(ctx, dbq.RecordImportParams{ID: st.grab.ID, ImportState: "imported", - ImportReason: "Imported.", ImportDetail: []byte("{}"), ImportedFiles: 3, EndReason: "imported"}); err != nil { - t.Fatal(err) - } - st.clock = st.clock.Add(15 * 24 * time.Hour) - if rep := st.s.Pass(ctx); rep.Released != 1 || len(st.client.deleted) != 1 { - t.Fatalf("pass = %+v", rep) - } -} - -func TestLifecycle_ADownloadTheClientWouldNotRemoveIsAskedAgain_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.4, State: "error"}) - ctx := context.Background() - st.client.deleteErr = errors.New("HTTP 500") - if rep := st.s.Pass(ctx); rep.GivenUp != 1 { - t.Fatalf("pass = %+v", rep) - } - if !st.grabNow(t).EndedAt.Valid { - t.Fatal("a refused removal held the grab") - } - open := 0 - for _, r := range st.ledger(t) { - if r.Trigger == NotRemoved && r.Outcome == "open" { - open++ - } - } - if open != 1 { - t.Fatalf("ledger = %+v", st.ledger(t)) - } - st.client.deleteErr = nil - if rep := st.s.Pass(ctx); rep.Removed != 1 || len(st.client.deleted) != 1 { - t.Fatalf("pass = %+v", rep) - } - for _, r := range st.ledger(t) { - if r.Outcome == "open" { - t.Errorf("still open: %+v", r) - } - } -} - -func TestLifecycle_APersonGivingUpSetsTheReleaseAsideForGood_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "Daft Punk - RAM [FLAC]", Progress: 0.4, State: "downloading"}) - ctx := context.Background() - if _, err := st.s.Abandon(ctx, st.grab.ID, pgtype.UUID{}); err != nil { - t.Fatal(err) - } - g := st.grabNow(t) - if g.EndReason != EndAbandoned || len(st.client.deleted) != 1 || !st.searchedAgain(t) { - t.Errorf("grab %q, deleted %v", g.EndReason, st.client.deleted) - } - blocks, _ := st.q.ListReleaseBlocks(ctx) - if len(blocks) != 1 || blocks[0].Reason != acquire.BlockOperator || blocks[0].ExpiresAt.Valid { - t.Errorf("blocks = %+v", blocks) - } - if _, err := st.s.Abandon(ctx, st.grab.ID, pgtype.UUID{}); !errors.Is(err, ErrNotAbandonable) { - t.Errorf("abandoned twice: %v", err) - } -} - -func TestLifecycle_AHoldExpiresButABlockForGoodIsNeverShortened_Integration(t *testing.T) { - st := newStack(t, downloader.Torrent{Name: "x", Progress: 0.4, State: "downloading"}) - ctx := context.Background() - mem := acquire.NewMemory(st.s.pool) - past := pgtype.Timestamptz{Time: time.Now().Add(-time.Hour), Valid: true} - if err := mem.Block(ctx, dbq.BlockReleaseParams{InfoHash: other, Name: "old", Reason: acquire.BlockStalled, ExpiresAt: past}); err != nil { - t.Fatal(err) - } - if blocks, _ := st.q.ListReleaseBlocks(ctx); len(blocks) != 0 { - t.Errorf("an expired hold still holds: %+v", blocks) - } - if n, err := st.q.DeleteExpiredBlocks(ctx); err != nil || n != 1 { - t.Errorf("lifted %d %v", n, err) - } - - if err := mem.Block(ctx, dbq.BlockReleaseParams{InfoHash: hash, Name: "x", Reason: acquire.BlockOperator}); err != nil { - t.Fatal(err) - } - soon := pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true} - if err := mem.Block(ctx, dbq.BlockReleaseParams{InfoHash: hash, Name: "x", Reason: acquire.BlockStalled, ExpiresAt: soon}); err != nil { - t.Fatal(err) - } - blocks, _ := st.q.ListReleaseBlocks(ctx) - if len(blocks) != 1 || blocks[0].Reason != acquire.BlockOperator || blocks[0].ExpiresAt.Valid { - t.Errorf("a block for good was shortened: %+v", blocks) - } -} - -func TestSpan(t *testing.T) { - for _, c := range []struct { - d time.Duration - want string - }{{45 * time.Minute, "45 minutes"}, {7 * time.Hour, "7 hours"}, {3 * 24 * time.Hour, "3 days"}} { - if got := span(c.d); got != c.want { - t.Errorf("span(%s) = %q, want %q", c.d, got, c.want) - } - } -} diff --git a/internal/lookups/lookups.go b/internal/lookups/lookups.go new file mode 100644 index 00000000..55b5ec0d --- /dev/null +++ b/internal/lookups/lookups.go @@ -0,0 +1,88 @@ +// Package lookups holds the admin's switches for the outside lookups that no +// metadata source setting covers: ListenBrainz's similar songs and artists, +// and MusicBrainz's album track lists for the duplicate resolver. Both are on +// unless an admin turns them off under Admin › Metadata sources. Turning one +// off stops the requests and keeps what was already fetched. +package lookups + +import ( + "context" + "errors" + "fmt" + "sync" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/Fabled-Sword/minstrel/internal/db/dbq" +) + +// Settings mirrors the lookup_settings row. +type Settings struct { + // ListenBrainzSimilarity lets the similarity worker ask ListenBrainz Labs + // which songs and artists are like the ones people play. + ListenBrainzSimilarity bool + // MusicBrainzTrackLists lets the duplicate resolver read an album's track + // list from MusicBrainz when it has never been read. + MusicBrainzTrackLists bool +} + +// Defaults mirrors the table's column defaults, so a database that can't be +// read behaves as a new install does. +var Defaults = Settings{ListenBrainzSimilarity: true, MusicBrainzTrackLists: true} + +// Service caches the settings and saves them. One instance is shared by the +// workers and the admin API, so a save reaches the workers at once. +type Service struct { + pool *pgxpool.Pool + + mu sync.RWMutex + cur Settings +} + +// New loads the settings once. It always returns a usable service, holding +// the defaults when the load fails; the error says so. +func New(ctx context.Context, pool *pgxpool.Pool) (*Service, error) { + s := &Service{pool: pool, cur: Defaults} + row, err := dbq.New(pool).GetLookupSettings(ctx) + if err != nil { + return s, fmt.Errorf("lookup settings: load: %w", err) + } + s.cur = fromRow(row) + return s, nil +} + +// Get returns the cached settings. A nil service answers with the defaults. +func (s *Service) Get() Settings { + if s == nil { + return Defaults + } + s.mu.RLock() + defer s.mu.RUnlock() + return s.cur +} + +// Set saves and re-caches. +func (s *Service) Set(ctx context.Context, in Settings) (Settings, error) { + if s == nil { + return Settings{}, errors.New("lookup settings: no settings service") + } + row, err := dbq.New(s.pool).UpdateLookupSettings(ctx, dbq.UpdateLookupSettingsParams{ + ListenbrainzSimilarity: in.ListenBrainzSimilarity, + MusicbrainzTrackLists: in.MusicBrainzTrackLists, + }) + if err != nil { + return Settings{}, fmt.Errorf("lookup settings: save: %w", err) + } + out := fromRow(row) + s.mu.Lock() + s.cur = out + s.mu.Unlock() + return out, nil +} + +func fromRow(row dbq.LookupSetting) Settings { + return Settings{ + ListenBrainzSimilarity: row.ListenbrainzSimilarity, + MusicBrainzTrackLists: row.MusicbrainzTrackLists, + } +} diff --git a/internal/lookups/lookups_test.go b/internal/lookups/lookups_test.go new file mode 100644 index 00000000..a3a122a6 --- /dev/null +++ b/internal/lookups/lookups_test.go @@ -0,0 +1,46 @@ +package lookups + +import ( + "context" + "testing" + + "github.com/Fabled-Sword/minstrel/internal/dbtest" +) + +// With no settings service, both lookups are on, as on a new install. +func TestGet_WithoutAServiceBothLookupsAreOn(t *testing.T) { + var s *Service + if got := s.Get(); got != Defaults || !got.ListenBrainzSimilarity || !got.MusicBrainzTrackLists { + t.Errorf("nil service = %+v, want both on", got) + } +} + +// A new install starts with both on; a save is cached for the workers and +// read back by a server started afterwards. +func TestSettings_StartOnAndKeepWhatIsSaved_Integration(t *testing.T) { + ctx := context.Background() + pool := dbtest.Pool(t) + + s, err := New(ctx, pool) + if err != nil { + t.Fatalf("load: %v", err) + } + if got := s.Get(); got != Defaults { + t.Fatalf("new install = %+v, want both on", got) + } + + off := Settings{ListenBrainzSimilarity: false, MusicBrainzTrackLists: true} + if _, err := s.Set(ctx, off); err != nil { + t.Fatalf("save: %v", err) + } + if got := s.Get(); got != off { + t.Errorf("cached = %+v, want %+v", got, off) + } + again, err := New(ctx, pool) + if err != nil { + t.Fatalf("reload: %v", err) + } + if got := again.Get(); got != off { + t.Errorf("after a restart = %+v, want %+v", got, off) + } +} diff --git a/internal/mailer/layout.go b/internal/mailer/layout.go new file mode 100644 index 00000000..c240e14f --- /dev/null +++ b/internal/mailer/layout.go @@ -0,0 +1,216 @@ +package mailer + +import ( + "bytes" + "embed" + "fmt" + htmltemplate "html/template" + "io/fs" + "sort" + "strings" + texttemplate "text/template" +) + +// Every email Minstrel sends is drawn by one layout: the Minstrel name at the +// top, the email's heading and message on a card, and a footer saying which +// server sent it and why. An email supplies only its content, as a text +// template and an HTML template, plus a Frame; Render puts the content in the +// frame. A plain-text body goes out beside the HTML for clients that won't +// show HTML. Colours and type come from the Minstrel +// design system, so an email reads as part of the same product. An email is +// dark, the app's own look, wherever the client can't say which the reader +// prefers; a client that says they use a light theme shows the design +// system's light colours instead (lightTheme). + +//go:embed templates/layout.html templates/layout.txt +var layoutFS embed.FS + +var ( + layoutText = texttemplate.Must(texttemplate.ParseFS(layoutFS, "templates/layout.txt")) + layoutHTML = htmltemplate.Must(htmltemplate.New("layout.html").Funcs(htmltemplate.FuncMap{ + "style": style, "class": class, "lightTheme": lightTheme, + }). + ParseFS(layoutFS, "templates/layout.html")) +) + +// The Minstrel design system's values, as an email client needs them: inline, +// and with web fonts named first but never required. +const ( + colourPage = "#14171A" // --fs-surface-page + colourCard = "#1E2228" // --fs-surface-raised + colourBorder = "#3F4651" // --fs-border-color + colourText = "#E8E4D8" // --fs-text-primary + colourSecondary = "#C2BFB4" // --fs-text-secondary + colourTertiary = "#9C9A92" // --fs-text-tertiary + colourLink = "#A1AEA0" // --fs-accent-fg: the accent, readable as text on a dark card + colourAction = "#4A5D3F" // --fs-action-primary + colourOnAction = "#E8E4D8" // --fs-text-on-action + + // The light theme's values of the same tokens. The action colour and the + // text on it are one value in both themes. + lightPage = "#F5F1E8" // --fs-surface-page + lightCard = "#FBF8F0" // --fs-surface-raised + lightBorder = "#D9D6CE" // --fs-border-color + lightText = "#14171A" // --fs-text-primary + lightSecondary = "#5A5852" // --fs-text-secondary + lightTertiary = "#9A9890" // --fs-text-tertiary + lightLink = "#2C3D38" // --fs-accent-fg, mixed with the light text colour + fontBody = "'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" + fontDisplay = "'Fraunces', Georgia, 'Times New Roman', serif" + fontMono = "'JetBrains Mono', ui-monospace, Menlo, Consolas, monospace" +) + +// styles are the named inline styles an email's HTML content uses, written +// `style="{{style "link"}}"`, so every email's links, buttons and quiet text +// look alike and change in one place. +var styles = map[string]string{ + "page": "margin:0; padding:0; background:" + colourPage + ";", + "wrap": "background:" + colourPage + ";", + "brand": "padding:0 4px 16px; font-family:" + fontDisplay + "; font-size:22px; font-weight:500; color:" + colourText + ";", + "heading": "margin:0 0 20px; font-family:" + fontDisplay + "; font-size:20px; font-weight:500; line-height:1.3; color:" + colourText + ";", + "card": "background:" + colourCard + "; border:1px solid " + colourBorder + "; border-radius:12px; padding:28px; font-family:" + fontBody + "; font-size:15px; line-height:1.55; color:" + colourText + ";", + "footer": "padding:16px 4px 0; font-family:" + fontBody + "; font-size:12px; line-height:1.5; color:" + colourTertiary + ";", + "p": "margin:0 0 16px;", + "link": "color:" + colourLink + "; text-decoration:underline;", + "quiet": "color:" + colourSecondary + "; font-size:14px;", + "faint": "color:" + colourTertiary + ";", + "group": "margin:20px 0 4px; font-weight:600; color:" + colourText + ";", + "list": "margin:0 0 8px; padding-left:20px;", + "item": "margin:2px 0;", + "button": "display:inline-block; padding:12px 24px; background:" + colourAction + "; color:" + colourOnAction + "; text-decoration:none; border-radius:8px; font-weight:500;", + "code": "font-family:" + fontMono + "; font-size:13px; word-break:break-all; color:" + colourSecondary + ";", +} + +// lightStyles are the colours each style takes in a light theme. A style +// with a colour has an entry, and an element using it carries its class, +// written `class="{{class "link"}}"`, for the light colours to reach it. +// Inline styles can't follow the reader's theme, so the light colours are +// a stylesheet that overrides them; a client that drops the stylesheet or +// can't tell the theme keeps the inline dark colours. +var lightStyles = map[string]string{ + "page": "background:" + lightPage, + "wrap": "background:" + lightPage, + "brand": "color:" + lightText, + "heading": "color:" + lightText, + "card": "background:" + lightCard + "; border-color:" + lightBorder + "; color:" + lightText, + "footer": "color:" + lightTertiary, + "link": "color:" + lightLink, + "quiet": "color:" + lightSecondary, + "faint": "color:" + lightTertiary, + "group": "color:" + lightText, + "code": "color:" + lightSecondary, +} + +// style returns a named style for an inline style attribute. An unknown name +// fails the render, so a typo shows in the email's test, not in an inbox. +func style(name string) (htmltemplate.CSS, error) { + s, ok := styles[name] + if !ok { + return "", fmt.Errorf("mailer: no email style %q", name) + } + return htmltemplate.CSS(s), nil //nolint:gosec // fixed strings from the table above, never user input +} + +// class returns the class names that give the named styles their light +// colours. An unknown name, or one with no light colours, fails the render. +func class(names ...string) (string, error) { + out := make([]string, 0, len(names)) + for _, n := range names { + if _, ok := lightStyles[n]; !ok { + return "", fmt.Errorf("mailer: no light colours for email style %q", n) + } + out = append(out, "m-"+n) + } + return strings.Join(out, " "), nil +} + +// lightTheme is the stylesheet that gives each class its light colours when +// the reader's system uses a light theme. +func lightTheme() htmltemplate.CSS { + names := make([]string, 0, len(lightStyles)) + for n := range lightStyles { + names = append(names, n) + } + sort.Strings(names) + var b strings.Builder + b.WriteString("@media (prefers-color-scheme: light) {\n") + for _, n := range names { + decls := strings.Split(lightStyles[n], "; ") + for i, d := range decls { + decls[i] = d + " !important" + } + fmt.Fprintf(&b, ".m-%s { %s; }\n", n, strings.Join(decls, "; ")) + } + b.WriteString("}") + return htmltemplate.CSS(b.String()) //nolint:gosec // built from the fixed table above, never user input +} + +// Frame is what the layout says around an email's content. +type Frame struct { + // Heading is the line at the top of the card, saying what the email is. + Heading string + // Server is the server's public address, named in the footer as the + // sender; empty when none is set, and the footer says "your Minstrel + // server" instead. + Server string + // Reason finishes the footer's "…because": why this person got this + // email, in a clause ("you asked to reset your password"). + Reason string + // NotificationSettings adds where to choose which notifications are + // emailed: a link under Server when it is set, else where to find it in + // the app. + NotificationSettings bool +} + +// SettingsURL is the notification settings page under Server, or "". +func (f Frame) SettingsURL() string { + if f.Server == "" { + return "" + } + return strings.TrimRight(f.Server, "/") + "/settings/notifications" +} + +// ServerName is how the footer names the sender. +func (f Frame) ServerName() string { + if f.Server == "" { + return "your Minstrel server" + } + return "the Minstrel server at " + strings.TrimRight(f.Server, "/") +} + +type layoutVars struct { + Content any + Frame Frame +} + +// Render returns an email's text and HTML bodies: the content templates +// textName and htmlName from content, executed with vars, inside the shared +// layout, framed by frame. HTML content styles its elements with +// {{style "name"}}. +func Render(content fs.FS, textName, htmlName string, vars any, frame Frame) (string, string, error) { + textSrc, err := fs.ReadFile(content, textName) + if err != nil { + return "", "", fmt.Errorf("mailer: read %s: %w", textName, err) + } + htmlSrc, err := fs.ReadFile(content, htmlName) + if err != nil { + return "", "", fmt.Errorf("mailer: read %s: %w", htmlName, err) + } + textTpl := texttemplate.Must(layoutText.Clone()) + if _, err := textTpl.New("content").Parse(string(textSrc)); err != nil { + return "", "", fmt.Errorf("mailer: parse %s: %w", textName, err) + } + htmlTpl := htmltemplate.Must(layoutHTML.Clone()) + if _, err := htmlTpl.New("content").Parse(string(htmlSrc)); err != nil { + return "", "", fmt.Errorf("mailer: parse %s: %w", htmlName, err) + } + lv := layoutVars{Content: vars, Frame: frame} + var textBuf, htmlBuf bytes.Buffer + if err := textTpl.ExecuteTemplate(&textBuf, "layout.txt", lv); err != nil { + return "", "", fmt.Errorf("mailer: render %s: %w", textName, err) + } + if err := htmlTpl.ExecuteTemplate(&htmlBuf, "layout.html", lv); err != nil { + return "", "", fmt.Errorf("mailer: render %s: %w", htmlName, err) + } + return textBuf.String(), htmlBuf.String(), nil +} diff --git a/internal/mailer/layout_test.go b/internal/mailer/layout_test.go new file mode 100644 index 00000000..bc3b048a --- /dev/null +++ b/internal/mailer/layout_test.go @@ -0,0 +1,124 @@ +package mailer + +import ( + "regexp" + "strings" + "testing" + "testing/fstest" +) + +// Every email Minstrel sends goes out in the one layout: the Fabled Minstrel name, +// its heading on the card, and a footer naming the sending server and why. +func TestEveryEmailIsFramedByTheLayout(t *testing.T) { + reset := func() (string, string, error) { + return RenderResetEmail(ResetEmailVars{ + Username: "alice", ResetURL: "https://music.example/reset/abc", ExpiryHours: 1, Server: "https://music.example", + }) + } + smtpTest := func() (string, string, error) { return RenderSMTPTestEmail("https://music.example/") } + + for name, render := range map[string]func() (string, string, error){"reset": reset, "smtp test": smtpTest} { + text, html, err := render() + if err != nil { + t.Fatalf("%s: %v", name, err) + } + for _, want := range []string{ + `">Fabled Minstrel`, + `

Hi.

")}} + text, html, err := Render(content, "c.txt", "c.html", nil, Frame{ + Heading: "Hello", Reason: "you asked", NotificationSettings: true, + }) + if err != nil { + t.Fatal(err) + } + for _, body := range []string{text, html} { + if !strings.Contains(body, "Sent by your Minstrel server because you asked.") { + t.Errorf("footer should name the server generically:\n%s", body) + } + if !strings.Contains(body, "under Settings → Notifications") || strings.Contains(body, "http") { + t.Errorf("with no address, the settings line says where to look, without a link:\n%s", body) + } + } +} + +// A misspelt style name fails the render rather than shipping an unstyled email. +func TestUnknownStyleFailsTheRender(t *testing.T) { + content := fstest.MapFS{"c.txt": {Data: []byte("x")}, "c.html": {Data: []byte(`

x

`)}} + if _, _, err := Render(content, "c.txt", "c.html", nil, Frame{Heading: "h", Reason: "r"}); err == nil { + t.Fatal("want an error for an unknown style") + } +} + +// An email is dark unless the reader's system is light. Every element drawn +// in a dark colour carries the class that gives it the light one, and every +// style with a colour has light colours to give. +func TestEveryColouredElementFollowsALightTheme(t *testing.T) { + for name, s := range styles { + if strings.Contains(s, "#") && name != "button" { + if _, ok := lightStyles[name]; !ok { + t.Errorf("style %q has a colour and no light colours", name) + } + } + } + reset, err := func() (string, error) { + _, html, err := RenderResetEmail(ResetEmailVars{ + Username: "alice", ResetURL: "https://music.example/reset/abc", ExpiryHours: 1, Server: "https://music.example", + }) + return html, err + }() + if err != nil { + t.Fatal(err) + } + _, smtpTest, err := RenderSMTPTestEmail("https://music.example/") + if err != nil { + t.Fatal(err) + } + for name, html := range map[string]string{"reset": reset, "smtp test": smtpTest} { + if !strings.Contains(html, "@media (prefers-color-scheme: light)") || + !strings.Contains(html, ".m-card { background:"+lightCard+" !important;") { + t.Errorf("%s html has no light theme", name) + } + for _, tag := range unthemed(html) { + t.Errorf("%s: %s is drawn dark with no light class", name, tag) + } + } + if got := unthemed(`

x

`); len(got) != 1 { + t.Errorf("an element without its class went unnoticed: %v", got) + } +} + +// unthemed lists the tags in html whose inline style uses a dark colour that +// has a light one, but which carry no m- class. A button is the action +// colour with its own text colour, the same in both themes. +func unthemed(html string) []string { + dark := []string{colourPage, colourCard, colourBorder, colourText, colourSecondary, colourTertiary, colourLink} + var out []string + for _, tag := range regexp.MustCompile(`<[a-z0-9]+\s[^>]*style="[^"]*"[^>]*>`).FindAllString(html, -1) { + if strings.Contains(tag, colourAction) { + continue + } + for _, c := range dark { + if strings.Contains(tag, c) && !strings.Contains(tag, `class="m-`) { + out = append(out, tag) + break + } + } + } + return out +} diff --git a/internal/mailer/mailer.go b/internal/mailer/mailer.go index 090017d5..ee16b087 100644 --- a/internal/mailer/mailer.go +++ b/internal/mailer/mailer.go @@ -22,7 +22,8 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/secret" ) // ErrNotConfigured is returned when smtp_config.enabled is false or @@ -68,7 +69,8 @@ func (s *SMTPSender) Send(ctx context.Context, to, subject, textBody, htmlBody s var auth smtp.Auth if cfg.Username != "" { - auth = smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host) + password := secret.Reveal(secret.SMTPPassword.Purpose(), "", cfg.Password) + auth = smtp.PlainAuth("", cfg.Username, password, cfg.Host) } // We respect the use_tls flag: if true, we require STARTTLS via @@ -173,7 +175,7 @@ func composeMessage(cfg dbq.SmtpConfig, to, subject, textBody, htmlBody string) // encodeSubject makes subject safe as a header value. Line breaks are // replaced, so a name carried into a subject cannot start a header of its -// own, and non-ASCII text ("Moe Shop – WWW") is RFC 2047 encoded, which +// own, and non-ASCII text ("Mochi Shop – XYZ") is RFC 2047 encoded, which // mime.QEncoding leaves alone when there is nothing to encode. func encodeSubject(subject string) string { subject = strings.NewReplacer("\r\n", " ", "\r", " ", "\n", " ").Replace(subject) diff --git a/internal/mailer/mailer_test.go b/internal/mailer/mailer_test.go index 9dbf8b97..5a5da890 100644 --- a/internal/mailer/mailer_test.go +++ b/internal/mailer/mailer_test.go @@ -6,7 +6,7 @@ import ( "strings" "testing" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/mailer" ) func TestFakeSender_RecordsCalls(t *testing.T) { diff --git a/internal/mailer/subject_test.go b/internal/mailer/subject_test.go index b3cc2fb7..a48f599e 100644 --- a/internal/mailer/subject_test.go +++ b/internal/mailer/subject_test.go @@ -11,11 +11,11 @@ func TestEncodeSubject(t *testing.T) { t.Errorf("plain ASCII changed: %q", got) } - enc := encodeSubject("Minstrel: Moe Shop – WWW") + enc := encodeSubject("Minstrel: Mochi Shop – XYZ") if !strings.HasPrefix(enc, "=?utf-8?q?") { t.Errorf("non-ASCII not RFC 2047 encoded: %q", enc) } - if dec, err := new(mime.WordDecoder).DecodeHeader(enc); err != nil || dec != "Minstrel: Moe Shop – WWW" { + if dec, err := new(mime.WordDecoder).DecodeHeader(enc); err != nil || dec != "Minstrel: Mochi Shop – XYZ" { t.Errorf("round trip = %q, %v", dec, err) } diff --git a/internal/mailer/templates.go b/internal/mailer/templates.go index 9c526973..6413be09 100644 --- a/internal/mailer/templates.go +++ b/internal/mailer/templates.go @@ -1,45 +1,44 @@ package mailer -import ( - "bytes" - "embed" - "fmt" - htmltemplate "html/template" - texttemplate "text/template" -) +import "embed" -//go:embed templates/password_reset.txt templates/password_reset.html -var resetEmailFS embed.FS +//go:embed templates/password_reset.txt templates/password_reset.html templates/smtp_test.txt templates/smtp_test.html +var emailsFS embed.FS // ResetEmailVars is the data passed to the password reset templates. type ResetEmailVars struct { Username string ResetURL string ExpiryHours int -} - -// RenderResetEmail returns (textBody, htmlBody) for the password -// reset email, parameterized with the given vars. -func RenderResetEmail(vars ResetEmailVars) (string, string, error) { - textTpl, err := texttemplate.ParseFS(resetEmailFS, "templates/password_reset.txt") - if err != nil { - return "", "", fmt.Errorf("mailer: parse text template: %w", err) - } - htmlTpl, err := htmltemplate.ParseFS(resetEmailFS, "templates/password_reset.html") - if err != nil { - return "", "", fmt.Errorf("mailer: parse html template: %w", err) - } - - var textBuf, htmlBuf bytes.Buffer - if err := textTpl.Execute(&textBuf, vars); err != nil { - return "", "", fmt.Errorf("mailer: render text: %w", err) - } - if err := htmlTpl.Execute(&htmlBuf, vars); err != nil { - return "", "", fmt.Errorf("mailer: render html: %w", err) - } - return textBuf.String(), htmlBuf.String(), nil + // Server is the server's public address, named in the footer as the + // sender. + Server string } // ResetEmailSubject is the subject line used by the forgot-password // flow. Exported so callers don't string-literal it independently. const ResetEmailSubject = "Minstrel password reset" + +// RenderResetEmail returns (textBody, htmlBody) for the password reset +// email. +func RenderResetEmail(vars ResetEmailVars) (string, string, error) { + return Render(emailsFS, "templates/password_reset.txt", "templates/password_reset.html", vars, Frame{ + Heading: "Reset your password", + Server: vars.Server, + Reason: "a password reset was requested for your account", + }) +} + +// SMTPTestSubject is the subject of the message an admin sends to check +// the server's email settings. +const SMTPTestSubject = "Minstrel email test" + +// RenderSMTPTestEmail returns (textBody, htmlBody) for the email settings +// test message. server is the server's public address, or "". +func RenderSMTPTestEmail(server string) (string, string, error) { + return Render(emailsFS, "templates/smtp_test.txt", "templates/smtp_test.html", struct{}{}, Frame{ + Heading: "Email is working", + Server: server, + Reason: "an admin sent a test from the email settings", + }) +} diff --git a/internal/mailer/templates/layout.html b/internal/mailer/templates/layout.html new file mode 100644 index 00000000..61a09910 --- /dev/null +++ b/internal/mailer/templates/layout.html @@ -0,0 +1,32 @@ + + + + + + + + + + +

+ + + + diff --git a/internal/mailer/templates/layout.txt b/internal/mailer/templates/layout.txt new file mode 100644 index 00000000..6119d81f --- /dev/null +++ b/internal/mailer/templates/layout.txt @@ -0,0 +1,9 @@ +{{.Frame.Heading}} + +{{template "content" .Content}} +-- +Sent by {{.Frame.ServerName}} because {{.Frame.Reason}}. +{{- if .Frame.NotificationSettings}} +{{with .Frame.SettingsURL}}Choose which notifications are emailed to you: {{.}}{{else}}Choose which notifications are emailed to you in Minstrel, under Settings → Notifications.{{end}} +{{- end}} +— Fabled Minstrel diff --git a/internal/mailer/templates/password_reset.html b/internal/mailer/templates/password_reset.html index c5d52527..ad433ac1 100644 --- a/internal/mailer/templates/password_reset.html +++ b/internal/mailer/templates/password_reset.html @@ -1,29 +1,7 @@ - - - -

Hello {{.Username}},

- -

A password reset was requested for your Minstrel account. To set a new - password, click the button below within {{.ExpiryHours}} hours:

- -

- Reset password -

- -

- Or copy this URL into your browser:
- {{.ResetURL}} -

- -

- If you didn't request this, you can safely ignore this email — your - password won't change. -

- -

- — Minstrel -

- - +

Hello {{.Username}},

+

A password reset was requested for your Minstrel account. To set a new +password, use the button below within {{.ExpiryHours}} hours.

+

Reset password

+

Or copy this address into your browser:
+{{.ResetURL}}

+

If you didn't ask for this, you can ignore this email. Your password won't change.

diff --git a/internal/mailer/templates/password_reset.txt b/internal/mailer/templates/password_reset.txt index ac1f3618..0cefb6db 100644 --- a/internal/mailer/templates/password_reset.txt +++ b/internal/mailer/templates/password_reset.txt @@ -5,7 +5,5 @@ password, follow this link within {{.ExpiryHours}} hours: {{.ResetURL}} -If you didn't request this, you can safely ignore this email — your -password won't change. - -— Minstrel +If you didn't ask for this, you can ignore this email. Your password +won't change. diff --git a/internal/mailer/templates/smtp_test.html b/internal/mailer/templates/smtp_test.html new file mode 100644 index 00000000..745384d7 --- /dev/null +++ b/internal/mailer/templates/smtp_test.html @@ -0,0 +1,2 @@ +

This is a test message from your Minstrel server.

+

It arrived, so the server's email settings work: password resets and the notification emails people choose will reach their inboxes.

diff --git a/internal/mailer/templates/smtp_test.txt b/internal/mailer/templates/smtp_test.txt new file mode 100644 index 00000000..61e68240 --- /dev/null +++ b/internal/mailer/templates/smtp_test.txt @@ -0,0 +1,4 @@ +This is a test message from your Minstrel server. + +It arrived, so the server's email settings work: password resets and the +notification emails people choose will reach their inboxes. diff --git a/internal/musicbrainz/client.go b/internal/musicbrainz/client.go index 86721968..86a181f4 100644 --- a/internal/musicbrainz/client.go +++ b/internal/musicbrainz/client.go @@ -8,18 +8,15 @@ import ( "io" "net/http" "net/url" - "strconv" "strings" "time" + + "github.com/Fabled-Sword/minstrel/internal/buildinfo" ) // DefaultBaseURL is the public MusicBrainz web service. const DefaultBaseURL = "https://musicbrainz.org/ws/2" -// UserAgent identifies Minstrel. MusicBrainz refuses requests without a -// descriptive one. -const UserAgent = "Minstrel/1.0 ( https://git.fabledsword.com/bvandeusen/minstrel )" - // DefaultTimeout bounds one request. A browse page with track // lists is the slowest thing asked for. const DefaultTimeout = 20 * time.Second @@ -131,7 +128,8 @@ func (c *Client) once(ctx context.Context, full string, out any) (retry bool, er return false, fmt.Errorf("musicbrainz: build request: %w", err) } req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", UserAgent) + // MusicBrainz refuses requests without a descriptive User-Agent. + req.Header.Set("User-Agent", buildinfo.UserAgent("")) resp, err := c.httpClient().Do(req) if err != nil { @@ -173,37 +171,3 @@ func sleep(ctx context.Context, d time.Duration) error { return nil } } - -// luceneSpecial are the characters MusicBrainz's search syntax gives meaning. -const luceneSpecial = `+-&|!(){}[]^"~*?:\/` - -// Escape makes text typed by a person safe to put in a search query, so -// "AC/DC" or "Sunn O)))" searches for what was typed rather than failing to -// parse. -func Escape(s string) string { - var b strings.Builder - for _, r := range s { - if strings.ContainsRune(luceneSpecial, r) { - b.WriteByte('\\') - } - b.WriteRune(r) - } - return b.String() -} - -// fieldQuery searches each field for the escaped text. -func fieldQuery(text string, fields ...string) string { - t := Escape(strings.TrimSpace(text)) - parts := make([]string, len(fields)) - for i, f := range fields { - parts[i] = f + ":(" + t + ")" - } - return strings.Join(parts, " OR ") -} - -func searchLimit(limit int) string { - if limit <= 0 || limit > 100 { - limit = 25 - } - return strconv.Itoa(limit) -} diff --git a/internal/musicbrainz/client_test.go b/internal/musicbrainz/client_test.go index ded2815f..ec8597e6 100644 --- a/internal/musicbrainz/client_test.go +++ b/internal/musicbrainz/client_test.go @@ -3,10 +3,8 @@ package musicbrainz import ( "context" "errors" - "fmt" "net/http" "net/http/httptest" - "strconv" "sync/atomic" "testing" "time" @@ -17,130 +15,17 @@ func testClient(srv *httptest.Server) *Client { return &Client{BaseURL: srv.URL, Pace: &Pacer{}, Backoff: time.Millisecond} } -func TestEscape_KeepsWhatWasTyped(t *testing.T) { - for in, want := range map[string]string{ - "Radiohead": "Radiohead", - "AC/DC": `AC\/DC`, - "Sunn O)))": `Sunn O\)\)\)`, - `"Weird" Al`: `\"Weird\" Al`, - } { - if got := Escape(in); got != want { - t.Errorf("Escape(%q) = %q, want %q", in, got, want) - } - } -} - -func TestSearchReleaseGroups_AsksTitleAndArtistAndReadsCredits(t *testing.T) { - var query, agent atomic.Value - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - query.Store(r.URL.Query().Get("query")) - agent.Store(r.Header.Get("User-Agent")) - _, _ = w.Write([]byte(`{"release-groups": [{ - "id": "rg1", "title": "OK Computer", "primary-type": "Album", "secondary-types": [], - "first-release-date": "1997-05-21", - "artist-credit": [{"name": "Radiohead", "joinphrase": "", "artist": {"id": "a1", "name": "Radiohead"}}] - }]}`)) - })) - defer srv.Close() - - got, err := testClient(srv).SearchReleaseGroups(context.Background(), "ok computer", 10) - if err != nil { - t.Fatal(err) - } - if q := query.Load(); q != "releasegroup:(ok computer) OR artist:(ok computer)" { - t.Errorf("query = %q", q) - } - if agent.Load() != UserAgent { - t.Errorf("User-Agent = %q", agent.Load()) - } - if len(got) != 1 || got[0].MBID != "rg1" || got[0].Year() != "1997" || got[0].ArtistCredit != "Radiohead" || got[0].ArtistMBIDs[0] != "a1" { - t.Errorf("got %+v", got) - } -} - -func TestSearchReleaseGroupsBy_AsksForBothTitleAndArtist(t *testing.T) { - var query atomic.Value - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - query.Store(r.URL.Query().Get("query")) - _, _ = w.Write([]byte(`{"release-groups": [{"id": "rg1", "title": "Highway to Hell", - "artist-credit": [{"name": "AC/DC", "artist": {"id": "a1"}}]}]}`)) - })) - defer srv.Close() - - got, err := testClient(srv).SearchReleaseGroupsBy(context.Background(), " AC/DC ", "Highway to Hell", 10) - if err != nil { - t.Fatal(err) - } - if q := query.Load(); q != `releasegroup:(Highway to Hell) AND artist:(AC\/DC)` { - t.Errorf("query = %q", q) - } - if len(got) != 1 || got[0].MBID != "rg1" || got[0].ArtistMBIDs[0] != "a1" { - t.Errorf("got %+v", got) - } -} - -func TestSearchRecordings_FilesASongUnderItsAlbum(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`{"recordings": [{ - "id": "rec1", "title": "Karma Police", "length": 264000, - "artist-credit": [{"name": "Radiohead", "artist": {"id": "a1"}}], - "releases": [ - {"id": "r1", "status": "Official", "release-group": {"id": "rg-live", "title": "Live", "primary-type": "Album", "secondary-types": ["Live"]}}, - {"id": "r2", "status": "Official", "release-group": {"id": "rg1", "title": "OK Computer", "primary-type": "Album"}} - ] - }]}`)) - })) - defer srv.Close() - - got, err := testClient(srv).SearchRecordings(context.Background(), "karma police", 5) - if err != nil { - t.Fatal(err) - } - if len(got) != 1 || got[0].ReleaseGroup.MBID != "rg1" || got[0].LengthMs != 264000 { - t.Errorf("got %+v, want it filed under the studio album", got) - } -} - -func TestArtistReleaseGroups_PagesUntilTheCount(t *testing.T) { - var calls atomic.Int32 - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls.Add(1) - offset, _ := strconv.Atoi(r.URL.Query().Get("offset")) - if r.URL.Query().Get("artist") != "a1" { - t.Errorf("artist = %q", r.URL.Query().Get("artist")) - } - // 3 in all, two per page. - var items string - for i := offset; i < offset+2 && i < 3; i++ { - if items != "" { - items += "," - } - items += fmt.Sprintf(`{"id": "rg%d", "title": "T%d", "primary-type": "Album"}`, i, i) - } - _, _ = fmt.Fprintf(w, `{"release-group-count": 3, "release-groups": [%s]}`, items) - })) - defer srv.Close() - - got, err := testClient(srv).ArtistReleaseGroups(context.Background(), "a1") - if err != nil { - t.Fatal(err) - } - if len(got) != 3 || calls.Load() != 2 { - t.Errorf("got %d groups in %d calls, want 3 in 2", len(got), calls.Load()) - } -} - func TestReleaseGroupReleases_ReadsMediaAndTracks(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("inc") != "media recordings" { t.Errorf("inc = %q", r.URL.Query().Get("inc")) } _, _ = w.Write([]byte(`{"release-count": 1, "releases": [{ - "id": "r1", "title": "OK Computer", "status": "Official", "date": "1997-06-16", "country": "GB", + "id": "r1", "title": "OK Calculator", "status": "Official", "date": "1997-06-16", "country": "GB", "media": [ {"position": 1, "format": "CD", "tracks": [ - {"position": 1, "number": "1", "title": "Airbag", "length": 284000, "recording": {"id": "rec-a"}}, - {"position": 2, "number": "2", "title": "Paranoid Android", "length": null, "recording": {"id": "rec-b", "length": 383000}} + {"position": 1, "number": "1", "title": "Lifebelt", "length": 284000, "recording": {"id": "rec-a"}}, + {"position": 2, "number": "2", "title": "Anxious Robot", "length": null, "recording": {"id": "rec-b", "length": 383000}} ]}, {"position": 2, "format": "CD", "tracks": []} ] @@ -171,12 +56,12 @@ func TestGet_ThrottleIsRetriedThenUnreachable(t *testing.T) { w.WriteHeader(http.StatusServiceUnavailable) return } - _, _ = w.Write([]byte(`{"artists": [{"id": "a1", "name": "Radiohead"}]}`)) + _, _ = w.Write([]byte(`{"id": "rg1", "title": "Paper Boats"}`)) })) defer srv.Close() - got, err := testClient(srv).SearchArtists(context.Background(), "radiohead", 5) - if err != nil || len(got) != 1 || calls.Load() != 2 { + got, err := testClient(srv).ReleaseGroup(context.Background(), "rg1") + if err != nil || got.Title != "Paper Boats" || calls.Load() != 2 { t.Fatalf("a throttled first answer should be retried: %v, %+v, %d calls", err, got, calls.Load()) } @@ -184,7 +69,7 @@ func TestGet_ThrottleIsRetriedThenUnreachable(t *testing.T) { w.WriteHeader(http.StatusBadGateway) })) defer down.Close() - if _, err := testClient(down).SearchArtists(context.Background(), "x", 5); !errors.Is(err, ErrUnreachable) { + if _, err := testClient(down).ReleaseGroup(context.Background(), "rg1"); !errors.Is(err, ErrUnreachable) { t.Errorf("err = %v, want ErrUnreachable", err) } } @@ -193,13 +78,13 @@ func TestGet_NotFoundAndNoServer(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) })) - if _, err := testClient(srv).Artist(context.Background(), "nope"); !errors.Is(err, ErrNotFound) { + if _, err := testClient(srv).ReleaseGroup(context.Background(), "nope"); !errors.Is(err, ErrNotFound) { t.Errorf("err = %v, want ErrNotFound", err) } srv.Close() c := testClient(srv) c.Retries = -1 - if _, err := c.Artist(context.Background(), "a1"); !errors.Is(err, ErrUnreachable) { + if _, err := c.ReleaseGroup(context.Background(), "rg1"); !errors.Is(err, ErrUnreachable) { t.Errorf("a closed server: err = %v, want ErrUnreachable", err) } } diff --git a/internal/musicbrainz/entities.go b/internal/musicbrainz/entities.go index b7acd786..6b7d8d9e 100644 --- a/internal/musicbrainz/entities.go +++ b/internal/musicbrainz/entities.go @@ -7,16 +7,6 @@ import ( "strings" ) -// Artist is a MusicBrainz artist. -type Artist struct { - MBID string - Name string - SortName string - Disambiguation string - Type string // Person, Group, Orchestra, …; may be empty - Country string -} - // ReleaseGroup is what a person calls an album: one work, released any // number of times. type ReleaseGroup struct { @@ -31,14 +21,6 @@ type ReleaseGroup struct { ArtistMBIDs []string } -// Year is the first release's year, or "". -func (g ReleaseGroup) Year() string { - if len(g.FirstReleaseDate) >= 4 { - return g.FirstReleaseDate[:4] - } - return "" -} - // Release is one issue of a release group: a pressing, an edition, a // digital release, each with its own track list. type Release struct { @@ -98,18 +80,6 @@ type Track struct { RecordingMBID string } -// Recording is a piece of audio, as a search returns it. -type Recording struct { - MBID string - Title string - LengthMs int - ArtistCredit string - ArtistMBIDs []string - // ReleaseGroup is the group the recording is best known from: the first - // official album it appears on, else the first release listed. - ReleaseGroup ReleaseGroup -} - // --- wire shapes --- type wireCredit struct { @@ -138,19 +108,6 @@ func credit(cs []wireCredit) (string, []string) { return b.String(), ids } -type wireArtist struct { - ID string `json:"id"` - Name string `json:"name"` - SortName string `json:"sort-name"` - Disambiguation string `json:"disambiguation"` - Type string `json:"type"` - Country string `json:"country"` -} - -func (w wireArtist) artist() Artist { - return Artist{MBID: w.ID, Name: w.Name, SortName: w.SortName, Disambiguation: w.Disambiguation, Type: w.Type, Country: w.Country} -} - type wireReleaseGroup struct { ID string `json:"id"` Title string `json:"title"` @@ -192,7 +149,6 @@ type wireRelease struct { Format string `json:"format"` Tracks []wireTrack `json:"tracks"` } `json:"media"` - ReleaseGroup *wireReleaseGroup `json:"release-group"` } func (w wireRelease) release() Release { @@ -217,149 +173,8 @@ func (w wireRelease) release() Release { return r } -// --- searches --- - -// SearchArtists finds artists by name or alias. -func (c *Client) SearchArtists(ctx context.Context, text string, limit int) ([]Artist, error) { - var resp struct { - Artists []wireArtist `json:"artists"` - } - q := url.Values{"query": {fieldQuery(text, "artist", "alias")}, "limit": {searchLimit(limit)}} - if err := c.get(ctx, "/artist", q, &resp); err != nil { - return nil, err - } - out := make([]Artist, 0, len(resp.Artists)) - for _, a := range resp.Artists { - out = append(out, a.artist()) - } - return out, nil -} - -// SearchReleaseGroups finds albums by title or by artist, so "radiohead ok -// computer" and "ok computer" both find OK Computer. -func (c *Client) SearchReleaseGroups(ctx context.Context, text string, limit int) ([]ReleaseGroup, error) { - var resp struct { - ReleaseGroups []wireReleaseGroup `json:"release-groups"` - } - q := url.Values{"query": {fieldQuery(text, "releasegroup", "artist")}, "limit": {searchLimit(limit)}} - if err := c.get(ctx, "/release-group", q, &resp); err != nil { - return nil, err - } - out := make([]ReleaseGroup, 0, len(resp.ReleaseGroups)) - for _, g := range resp.ReleaseGroups { - out = append(out, g.group()) - } - return out, nil -} - -// SearchReleaseGroupsBy finds an artist's albums by title: both must -// match, where SearchReleaseGroups takes either. It is for naming an album -// already in hand, not for a person's search box. -func (c *Client) SearchReleaseGroupsBy(ctx context.Context, artist, title string, limit int) ([]ReleaseGroup, error) { - var resp struct { - ReleaseGroups []wireReleaseGroup `json:"release-groups"` - } - query := "releasegroup:(" + Escape(strings.TrimSpace(title)) + ") AND artist:(" + Escape(strings.TrimSpace(artist)) + ")" - q := url.Values{"query": {query}, "limit": {searchLimit(limit)}} - if err := c.get(ctx, "/release-group", q, &resp); err != nil { - return nil, err - } - out := make([]ReleaseGroup, 0, len(resp.ReleaseGroups)) - for _, g := range resp.ReleaseGroups { - out = append(out, g.group()) - } - return out, nil -} - -// SearchRecordings finds songs by title or by artist. -func (c *Client) SearchRecordings(ctx context.Context, text string, limit int) ([]Recording, error) { - var resp struct { - Recordings []struct { - ID string `json:"id"` - Title string `json:"title"` - Length *int `json:"length"` - ArtistCredit []wireCredit `json:"artist-credit"` - Releases []wireRelease `json:"releases"` - } `json:"recordings"` - } - q := url.Values{"query": {fieldQuery(text, "recording", "artist")}, "limit": {searchLimit(limit)}} - if err := c.get(ctx, "/recording", q, &resp); err != nil { - return nil, err - } - out := make([]Recording, 0, len(resp.Recordings)) - for _, r := range resp.Recordings { - name, ids := credit(r.ArtistCredit) - rec := Recording{MBID: r.ID, Title: r.Title, ArtistCredit: name, ArtistMBIDs: ids} - if r.Length != nil { - rec.LengthMs = *r.Length - } - rec.ReleaseGroup = bestKnownFrom(r.Releases) - out = append(out, rec) - } - return out, nil -} - -// bestKnownFrom picks the release group a recording should be filed under -// in a search result: the first official album, else the first release. -func bestKnownFrom(releases []wireRelease) ReleaseGroup { - var first *wireReleaseGroup - for _, r := range releases { - if r.ReleaseGroup == nil || r.ReleaseGroup.ID == "" { - continue - } - if first == nil { - first = r.ReleaseGroup - } - if r.Status == "Official" && r.ReleaseGroup.PrimaryType == "Album" && len(r.ReleaseGroup.SecondaryTypes) == 0 { - return r.ReleaseGroup.group() - } - } - if first == nil { - return ReleaseGroup{} - } - return first.group() -} - // --- lookups and browses --- -// Artist looks one artist up by MBID. -func (c *Client) Artist(ctx context.Context, mbid string) (Artist, error) { - var w wireArtist - if err := c.get(ctx, "/artist/"+url.PathEscape(mbid), nil, &w); err != nil { - return Artist{}, err - } - if w.ID == "" { - return Artist{}, ErrBadResponse - } - return w.artist(), nil -} - -// ArtistReleaseGroups lists every release group the artist is credited on, -// paging through MusicBrainz's browse. -func (c *Client) ArtistReleaseGroups(ctx context.Context, artistMBID string) ([]ReleaseGroup, error) { - var out []ReleaseGroup - for page := 0; page < maxPages; page++ { - var resp struct { - Count int `json:"release-group-count"` - ReleaseGroups []wireReleaseGroup `json:"release-groups"` - } - q := url.Values{ - "artist": {artistMBID}, "inc": {"artist-credits"}, - "limit": {strconv.Itoa(pageSize)}, "offset": {strconv.Itoa(len(out))}, - } - if err := c.get(ctx, "/release-group", q, &resp); err != nil { - return nil, err - } - for _, g := range resp.ReleaseGroups { - out = append(out, g.group()) - } - if len(resp.ReleaseGroups) == 0 || len(out) >= resp.Count { - break - } - } - return out, nil -} - // ReleaseGroupReleases lists every release of a release group with its // media and track lists. func (c *Client) ReleaseGroupReleases(ctx context.Context, groupMBID string) ([]Release, error) { diff --git a/internal/netsettings/publicurl_test.go b/internal/netsettings/publicurl_test.go index 1deebde5..f885a33b 100644 --- a/internal/netsettings/publicurl_test.go +++ b/internal/netsettings/publicurl_test.go @@ -8,7 +8,7 @@ func TestNormalizePublicURL(t *testing.T) { " ": "", "https://music.example.com": "https://music.example.com", "https://music.example.com/": "https://music.example.com", - "http://192.168.1.10:4533": "http://192.168.1.10:4533", + "http://198.51.100.10:4533": "http://198.51.100.10:4533", " https://Music.Example.com/ ": "https://Music.Example.com", } for in, want := range ok { diff --git a/internal/netsettings/service.go b/internal/netsettings/service.go index 8fe4d31a..6fbe06b3 100644 --- a/internal/netsettings/service.go +++ b/internal/netsettings/service.go @@ -18,15 +18,15 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) const ( - // DefaultTrustedProxyHops mirrors migration 0053's column default. One + // DefaultTrustedProxyHops mirrors network_settings's column default. One // proxy, because anything publicly reachable needs a TLS terminator in // front of it. DefaultTrustedProxyHops = 1 - // MaxTrustedProxyHops mirrors the CHECK in migration 0053. + // MaxTrustedProxyHops mirrors network_settings's CHECK. MaxTrustedProxyHops = 10 ) diff --git a/internal/notifications/digest.go b/internal/notifications/digest.go index 94b44211..4225b1c6 100644 --- a/internal/notifications/digest.go +++ b/internal/notifications/digest.go @@ -11,8 +11,9 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/periodic" ) // The email digest. Nothing is emailed per event: a steady stream of new @@ -159,17 +160,9 @@ func NewDigest(pool *pgxpool.Pool, sender mailer.Sender, logger *slog.Logger) *D // that has been down past a batch or a summary hour catches up, then every // few minutes. func (d *Digest) Run(ctx context.Context) { - d.Tick(ctx, time.Now()) - t := time.NewTicker(digestInterval) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case now := <-t.C: - d.Tick(ctx, now) - } - } + periodic.Run(ctx, d.logger, "notification digest", digestInterval, func(ctx context.Context) { + d.Tick(ctx, time.Now()) + }) } // Tick sends every group that is due as of now. Failures are logged and diff --git a/internal/notifications/digest_db_test.go b/internal/notifications/digest_db_test.go index a61bf940..048493bb 100644 --- a/internal/notifications/digest_db_test.go +++ b/internal/notifications/digest_db_test.go @@ -10,9 +10,10 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "github.com/stretchr/testify/require" - "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" - "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" - "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/dbtest" + "github.com/Fabled-Sword/minstrel/internal/mailer" + "github.com/Fabled-Sword/minstrel/internal/notifications" ) // emailUser is a user with an address, so the digest can reach them. @@ -30,17 +31,17 @@ func digestWith(pool *pgxpool.Pool) (*notifications.Digest, *mailer.FakeSender) } func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() - alice := emailUser(t, pool, "alice", false) + alice := emailUser(t, pool, "alice", true) n := notifications.New(pool, nil, nil) d, fake := digestWith(pool) start := time.Now() - require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), - notifications.Payload{Name: "Moe Shop – WWW"}.Map())) - require.NoError(t, n.Notify(ctx, notifications.KindRequestRejected, notifications.ToUser(alice), - notifications.Payload{Name: "Tycho – Awake", Reason: "already have it"}.Map())) + require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), + notifications.Payload{Name: "Mochi Shop – XYZ"}.Map())) + require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), + notifications.Payload{Name: "Tacho – Asleep", Reason: "already have it"}.Map())) d.Tick(ctx, start.Add(30*time.Minute)) require.Empty(t, fake.Sent, "inside the window nothing goes") @@ -49,23 +50,23 @@ func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) { require.Len(t, fake.Sent, 1, "both items, one email") require.Equal(t, "alice@example.com", fake.Sent[0].To) require.Equal(t, "Minstrel: 2 updates", fake.Sent[0].Subject) - require.Contains(t, fake.Sent[0].TextBody, "Moe Shop – WWW is on its way.") - require.Contains(t, fake.Sent[0].TextBody, "Tycho – Awake was declined: already have it") + require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Mochi Shop – XYZ.") + require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Tacho – Asleep: already have it") d.Tick(ctx, start.Add(3*time.Hour)) require.Len(t, fake.Sent, 1, "never sent twice") } func TestDigest_ReadBeforeTheEmailIsNotEmailed(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) - alice := emailUser(t, pool, "alice", false) + alice := emailUser(t, pool, "alice", true) n := notifications.New(pool, nil, nil) d, fake := digestWith(pool) start := time.Now() - require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil)) + require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil)) _, err := q.MarkAllNotificationsRead(ctx, dbq.MarkAllNotificationsReadParams{UserID: alice}) require.NoError(t, err) @@ -74,23 +75,23 @@ func TestDigest_ReadBeforeTheEmailIsNotEmailed(t *testing.T) { } func TestDigest_EmailOffAtNotifyTimeIsNeverSent(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) - alice := emailUser(t, pool, "alice", false) + alice := emailUser(t, pool, "alice", true) off := false - _, err := notifications.SaveSettings(ctx, q, alice, false, []notifications.SettingChange{ - {Kind: notifications.KindRequestApproved, Email: &off}, + _, err := notifications.SaveSettings(ctx, q, alice, true, []notifications.SettingChange{ + {Kind: notifications.KindQuarantineFlagged, Email: &off}, }) require.NoError(t, err) n := notifications.New(pool, nil, nil) d, fake := digestWith(pool) start := time.Now() - require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil)) + require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil)) on := true - _, err = notifications.SaveSettings(ctx, q, alice, false, []notifications.SettingChange{ - {Kind: notifications.KindRequestApproved, Email: &on}, + _, err = notifications.SaveSettings(ctx, q, alice, true, []notifications.SettingChange{ + {Kind: notifications.KindQuarantineFlagged, Email: &on}, }) require.NoError(t, err) @@ -99,19 +100,19 @@ func TestDigest_EmailOffAtNotifyTimeIsNeverSent(t *testing.T) { } func TestDigest_NoAddressNoEmail(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() - bob := mkUser(t, dbq.New(pool), "bob", false) + bob := mkUser(t, dbq.New(pool), "bob", true) n := notifications.New(pool, nil, nil) d, fake := digestWith(pool) - require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(bob), nil)) + require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(bob), nil)) d.Tick(ctx, time.Now().Add(2*time.Hour)) require.Empty(t, fake.Sent) } func TestDigest_CoalescedItemAppearsOnceWithItsLatestCount(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) root := emailUser(t, pool, "root", true) @@ -134,14 +135,14 @@ func TestDigest_CoalescedItemAppearsOnceWithItsLatestCount(t *testing.T) { } func TestDigest_MailerFailureRetriesWithBackoffAndSendsOnce(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() - alice := emailUser(t, pool, "alice", false) + alice := emailUser(t, pool, "alice", true) n := notifications.New(pool, nil, nil) d, fake := digestWith(pool) start := time.Now() - require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil)) + require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil)) fake.FailNext = errors.New("smtp: 421 try later") d.Tick(ctx, start.Add(61*time.Minute)) @@ -158,9 +159,9 @@ func TestDigest_MailerFailureRetriesWithBackoffAndSendsOnce(t *testing.T) { } func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() - alice := emailUser(t, pool, "alice", false) // timezone defaults to UTC + alice := emailUser(t, pool, "alice", true) // timezone defaults to UTC n := notifications.New(pool, nil, nil) d, fake := digestWith(pool) @@ -170,11 +171,12 @@ func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) { slot = slot.AddDate(0, 0, 1) } - for _, p := range []notifications.Payload{ - {Name: "Moe Shop – WWW", Artist: "Moe Shop", Title: "WWW"}, - {Name: "Moe Shop – Pure", Artist: "Moe Shop", Title: "Pure"}, + for _, a := range []notifications.Arrival{ + {Artist: "Mochi Shop", Title: "XYZ"}, + {Artist: "Mochi Shop", Title: "Pure"}, } { - require.NoError(t, n.Notify(ctx, notifications.KindRequestCompleted, notifications.ToUser(alice), p.Map())) + p := notifications.Payload{Count: 1, Albums: []notifications.Arrival{a}} + require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, notifications.ToUser(alice), p.Map())) } d.Tick(ctx, slot.Add(-time.Minute)) @@ -183,7 +185,7 @@ func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) { d.Tick(ctx, slot) require.Len(t, fake.Sent, 1) require.Equal(t, "Minstrel: new music in your library", fake.Sent[0].Subject) - require.Contains(t, fake.Sent[0].TextBody, "Moe Shop\n - WWW") + require.Contains(t, fake.Sent[0].TextBody, "Mochi Shop\n - XYZ") require.Contains(t, fake.Sent[0].TextBody, " - Pure") d.Tick(ctx, slot.Add(5*time.Hour)) @@ -191,7 +193,7 @@ func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) { } func TestEmailSettings_DefaultsMatchTheMigrationAndRoundTrip(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -208,16 +210,16 @@ func TestEmailSettings_DefaultsMatchTheMigrationAndRoundTrip(t *testing.T) { } func TestDigest_UsesTheConfiguredBatchWindow(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() - alice := emailUser(t, pool, "alice", false) + alice := emailUser(t, pool, "alice", true) _, err := notifications.SaveEmailSettings(ctx, dbq.New(pool), notifications.EmailSettings{SummaryHour: 9, BatchWindowMinutes: 15}) require.NoError(t, err) n := notifications.New(pool, nil, nil) d, fake := digestWith(pool) start := time.Now() - require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil)) + require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil)) d.Tick(ctx, start.Add(16*time.Minute)) require.Len(t, fake.Sent, 1) } diff --git a/internal/notifications/digest_render.go b/internal/notifications/digest_render.go index 5c9ae146..e1241751 100644 --- a/internal/notifications/digest_render.go +++ b/internal/notifications/digest_render.go @@ -1,23 +1,17 @@ package notifications import ( - "bytes" "embed" "encoding/json" "fmt" - htmltemplate "html/template" "strings" - texttemplate "text/template" + + "github.com/Fabled-Sword/minstrel/internal/mailer" ) //go:embed templates/digest.txt templates/digest.html var digestFS embed.FS -var ( - digestText = texttemplate.Must(texttemplate.ParseFS(digestFS, "templates/digest.txt")) - digestHTML = htmltemplate.Must(htmltemplate.ParseFS(digestFS, "templates/digest.html")) -) - // digestEmail is one rendered email. type digestEmail struct { Subject string @@ -38,22 +32,24 @@ type digestArtist struct { } type digestVars struct { - Name string - Intro string - Items []digestLine - Artists []digestArtist - SettingsURL string + Name string + Intro string + Items []digestLine + Artists []digestArtist } // renderDigest renders one group's email. base is the public address; with // none set, the email still goes out, without links. func renderDigest(group EmailGroup, name string, items []pendingItem, base string) (digestEmail, error) { - vars := digestVars{Name: name, SettingsURL: joinURL(base, "/settings/notifications")} + vars := digestVars{Name: name} + frame := mailer.Frame{Server: base, NotificationSettings: true} var subject string if group == EmailSummary { vars.Artists = summaryArtists(items, base) vars.Intro = "New in your library since the last summary:" subject = "Minstrel: new music in your library" + frame.Heading = "New music in your library" + frame.Reason = "you chose to get new-music summaries by email" } else { for _, it := range items { r := Render(it.Kind, it.Payload) @@ -61,52 +57,49 @@ func renderDigest(group EmailGroup, name string, items []pendingItem, base strin } vars.Intro = "Here's what happened on Minstrel:" subject = fmt.Sprintf("Minstrel: %d updates", len(items)) + frame.Heading = fmt.Sprintf("%d updates", len(items)) if len(items) == 1 { subject = "Minstrel: " + vars.Items[0].Title + frame.Heading = vars.Items[0].Title } + frame.Reason = "you chose to get these notifications by email" } - var text, html bytes.Buffer - if err := digestText.Execute(&text, vars); err != nil { - return digestEmail{}, fmt.Errorf("render text: %w", err) + text, html, err := mailer.Render(digestFS, "templates/digest.txt", "templates/digest.html", vars, frame) + if err != nil { + return digestEmail{}, fmt.Errorf("render digest: %w", err) } - if err := digestHTML.Execute(&html, vars); err != nil { - return digestEmail{}, fmt.Errorf("render html: %w", err) - } - return digestEmail{Subject: subject, Text: text.String(), HTML: html.String()}, nil + return digestEmail{Subject: subject, Text: text, HTML: html}, nil } // summaryArtists groups new-music arrivals by artist, in the order each -// artist first arrived, with each artist's albums and tracks under them. An -// artist request has no title of its own; the artist links to its page. +// artist first arrived, with each artist's albums under them. func summaryArtists(items []pendingItem, base string) []digestArtist { var out []digestArtist index := map[string]int{} for _, it := range items { var p Payload _ = json.Unmarshal(it.Payload, &p) - artist, title := p.Artist, p.Title - if artist == "" { - // Rows from before Artist was recorded carry only "Artist – Title". - artist, title, _ = strings.Cut(p.Name, " – ") - } - if artist == "" { - artist = "Something you asked for" - } - i, ok := index[artist] - if !ok { - i = len(out) - index[artist] = i - out = append(out, digestArtist{Name: artist}) - } - link := Render(it.Kind, it.Payload).Link - if title == "" { - if p.ArtistID != "" { - out[i].URL = joinURL(base, link) + for _, a := range p.Albums { + artist := a.Artist + if artist == "" { + artist = "Unknown artist" } - continue + i, ok := index[artist] + if !ok { + i = len(out) + index[artist] = i + out = append(out, digestArtist{Name: artist}) + if a.ArtistID != "" { + out[i].URL = joinURL(base, "/artists/"+a.ArtistID) + } + } + link := "/" + if a.AlbumID != "" { + link = "/albums/" + a.AlbumID + } + out[i].Titles = append(out[i].Titles, digestLine{Title: a.Title, URL: joinURL(base, link)}) } - out[i].Titles = append(out[i].Titles, digestLine{Title: title, URL: joinURL(base, link)}) } return out } diff --git a/internal/notifications/digest_test.go b/internal/notifications/digest_test.go index 60799a13..35bac7e1 100644 --- a/internal/notifications/digest_test.go +++ b/internal/notifications/digest_test.go @@ -28,8 +28,8 @@ func allEmail() map[Kind]bool { } func TestPlanUser_BatchWindow(t *testing.T) { - first := item(KindRequestApproved, t0) - later := item(KindRequestRejected, t0.Add(40*time.Minute)) + first := item(KindQuarantineFlagged, t0) + later := item(KindTracksMissing, t0.Add(40*time.Minute)) cases := []struct { name string now time.Time @@ -63,7 +63,7 @@ func TestPlanUser_QuietBatchSendsNothing(t *testing.T) { func TestPlanUser_SummaryHourInUserTimezone(t *testing.T) { ny, err := time.LoadLocation("America/New_York") require.NoError(t, err) - arrived := []pendingItem{item(KindRequestCompleted, time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC))} + arrived := []pendingItem{item(KindNewMusic, time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC))} // 09:00 in New York in July is 13:00 UTC (EDT, UTC-4). cases := []struct { name string @@ -90,7 +90,7 @@ func TestPlanUser_SummaryHourInUserTimezone(t *testing.T) { func TestPlanUser_SummaryAcrossDST(t *testing.T) { ny, err := time.LoadLocation("America/New_York") require.NoError(t, err) - arrived := []pendingItem{item(KindRequestCompleted, time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))} + arrived := []pendingItem{item(KindNewMusic, time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))} // Clocks go back on 1 November 2026: 09:00 the day before is 13:00 UTC // (EDT), and 09:00 that day is 14:00 UTC (EST). before := groupState{LastSentAt: time.Date(2026, 10, 31, 13, 0, 0, 0, time.UTC)} @@ -102,7 +102,7 @@ func TestPlanUser_SummaryAcrossDST(t *testing.T) { // Spring forward, 8 March 2026: 02:00 does not exist. A summary hour of // 2 still goes out that day, once. gap := EmailSettings{SummaryHour: 2, BatchWindowMinutes: 60} - spring := []pendingItem{item(KindRequestCompleted, time.Date(2026, 3, 8, 0, 0, 0, 0, time.UTC))} + spring := []pendingItem{item(KindNewMusic, time.Date(2026, 3, 8, 0, 0, 0, 0, time.UTC))} at := time.Date(2026, 3, 8, 9, 0, 0, 0, time.UTC) // 05:00 EDT p = planUser(at, gap, ny, spring, allEmail(), groupState{}, groupState{LastSentAt: time.Date(2026, 3, 7, 7, 0, 0, 0, time.UTC)}) require.True(t, p.SummaryDue) @@ -112,10 +112,10 @@ func TestPlanUser_SummaryAcrossDST(t *testing.T) { func TestPlanUser_EmailOffAndStaleItemsAreSkippedNotSent(t *testing.T) { off := allEmail() - off[KindRequestRejected] = false + off[KindTracksMissing] = false items := []pendingItem{ - item(KindRequestRejected, t0), - item(KindRequestApproved, t0.Add(-8*24*time.Hour)), + item(KindTracksMissing, t0), + item(KindQuarantineFlagged, t0.Add(-8*24*time.Hour)), } p := planUser(t0.Add(2*time.Hour), digestCfg, time.UTC, items, off, groupState{}, groupState{}) require.Len(t, p.Skip, 2) @@ -132,28 +132,27 @@ func TestRetryDelay_DoublesToACap(t *testing.T) { } func TestRenderDigest_SummaryGroupsByArtist(t *testing.T) { - arrival := func(p Payload) pendingItem { - b, _ := json.Marshal(p.Map()) - return pendingItem{Kind: KindRequestCompleted, Payload: b} + scan := func(albums ...Arrival) pendingItem { + b, _ := json.Marshal(Payload{Count: int64(len(albums)), Albums: albums}.Map()) + return pendingItem{Kind: KindNewMusic, Payload: b} } items := []pendingItem{ - arrival(Payload{Name: "Moe Shop – WWW", Artist: "Moe Shop", Title: "WWW", AlbumID: "al-1"}), - arrival(Payload{Name: "Boards of Canada", Artist: "Boards of Canada", ArtistID: "ar-2"}), - arrival(Payload{Name: "Moe Shop – Pure", Artist: "Moe Shop", Title: "Pure", AlbumID: "al-3"}), - arrival(Payload{Name: "Tycho – Awake"}), // stored before Artist was recorded + scan(Arrival{Artist: "Mochi Shop", Title: "XYZ", ArtistID: "ar-1", AlbumID: "al-1"}, + Arrival{Artist: "Fields of Ontario", Title: "Geomantic", AlbumID: "al-2"}), + scan(Arrival{Artist: "Mochi Shop", Title: "Pure", ArtistID: "ar-1", AlbumID: "al-3"}), } e, err := renderDigest(EmailSummary, "alice", items, "https://music.example/") require.NoError(t, err) require.Equal(t, "Minstrel: new music in your library", e.Subject) - moe := strings.Index(e.Text, "Moe Shop") + moe := strings.Index(e.Text, "Mochi Shop") require.GreaterOrEqual(t, moe, 0) - require.Equal(t, moe, strings.LastIndex(e.Text, "Moe Shop\n"), "one heading per artist") - require.Less(t, moe, strings.Index(e.Text, "Boards of Canada"), "artists in the order they arrived") - require.Contains(t, e.Text, " - WWW\n https://music.example/albums/al-1") + require.Equal(t, moe, strings.LastIndex(e.Text, "Mochi Shop\n"), "one heading per artist, across scans") + require.Less(t, moe, strings.Index(e.Text, "Fields of Ontario"), "artists in the order they arrived") + require.Contains(t, e.Text, "Mochi Shop\n https://music.example/artists/ar-1") + require.Contains(t, e.Text, " - XYZ\n https://music.example/albums/al-1") require.Contains(t, e.Text, " - Pure\n https://music.example/albums/al-3") - require.Contains(t, e.Text, "Boards of Canada\n https://music.example/artists/ar-2") - require.Contains(t, e.Text, "Tycho\n - Awake") + require.Contains(t, e.Text, " - Geomantic\n https://music.example/albums/al-2") require.Contains(t, e.Text, "https://music.example/settings/notifications") require.Contains(t, e.HTML, `x", Reason: "dup"}.Map()) items := []pendingItem{ - {Kind: KindRequestApproved, Payload: []byte(`{"name":"WWW"}`)}, - {Kind: KindRequestRejected, Payload: b}, + {Kind: KindQuarantineFlagged, Payload: []byte(`{"name":"XYZ","actor":"Ann"}`)}, + {Kind: KindQuarantineFlagged, Payload: b}, } e, err := renderDigest(EmailBatch, "alice", items, "") require.NoError(t, err) require.Equal(t, "Minstrel: 2 updates", e.Subject) - require.Contains(t, e.Text, "- Request approved\n WWW is on its way.") + require.Contains(t, e.Text, "- Track flagged\n Ann flagged XYZ.") require.NotContains(t, e.Text, "http", "no public address: no links") require.Contains(t, e.Text, "Settings → Notifications") require.NotContains(t, e.HTML, " - {#if loadError} -

- Couldn't load AcoustID settings. - -

- {:else if overview === null} -

Loading AcoustID settings…

+ {#if loadError || overview === null} + {:else} {#if overview.ready && !overview.status.problem} diff --git a/web/src/lib/components/AcoustIDCard.test.ts b/web/src/lib/components/AcoustIDCard.test.ts index 45c7b610..8344d3e2 100644 --- a/web/src/lib/components/AcoustIDCard.test.ts +++ b/web/src/lib/components/AcoustIDCard.test.ts @@ -107,7 +107,7 @@ describe("AcoustIDCard", () => { expect(saveButton()).toHaveProperty("disabled", true); }); - // Rule 164: off, keyless or unreachable is a visible state, not a silent one. + // Off, keyless or unreachable is a visible state, not a silent one. test("says why it is not looking anything up", async () => { await renderCard( overview({ @@ -150,9 +150,9 @@ describe("AcoustIDCard", () => { vi.mocked(listUnsettledAcoustID).mockResolvedValue([ { track_id: "t1", - title: "WWW", - artist: "Moe Shop", - album: "WWW", + title: "XYZ", + artist: "Mochi Shop", + album: "XYZ", file_path: "/music/a.mp3", state: "ambiguous", best_score: 0.97, @@ -168,7 +168,7 @@ describe("AcoustIDCard", () => { details.open = true; await fireEvent(details, new Event("toggle")); const list = await screen.findByTestId("acoustid-unsettled"); - expect(list.textContent).toMatch(/WWW/); + expect(list.textContent).toMatch(/XYZ/); expect(list.textContent).toMatch(/2 recordings/); }); diff --git a/web/src/lib/components/AcquisitionCard.svelte b/web/src/lib/components/AcquisitionCard.svelte deleted file mode 100644 index bb1b4557..00000000 --- a/web/src/lib/components/AcquisitionCard.svelte +++ /dev/null @@ -1,166 +0,0 @@ - - -{#snippet addMenu(kind: 'search' | 'download', label: string)} -
- {#if adding === kind} -
- {#each choices[kind] as choice (choice.protocol)} - - {/each} - -
- {:else} - - {/if} -
-{/snippet} - -
- {#if loadError} -

- Couldn't load indexers and download clients. - -

- {:else if services === null} -

Loading indexers and download clients…

- {:else} - -

- {#if !canFetch} - No download client is switched on, so nothing can be downloaded. - {:else if !canSearch} - No indexer is switched on, so nothing new can be found. - {:else} - Music can be searched for and downloaded. - {/if} -

- -
- - {#each indexers as service (service.code)} - - {:else} -

No indexer yet. Prowlarr is the usual choice.

- {/each} - {#if searchingExchanges.length > 0} -

- Also searched: {searchingExchanges.map((s) => s.label).join(', ')}, under download clients. -

- {/if} - {@render addMenu('search', 'Add indexer')} -
-
- -
- - {#each clients as service (service.code)} - - {:else} -

No download client yet.

- {/each} - {@render addMenu('download', 'Add download client')} -
-
- {/if} -
diff --git a/web/src/lib/components/AcquisitionCard.test.ts b/web/src/lib/components/AcquisitionCard.test.ts deleted file mode 100644 index 3db6448f..00000000 --- a/web/src/lib/components/AcquisitionCard.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor, within } from '@testing-library/svelte'; -import type { AcquisitionService } from '#lib/api/admin.js'; - -vi.mock('#lib/api/admin.js', () => ({ - listAcquisitionServices: vi.fn(), - addAcquisitionService: vi.fn(), - updateAcquisitionService: vi.fn(), - removeAcquisitionService: vi.fn(), - testAcquisitionService: vi.fn(), - setAcquisitionSecret: vi.fn(), - clearAcquisitionSecret: vi.fn() -})); - -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import AcquisitionCard from './AcquisitionCard.svelte'; -import { - addAcquisitionService, - listAcquisitionServices, - setAcquisitionSecret, - testAcquisitionService, - updateAcquisitionService -} from '#lib/api/admin.js'; - -function service(over: Partial = {}): AcquisitionService { - return { - code: 'prowlarr', - kind: 'search', - protocol: 'prowlarr', - label: 'Prowlarr', - enabled: false, - base_url: '', - has_api_key: false, - has_password: false, - username: '', - category: '', - timeout_ms: 60000, - serves_search: true, - serves_downloads: true, - serves_enrichment: true, - local_path: '/downloads', - remote_path: '', - searches_per_hour: 120, - usable: false, - ...over - }; -} - -const exchange = (over: Partial = {}) => - service({ - code: 'exchange', - kind: 'download', - protocol: 'exchange', - label: 'FabledExchange', - category: 'minstrel', - searches_per_hour: 0, - ...over - }); - -afterEach(() => vi.clearAllMocks()); - -async function renderCard(services: AcquisitionService[]) { - vi.mocked(listAcquisitionServices).mockResolvedValue(services); - render(AcquisitionCard); - await screen.findByTestId('acquisition-health'); -} - -describe('AcquisitionCard', () => { - test('starts empty: nothing is seeded', async () => { - await renderCard([]); - expect(screen.getByText(/no indexer yet/i)).toBeInTheDocument(); - expect(screen.getByText(/no download client yet/i)).toBeInTheDocument(); - expect(screen.getByTestId('acquisition-health')).toHaveTextContent(/nothing can be downloaded/i); - }); - - test('adding offers the types each list takes', async () => { - await renderCard([]); - await fireEvent.click(screen.getByRole('button', { name: 'Add indexer' })); - const indexerChoices = within(screen.getByTestId('add-search')); - expect(indexerChoices.getByRole('button', { name: /prowlarr/i })).toBeInTheDocument(); - expect(indexerChoices.getByRole('button', { name: /torznab feed/i })).toBeInTheDocument(); - expect(indexerChoices.queryByRole('button', { name: /qbittorrent/i })).toBeNull(); - - vi.mocked(addAcquisitionService).mockResolvedValue(service()); - await fireEvent.click(indexerChoices.getByRole('button', { name: /prowlarr/i })); - expect(addAcquisitionService).toHaveBeenCalledWith('prowlarr'); - - await fireEvent.click(screen.getByRole('button', { name: 'Add download client' })); - const clientChoices = within(screen.getByTestId('add-download')); - expect(clientChoices.getByRole('button', { name: /qbittorrent/i })).toBeInTheDocument(); - expect(clientChoices.getByRole('button', { name: /fabledexchange/i })).toBeInTheDocument(); - }); - - test('an exchange sits under download clients with a switch per job; others have none', async () => { - await renderCard([ - service({ code: 'qbittorrent', kind: 'download', protocol: 'qbittorrent', label: 'qBittorrent' }), - exchange() - ]); - const clients = within(screen.getByTestId('download-clients')); - expect(clients.getAllByTestId('acquisition-service')).toHaveLength(2); - // Only the exchange carries the job switches. - expect(clients.getAllByTestId('exchange-jobs')).toHaveLength(1); - expect(clients.getByRole('checkbox', { name: /downloads what is grabbed/i })).toBeChecked(); - expect(clients.getByRole('checkbox', { name: /searches its dht index/i })).toBeChecked(); - expect(clients.getByRole('checkbox', { name: /checks a release/i })).toBeChecked(); - // qBittorrent asks for a username and a password; the exchange for an optional key. - expect(clients.getByText('Username')).toBeInTheDocument(); - expect(clients.getByText(/save password/i)).toBeInTheDocument(); - expect(clients.getByText(/save key/i)).toBeInTheDocument(); - }); - - test('an exchange searching is named under indexers too', async () => { - await renderCard([exchange({ usable: true, enabled: true, base_url: 'http://ex' })]); - expect(within(screen.getByTestId('indexers')).getByText(/also searched: fabledexchange/i)).toBeInTheDocument(); - expect(screen.getByTestId('acquisition-health')).toHaveTextContent(/searched for and downloaded/i); - }); - - test('switching a job off and saving sends the switches', async () => { - const ex = exchange({ base_url: 'http://ex' }); - await renderCard([ex]); - await fireEvent.click(screen.getByRole('checkbox', { name: /checks a release/i })); - vi.mocked(updateAcquisitionService).mockResolvedValue({ ...ex, serves_enrichment: false }); - await fireEvent.click(screen.getByRole('button', { name: /^save$/i })); - await waitFor(() => expect(updateAcquisitionService).toHaveBeenCalled()); - const [code, sent] = vi.mocked(updateAcquisitionService).mock.calls[0]; - expect(code).toBe('exchange'); - expect(sent).toMatchObject({ serves_enrichment: false, serves_search: true, serves_downloads: true }); - }); - - test('a refused setting is shown beside the form in the server’s words', async () => { - await renderCard([service({ base_url: 'http://p' })]); - await fireEvent.input(screen.getByRole('textbox', { name: /^name$/i }), { - target: { value: 'Mine' } - }); - vi.mocked(updateAcquisitionService).mockRejectedValue({ - code: 'invalid_setting', - message: 'Address: start with http:// or https://.', - status: 400 - }); - await fireEvent.click(screen.getByRole('button', { name: /^save$/i })); - expect(await screen.findByTestId('acquisition-problem')).toHaveTextContent( - 'Address: start with http:// or https://.' - ); - }); - - test('Test shows what the server found, and needs an address', async () => { - await renderCard([service({ code: 'a' }), service({ code: 'b', label: 'Second', base_url: 'http://p' })]); - const [noAddress, addressed] = screen.getAllByRole('button', { name: 'Test' }); - expect(noAddress).toBeDisabled(); - vi.mocked(testAcquisitionService).mockResolvedValue({ - ok: false, - detail: 'the API key was refused: HTTP 401. Check it on the service’s own settings page.' - }); - await fireEvent.click(addressed); - expect(testAcquisitionService).toHaveBeenCalledWith('b'); - expect(await screen.findByTestId('acquisition-test-result')).toHaveTextContent(/key was refused/i); - }); - - test('a key is sent write-only and never shown back', async () => { - await renderCard([service({ base_url: 'http://p', has_api_key: true })]); - expect(screen.getByLabelText(/replace the api key/i)).toHaveValue(''); - await fireEvent.input(screen.getByLabelText(/replace the api key/i), { target: { value: 'k2' } }); - vi.mocked(setAcquisitionSecret).mockResolvedValue(undefined); - await fireEvent.click(screen.getByRole('button', { name: /save key/i })); - await waitFor(() => expect(setAcquisitionSecret).toHaveBeenCalledWith('prowlarr', 'api-key', 'k2')); - }); -}); diff --git a/web/src/lib/components/AcquisitionServiceRow.svelte b/web/src/lib/components/AcquisitionServiceRow.svelte deleted file mode 100644 index 48f7df91..00000000 --- a/web/src/lib/components/AcquisitionServiceRow.svelte +++ /dev/null @@ -1,394 +0,0 @@ - - -
-
- -
- {#each jobs as job (job)} - {job} - {/each} - {#if service.usable} - On - {:else if service.enabled} - On, but no address - {:else} - Off - {/if} -
-
- -

{blurb[service.protocol]}

- -
- Connection -
- - - - - {#if isExchange} -
- What it does here - - - -
- {/if} - - {#if isQbit} - - {/if} - - {#if fetches} - - - - {/if} - - {#if searches} - - {/if} - - -
- -
- -
- - - {#if secretSet} - - {/if} -
- - {#if service.protocol === 'prowlarr'} - Prowlarr shows it under Settings → General. - {:else if isExchange} - Optional: only if your FabledExchange asks for one. Give Minstrel a key of its own there, - so it can be revoked on its own. - {:else if service.protocol === 'torznab'} - Optional: only if the feed asks for one. - {:else} - Empty if your WebUI does not ask for one. - {/if} - {secretSet ? 'One is saved.' : ''} Never shown again once saved. - -
-
- - {#if problem} -

{problem}

- {/if} - {#if result} -

- {result.detail} -

- {/if} - -
- {#if confirmRemove} - - Remove {service.label}? Minstrel forgets its address and credentials. - Nothing on the service itself changes. - - - - {:else} - - - - {/if} -
-
diff --git a/web/src/lib/components/AlbumCard.svelte b/web/src/lib/components/AlbumCard.svelte index 0273ccda..baf82efd 100644 --- a/web/src/lib/components/AlbumCard.svelte +++ b/web/src/lib/components/AlbumCard.svelte @@ -2,6 +2,7 @@ import type { AlbumRef, AlbumDetail } from '#lib/api/types.js'; import { api } from '#lib/api/client.js'; import { enqueueTracks, playQueue } from '#lib/player/store.svelte.js'; + import { playSource } from '#lib/player/playSource.js'; import { Play } from 'lucide-svelte'; import AlbumMenu from './AlbumMenu.svelte'; import CardActionCluster from './CardActionCluster.svelte'; @@ -20,7 +21,7 @@ e.preventDefault(); e.stopPropagation(); const detail = await api.get(`/api/albums/${album.id}`); - playQueue(detail.tracks, 0); + playQueue(detail.tracks, 0, { source: playSource.album(album.id) }); } diff --git a/web/src/lib/components/AlbumCard.test.ts b/web/src/lib/components/AlbumCard.test.ts index 7cb69f77..45607dba 100644 --- a/web/src/lib/components/AlbumCard.test.ts +++ b/web/src/lib/components/AlbumCard.test.ts @@ -39,10 +39,10 @@ import { enqueueTracks, playQueue } from '#lib/player/store.svelte.js'; const album: AlbumRef = { id: 'xyz', - title: 'Kind of Blue', - sort_title: 'Kind of Blue', - artist_id: 'm-davis', - artist_name: 'Miles Davis', + title: 'Kind of Grey', + sort_title: 'Kind of Grey', + artist_id: 'm-davies', + artist_name: 'Marlo Davies', year: 1959, track_count: 5, duration_sec: 2630, @@ -57,8 +57,8 @@ describe('AlbumCard', () => { const { container } = render(AlbumCard, { props: { album } }); const link = screen.getByRole('link'); expect(link).toHaveAttribute('href', '/albums/xyz'); - expect(link).toHaveTextContent('Kind of Blue'); - expect(link).toHaveTextContent('Miles Davis'); + expect(link).toHaveTextContent('Kind of Grey'); + expect(link).toHaveTextContent('Marlo Davies'); // The year is intentionally omitted from the Home tile — // dropped in the visual polish pass; the album detail page // still shows it. @@ -85,9 +85,9 @@ describe('AlbumCard', () => { test('+ queue button fetches album detail and calls enqueueTracks', async () => { const tracks: TrackRef[] = [ makeTrack({ - title: 'So What', - album_id: 'xyz', album_title: 'Kind of Blue', - artist_id: 'm-davis', artist_name: 'Miles Davis', + title: 'So Then', + album_id: 'xyz', album_title: 'Kind of Grey', + artist_id: 'm-davies', artist_name: 'Marlo Davies', duration_sec: 545 }) ]; @@ -106,9 +106,9 @@ describe('AlbumCard', () => { test('play overlay click fetches album detail and calls playQueue at index 0', async () => { const tracks: TrackRef[] = [ makeTrack({ - title: 'So What', - album_id: 'xyz', album_title: 'Kind of Blue', - artist_id: 'm-davis', artist_name: 'Miles Davis', + title: 'So Then', + album_id: 'xyz', album_title: 'Kind of Grey', + artist_id: 'm-davies', artist_name: 'Marlo Davies', duration_sec: 545 }) ]; @@ -116,15 +116,15 @@ describe('AlbumCard', () => { (api.get as ReturnType).mockResolvedValueOnce(detail); render(AlbumCard, { props: { album } }); - await fireEvent.click(screen.getByRole('button', { name: /play kind of blue/i })); + await fireEvent.click(screen.getByRole('button', { name: /play kind of grey/i })); expect(api.get).toHaveBeenCalledWith('/api/albums/xyz'); await Promise.resolve(); await Promise.resolve(); - expect(playQueue).toHaveBeenCalledWith(tracks, 0); + expect(playQueue).toHaveBeenCalledWith(tracks, 0, { source: 'album:xyz' }); }); test('renders the bottom-right kebab menu trigger', () => { render(AlbumCard, { props: { album } }); - expect(screen.getByRole('button', { name: /Album actions for Kind of Blue/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Album actions for Kind of Grey/i })).toBeInTheDocument(); }); }); diff --git a/web/src/lib/components/AlbumDrillDown.svelte b/web/src/lib/components/AlbumDrillDown.svelte new file mode 100644 index 00000000..fda2d12f --- /dev/null +++ b/web/src/lib/components/AlbumDrillDown.svelte @@ -0,0 +1,77 @@ + + +
+
+ + +
+

{title}

+ {#if query && !query.isPending && !failed} +

{plural(total, 'album', 'albums')}

+ {/if} +
+
+ + {#if failed} +

+ {failText} + +

+ {:else if !query || query.isPending} +

Loading…

+ {:else if albums.length === 0} + + {:else} +
+ {#each albums as album (album.id)} + + {/each} +
+ query?.fetchNextPage()} + {endLabel} + /> + {/if} +
diff --git a/web/src/lib/components/AlbumMenu.svelte b/web/src/lib/components/AlbumMenu.svelte index eade006f..5a71d7fb 100644 --- a/web/src/lib/components/AlbumMenu.svelte +++ b/web/src/lib/components/AlbumMenu.svelte @@ -1,145 +1,32 @@ - { menuOpen = false; addOpen = false; }} onkeydown={onKeydown} /> - -
- - - {#if menuOpen} - - - - {/if} - - {#if addOpen && cachedTracks} - - {/if} -
+ listAlbumTracks(albumId)} + {tracks} + {artistId} + {direction} +/> diff --git a/web/src/lib/components/AlphaLibrary.svelte b/web/src/lib/components/AlphaLibrary.svelte new file mode 100644 index 00000000..d93b088d --- /dev/null +++ b/web/src/lib/components/AlphaLibrary.svelte @@ -0,0 +1,120 @@ + + +
+
+
+

{title}

+ {#if !query.isPending && !failed} +

{plural(total, one, many)}

+ {/if} +
+ {#if items.length > 0} + + {/if} +
+ + {#if failed} + + {:else if showSkeleton.value && items.length === 0} +

Loading…

+ {:else if !query.isPending && total === 0} + + {#if user.value?.is_admin} + + {#snippet actions()} + + Run a scan + + {/snippet} + + {:else} + + {/if} + {:else if filter.trim() && filtered.length === 0} +

+ No {many} in your loaded library match + '{filter.trim()}'. + + Search the full library → + +

+ {:else} + query.fetchNextPage()} + {item} + /> + + query.fetchNextPage()} + endLabel="End of library" + /> + {/if} +
diff --git a/web/src/lib/components/ArtistCard.svelte b/web/src/lib/components/ArtistCard.svelte index 03ec5d9b..2c3c6566 100644 --- a/web/src/lib/components/ArtistCard.svelte +++ b/web/src/lib/components/ArtistCard.svelte @@ -3,6 +3,7 @@ import type { ArtistRef, TrackRef } from '#lib/api/types.js'; import { api } from '#lib/api/client.js'; import { playQueue, enqueueTracks } from '#lib/player/store.svelte.js'; + import { playSource } from '#lib/player/playSource.js'; import { Play } from 'lucide-svelte'; import ArtistMenu from './ArtistMenu.svelte'; import CardActionCluster from './CardActionCluster.svelte'; @@ -18,7 +19,7 @@ e.stopPropagation(); const tracks = await api.get(`/api/artists/${artist.id}/tracks`); if (tracks.length === 0) return; - playQueue(shuffled(tracks), 0); + playQueue(shuffled(tracks), 0, { source: playSource.artist(artist.id) }); } async function onAddToQueue(e: MouseEvent) { diff --git a/web/src/lib/components/ArtistCard.test.ts b/web/src/lib/components/ArtistCard.test.ts index 44fd8d9c..59af3b95 100644 --- a/web/src/lib/components/ArtistCard.test.ts +++ b/web/src/lib/components/ArtistCard.test.ts @@ -20,8 +20,8 @@ import { playQueue } from '#lib/player/store.svelte.js'; const artist: ArtistRef = { id: 'art-1', - name: 'Boards of Canada', - sort_name: 'Boards of Canada', + name: 'Fields of Ontario', + sort_name: 'Fields of Ontario', album_count: 5, cover_url: '/api/albums/cov-1/cover' }; @@ -48,13 +48,13 @@ describe('ArtistCard', () => { test('play overlay fetches tracks, shuffles, calls playQueue', async () => { const tracks: TrackRef[] = makeTracks(2, { album_id: 'al-1', album_title: 'X', - artist_id: 'art-1', artist_name: 'BoC', + artist_id: 'art-1', artist_name: 'FoO', duration_sec: 1 }); (api.get as ReturnType).mockResolvedValueOnce(tracks); render(ArtistCard, { props: { artist } }); - await fireEvent.click(screen.getByRole('button', { name: /play boards of canada/i })); + await fireEvent.click(screen.getByRole('button', { name: /play fields of ontario/i })); expect(api.get).toHaveBeenCalledWith('/api/artists/art-1/tracks'); await Promise.resolve(); await Promise.resolve(); @@ -70,22 +70,22 @@ describe('ArtistCard', () => { // Like button (LikeButton's aria-label is dynamic Like|Unlike). expect(screen.getByRole('button', { name: /^(Like|Unlike)$/ })).toBeInTheDocument(); // Add-to-queue button. - expect(screen.getByRole('button', { name: /Add Boards of Canada to queue/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Add Fields of Ontario to queue/i })).toBeInTheDocument(); }); test('renders the bottom-right kebab', () => { render(ArtistCard, { props: { artist } }); - expect(screen.getByRole('button', { name: /Artist actions for Boards of Canada/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Artist actions for Fields of Ontario/i })).toBeInTheDocument(); }); test('+queue button calls listArtistTracks then enqueueTracks', async () => { const fakeTracks = [ - makeTrack({ artist_id: 'art-1', artist_name: 'BoC' }) + makeTrack({ artist_id: 'art-1', artist_name: 'FoO' }) ]; const { listArtistTracks } = await import('#lib/api/artists.js'); (listArtistTracks as unknown as ReturnType).mockResolvedValueOnce(fakeTracks); render(ArtistCard, { props: { artist } }); - const btn = screen.getByRole('button', { name: /Add Boards of Canada to queue/i }); + const btn = screen.getByRole('button', { name: /Add Fields of Ontario to queue/i }); await fireEvent.click(btn); // Allow promise microtask to flush. await new Promise((r) => setTimeout(r, 0)); diff --git a/web/src/lib/components/ArtistMenu.svelte b/web/src/lib/components/ArtistMenu.svelte index 4018ea50..d2cd8fa1 100644 --- a/web/src/lib/components/ArtistMenu.svelte +++ b/web/src/lib/components/ArtistMenu.svelte @@ -1,14 +1,9 @@ - { menuOpen = false; addOpen = false; }} onkeydown={onKeydown} /> - -
- - - {#if menuOpen} - - - - {/if} - - {#if addOpen && cachedTracks} - - {/if} -
+ listArtistTracks(artistId)} + {tracks} + {direction} +/> diff --git a/web/src/lib/components/CollectionMenu.svelte b/web/src/lib/components/CollectionMenu.svelte new file mode 100644 index 00000000..e6098078 --- /dev/null +++ b/web/src/lib/components/CollectionMenu.svelte @@ -0,0 +1,115 @@ + + + (addOpen = false)} +> + + + + + {#if artistId} + + + {/if} + + {#snippet after()} + {#if addOpen && cache} + + {/if} + {/snippet} + diff --git a/web/src/lib/components/CollectionRail.svelte b/web/src/lib/components/CollectionRail.svelte new file mode 100644 index 00000000..c023cfc5 --- /dev/null +++ b/web/src/lib/components/CollectionRail.svelte @@ -0,0 +1,21 @@ + + + diff --git a/web/src/lib/components/CompactTrackCard.svelte b/web/src/lib/components/CompactTrackCard.svelte index 5c15d77c..68d77472 100644 --- a/web/src/lib/components/CompactTrackCard.svelte +++ b/web/src/lib/components/CompactTrackCard.svelte @@ -15,17 +15,20 @@ let { track, sectionTracks, - index + index, + source }: { track: TrackRef; sectionTracks: TrackRef[]; index: number; + /** Where a play started here began, in the playSource vocabulary. */ + source?: string; } = $props(); const cover = $derived(coverUrl(track.album_id)); function onClick() { - playQueue(sectionTracks, index); + playQueue(sectionTracks, index, { source }); } function onAddToQueue(e: MouseEvent) { diff --git a/web/src/lib/components/CompactTrackCard.test.ts b/web/src/lib/components/CompactTrackCard.test.ts index 8366c305..be953faa 100644 --- a/web/src/lib/components/CompactTrackCard.test.ts +++ b/web/src/lib/components/CompactTrackCard.test.ts @@ -41,7 +41,7 @@ describe('CompactTrackCard', () => { props: { track: tracks[1], sectionTracks: tracks, index: 1 } }); await fireEvent.click(screen.getByRole('button', { name: /play second/i })); - expect(playQueue).toHaveBeenCalledWith(tracks, 1); + expect(playQueue).toHaveBeenCalledWith(tracks, 1, { source: undefined }); }); test('renders title and artist name', () => { diff --git a/web/src/lib/components/ConfirmModal.svelte b/web/src/lib/components/ConfirmModal.svelte new file mode 100644 index 00000000..53346aa3 --- /dev/null +++ b/web/src/lib/components/ConfirmModal.svelte @@ -0,0 +1,58 @@ + + + +
{@render children()}
+
+ + +
+
diff --git a/web/src/lib/components/ConfirmModal.test.ts b/web/src/lib/components/ConfirmModal.test.ts new file mode 100644 index 00000000..06508f64 --- /dev/null +++ b/web/src/lib/components/ConfirmModal.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test, vi } from 'vitest'; +import { render, screen, fireEvent } from '@testing-library/svelte'; +import { createRawSnippet } from 'svelte'; +import ConfirmModal from './ConfirmModal.svelte'; +import { offendingSources } from '#lib/testing/sourceGuard.js'; + +const body = createRawSnippet(() => ({ render: () => `Its songs stay in your library.` })); + +// The children Snippet isn't inferable through testing-library's render. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AnyProps = any; + +function show(extra: Record = {}) { + const onCancel = vi.fn(); + const onConfirm = vi.fn(); + render(ConfirmModal, { + props: { + title: 'Delete this playlist?', + open: true, + confirmLabel: 'Delete', + onCancel, + onConfirm, + children: body, + ...extra + } as AnyProps + }); + return { onCancel, onConfirm }; +} + +describe('ConfirmModal', () => { + test('says what goes, and acts only on the confirm button', async () => { + const { onCancel, onConfirm } = show(); + expect(screen.getByRole('dialog', { name: 'Delete this playlist?' })).toBeInTheDocument(); + expect(screen.getByText('Its songs stay in your library.')).toBeInTheDocument(); + await fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(onCancel).toHaveBeenCalledOnce(); + expect(onConfirm).not.toHaveBeenCalled(); + await fireEvent.click(screen.getByRole('button', { name: 'Delete' })); + expect(onConfirm).toHaveBeenCalledOnce(); + }); + + test('the confirm button wears the destructive action colour, not the error colour', () => { + show(); + const confirm = screen.getByRole('button', { name: 'Delete' }); + expect(confirm.className).toContain('bg-action-destructive'); + }); + + test('while the act runs, both buttons are off and the confirm says so', () => { + show({ busy: true, busyLabel: 'Deleting…' }); + expect(screen.getByRole('button', { name: 'Deleting…' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled(); + }); +}); + +// Asking before an act that can't be undone goes through ConfirmModal, and an +// error goes to a toast. The browser's own confirm() and alert() boxes look +// like neither app and can't be styled or tested, so no page calls them. +const NATIVE = /(? { + test('no page calls the browser confirm() or alert()', () => { + expect(offendingSources([NATIVE])).toEqual([]); + }); +}); diff --git a/web/src/lib/components/Cover.svelte b/web/src/lib/components/Cover.svelte index b4cdec4c..38a82264 100644 --- a/web/src/lib/components/Cover.svelte +++ b/web/src/lib/components/Cover.svelte @@ -1,6 +1,6 @@ - - - -
-
- {#if imageUrl && !imageFailed} - (imageFailed = true)} - /> - {:else} - - {/if} -
- -
-
{title}
- {#if subtitle} -
{subtitle}
- {/if} - {#if attribution} -
- {attribution} -
- {/if} -
- {#if cardState === 'kept'} - Kept - {:else if cardState === 'snoozed'} - Not right now - {/if} -
-
- -
- {#if cardState === 'snoozed'} - - {:else if cardState === 'requestable'} -
- - {#if onSnooze} - - - {/if} -
- {:else if cardState === 'kept'} - - {:else} - - {/if} -
-
- - diff --git a/web/src/lib/components/DiscoverResultCard.test.ts b/web/src/lib/components/DiscoverResultCard.test.ts deleted file mode 100644 index e22ad06f..00000000 --- a/web/src/lib/components/DiscoverResultCard.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/svelte'; -import DiscoverResultCard from './DiscoverResultCard.svelte'; - -afterEach(() => vi.clearAllMocks()); - -describe('DiscoverResultCard', () => { - test('requestable state renders Request button and calls onRequest on click', async () => { - const onRequest = vi.fn(); - render(DiscoverResultCard, { - props: { - kind: 'artist', - title: 'Boards of Canada', - state: 'requestable', - onRequest, - }, - }); - // aria-label includes the title, so the accessible name is - // "Request Boards of Canada". - const btn = screen.getByRole('button', { - name: /request boards of canada/i, - }); - expect(btn).not.toBeDisabled(); - await fireEvent.click(btn); - expect(onRequest).toHaveBeenCalledOnce(); - }); - - test('kept state renders disabled "In library" button + Kept pill with role=status', () => { - render(DiscoverResultCard, { - props: { - kind: 'album', - title: 'Music Has The Right To Children', - state: 'kept', - }, - }); - expect(screen.getByRole('button', { name: /in library/i })).toBeDisabled(); - // Kept pill is exposed as a status region so SR users hear it when it - // appears. - const status = screen.getByRole('status'); - expect(status).toBeInTheDocument(); - expect(status.textContent).toMatch(/kept/i); - }); - - test('requested state renders disabled "Requested" button', () => { - render(DiscoverResultCard, { - props: { - kind: 'track', - title: 'Roygbiv', - state: 'requested', - }, - }); - expect(screen.getByRole('button', { name: /requested/i })).toBeDisabled(); - }); - - test('does not call onRequest when state is not requestable', async () => { - const onRequest = vi.fn(); - render(DiscoverResultCard, { - props: { - kind: 'album', - title: 'Geogaddi', - state: 'kept', - onRequest, - }, - }); - // Button is disabled — the test still verifies onRequest isn't called even - // if a click slips through (jsdom does not enforce :disabled at fireEvent - // level). - const btn = screen.getByRole('button'); - await fireEvent.click(btn); - expect(onRequest).not.toHaveBeenCalled(); - }); - - // The layout discipline (reserved badge slot + bottom-anchored actions) is - // not asserted here: vitest's @testing-library/svelte renderer does not - // inject the component's scoped diff --git a/web/src/lib/components/PlaylistCard.test.ts b/web/src/lib/components/PlaylistCard.test.ts index 800da1ed..dfeb3153 100644 --- a/web/src/lib/components/PlaylistCard.test.ts +++ b/web/src/lib/components/PlaylistCard.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test, vi, beforeEach } from 'vitest'; import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; import PlaylistCard from './PlaylistCard.svelte'; +import { washTone } from '#lib/playlists/shelf.js'; import type { Playlist, PlaylistDetail } from '#lib/api/types.js'; vi.mock('#lib/auth/store.svelte.js', () => ({ @@ -75,6 +76,11 @@ vi.mock('#lib/api/playlists.js', () => ({ refreshSystem: vi.fn().mockResolvedValue({ playlist_id: 'p-1', track_count: 5, track_ids: ['t-1'] }) })); +vi.mock('#lib/media/dominantColor.js', () => ({ + dominantColorFromUrl: vi.fn().mockResolvedValue({ r: 90, g: 40, b: 130 }), + rgbToCssString: ({ r, g, b }: { r: number; g: number; b: number }) => `rgb(${r} ${g} ${b})` +})); + vi.mock('#lib/player/store.svelte.js', () => ({ playQueue: vi.fn() })); @@ -266,6 +272,7 @@ describe('PlaylistCard', () => { ...base, kind: 'system', system_variant: 'for_you', + refreshable: true, name: 'For You' }; render(PlaylistCard, { props: { playlist: forYouPlaylist } }); @@ -280,6 +287,34 @@ describe('PlaylistCard', () => { ); }); + test('genre-mix play fetches that playlist by id, tagged genre_mix', async () => { + // Several genre mixes per user: the variant alone can't address one, + // so the card plays the exact playlist it shows. + const { getPlaylist, systemShuffle } = await import('#lib/api/playlists.js'); + const { playQueue } = await import('#lib/player/store.svelte.js'); + vi.mocked(getPlaylist).mockClear(); + vi.mocked(systemShuffle).mockClear(); + const jazzMix: Playlist = { + ...base, + id: 'gm-jazz', + kind: 'system', + system_variant: 'genre_mix', + refreshable: false, + name: 'Jazz mix' + }; + render(PlaylistCard, { props: { playlist: jazzMix } }); + await fireEvent.click(screen.getByLabelText(/Play Jazz mix/i)); + await new Promise(resolve => setTimeout(resolve, 10)); + + expect(getPlaylist).toHaveBeenCalledWith('gm-jazz'); + expect(systemShuffle).not.toHaveBeenCalled(); + expect(playQueue).toHaveBeenCalledWith( + expect.any(Array), + 0, + expect.objectContaining({ source: 'genre_mix' }) + ); + }); + test('user-playlist play uses getPlaylist + plain playQueue (no source)', async () => { const { getPlaylist, systemShuffle } = await import('#lib/api/playlists.js'); const { playQueue } = await import('#lib/player/store.svelte.js'); @@ -306,4 +341,57 @@ describe('PlaylistCard', () => { expect(getPlaylist).toHaveBeenCalledWith('p-1'); expect(playQueue).toHaveBeenCalled(); }); + + describe('home shelf shapes', () => { + const mix: Playlist = { + ...base, + name: 'For You', + kind: 'system', + system_variant: 'for_you', + refreshable: true, + description: 'Built around the songs you play most', + cover_url: '/api/playlists/p-1/cover' + }; + + test('a wide card shows its lead album, not the collage, and says what the mix is built from', () => { + const { container } = render(PlaylistCard, { props: { playlist: mix, shape: 'wide', covers: ['al-7'] } }); + expect(container.querySelector('[data-shape="wide"] img')!.getAttribute('src')).toBe('/api/albums/al-7/cover'); + expect(screen.getByText('Built around the songs you play most')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Play For You' })).toBeInTheDocument(); + }); + + test("a wide card for someone's own playlist shows its size instead", () => { + render(PlaylistCard, { props: { playlist: base, shape: 'wide' } }); + expect(screen.getByText(/12\s+tracks/)).toBeInTheDocument(); + }); + + test('a wide card takes the colour of its lead cover, toned for its text', async () => { + const { container } = render(PlaylistCard, { props: { playlist: mix, shape: 'wide', covers: ['al-7'] } }); + const card = container.querySelector('[data-shape="wide"] a') as HTMLElement; + const { r, g, b } = washTone({ r: 90, g: 40, b: 130 }); + await waitFor(() => expect(card.style.getPropertyValue('--wash')).toBe(`rgb(${r} ${g} ${b})`)); + }); + + test('the shelf heading can carry the refresh line instead of the tile', () => { + render(PlaylistCard, { + props: { playlist: { ...mix, created_at: new Date().toISOString() }, shape: 'wide', showMeta: false } + }); + expect(screen.queryByText(/Refreshed/)).toBeNull(); + }); + + test('a Songs like circle is labelled by its artist', () => { + const sl: Playlist = { ...base, name: 'Songs like Low Tide Choir', kind: 'system', system_variant: 'songs_like_artist' }; + const { container } = render(PlaylistCard, { props: { playlist: sl, shape: 'round', covers: ['al-2'] } }); + expect(screen.getByText('Low Tide Choir')).toBeInTheDocument(); + expect(container.querySelector('[data-shape="round"] .rounded-full img')!.getAttribute('src')).toBe('/api/albums/al-2/cover'); + }); + + test('a genre band names the genre and fans out the covers it was given', () => { + const g: Playlist = { ...base, name: 'Jazz mix', kind: 'system', system_variant: 'genre_mix' }; + const { container } = render(PlaylistCard, { props: { playlist: g, shape: 'band', covers: ['a', 'b', 'c'] } }); + expect(screen.getByText('Jazz')).toBeInTheDocument(); + const fan = Array.from(container.querySelectorAll('.fan img')).map((i) => i.getAttribute('src')); + expect(fan).toEqual(['/api/albums/a/cover', '/api/albums/b/cover', '/api/albums/c/cover']); + }); + }); }); diff --git a/web/src/lib/components/PlaylistPlaceholderCard.svelte b/web/src/lib/components/PlaylistPlaceholderCard.svelte index 090b8539..7771a5fe 100644 --- a/web/src/lib/components/PlaylistPlaceholderCard.svelte +++ b/web/src/lib/components/PlaylistPlaceholderCard.svelte @@ -3,12 +3,16 @@ let { label, - variant = 'pending' + variant = 'pending', + shape = 'square' }: { /** Card title (e.g. "For You" or "Songs like…"). */ label: string; /** Drives copy + animation. */ variant?: 'building' | 'failed' | 'pending' | 'seed-needed'; + /** Matches the shelf it stands in for, so a mix arriving does not + change the shelf's shape (see PlaylistCard's shapes). */ + shape?: 'square' | 'wide' | 'round'; } = $props(); const copy = $derived.by(() => { @@ -30,12 +34,35 @@ ); -
-
- +{#if shape === 'wide'} +
+
+ +
+
+
{label}
+
{copy}
+
-
-
{label}
-
{copy}
+{:else} +
+
+ +
+
+
{label}
+
{copy}
+
-
+{/if} diff --git a/web/src/lib/components/PlaylistPlaceholderCard.test.ts b/web/src/lib/components/PlaylistPlaceholderCard.test.ts index 1d92a4cb..b0c7ec9f 100644 --- a/web/src/lib/components/PlaylistPlaceholderCard.test.ts +++ b/web/src/lib/components/PlaylistPlaceholderCard.test.ts @@ -2,35 +2,21 @@ import { describe, test, expect } from 'vitest'; import { render, screen } from '@testing-library/svelte'; import PlaylistPlaceholderCard from './PlaylistPlaceholderCard.svelte'; +// A placeholder names the mix and says why it is not there yet. It pulses +// while the mix is still coming, and not once it has failed or needs more +// listening. describe('PlaylistPlaceholderCard', () => { - test('renders label', () => { - render(PlaylistPlaceholderCard, { props: { label: 'For You', variant: 'pending' } }); + test.each([ + ['pending', undefined, /within 24h/i, true], + ['building', 'building', /Building your daily mix/i, true], + ['failed', 'failed', /Couldn.t build this mix/i, false], + ['seed-needed', 'seed-needed', /Listen to more variety/i, false] + ] as const)('%s', (shown, variant, copy, pulses) => { + const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You', variant } }); expect(screen.getByText('For You')).toBeInTheDocument(); - }); - - test('building variant shows building copy and pulses', () => { - const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You', variant: 'building' } }); - expect(screen.getByText(/Building your daily mix/i)).toBeInTheDocument(); - const cover = container.querySelector('[data-variant="building"] .aspect-square'); - expect(cover?.className).toMatch(/animate-pulse/); - }); - - test('failed variant shows failure copy and does NOT pulse', () => { - const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You', variant: 'failed' } }); - expect(screen.getByText(/Couldn.t build this mix/i)).toBeInTheDocument(); - const cover = container.querySelector('[data-variant="failed"] .aspect-square'); - expect(cover?.className).not.toMatch(/animate-pulse/); - }); - - test('seed-needed variant shows variety copy', () => { - render(PlaylistPlaceholderCard, { props: { label: 'Songs like…', variant: 'seed-needed' } }); - expect(screen.getByText(/Listen to more variety/i)).toBeInTheDocument(); - }); - - test('pending variant (default) shows within-24h copy and pulses', () => { - const { container } = render(PlaylistPlaceholderCard, { props: { label: 'For You' } }); - expect(screen.getByText(/within 24h/i)).toBeInTheDocument(); - const cover = container.querySelector('[data-variant="pending"] .aspect-square'); - expect(cover?.className).toMatch(/animate-pulse/); + expect(screen.getByText(copy)).toBeInTheDocument(); + const cover = container.querySelector(`[data-variant="${shown}"] .aspect-square`); + expect(cover).not.toBeNull(); + expect(/animate-pulse/.test(cover!.className)).toBe(pulses); }); }); diff --git a/web/src/lib/components/PlaylistTrackRow.test.ts b/web/src/lib/components/PlaylistTrackRow.test.ts index 762bb22f..8f9e7c27 100644 --- a/web/src/lib/components/PlaylistTrackRow.test.ts +++ b/web/src/lib/components/PlaylistTrackRow.test.ts @@ -36,9 +36,9 @@ const live: PlaylistTrack = { track_id: 't-1', album_id: 'a-1', artist_id: 'ar-1', - title: 'Roygbiv', - artist_name: 'Boards of Canada', - album_title: 'MHTRTC', + title: 'Prismatic', + artist_name: 'Fields of Ontario', + album_title: 'MHTRTW', duration_sec: 137, stream_url: '/api/tracks/t-1/stream', added_at: '', @@ -69,7 +69,7 @@ describe('PlaylistTrackRow', () => { render(PlaylistTrackRow, { props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } }); - expect(screen.getByText('Roygbiv')).toBeInTheDocument(); + expect(screen.getByText('Prismatic')).toBeInTheDocument(); expect(screen.getByText('2:17')).toBeInTheDocument(); }); @@ -79,7 +79,7 @@ describe('PlaylistTrackRow', () => { }); expect(screen.getByLabelText(/reorder track/i)).toBeInTheDocument(); expect( - screen.getByLabelText(/Remove Roygbiv from playlist/i) + screen.getByLabelText(/Remove Prismatic from playlist/i) ).toBeInTheDocument(); }); @@ -89,35 +89,27 @@ describe('PlaylistTrackRow', () => { }); expect(screen.queryByLabelText(/reorder track/i)).not.toBeInTheDocument(); expect( - screen.queryByLabelText(/Remove Roygbiv from playlist/i) + screen.queryByLabelText(/Remove Prismatic from playlist/i) ).not.toBeInTheDocument(); }); - test('ArrowDown on the reorder handle calls onMove(pos, pos+1)', async () => { + test.each([ + ['ArrowDown', 3], + ['ArrowUp', 1] + ])('%s on the reorder handle moves the row one place', async (key, to) => { const onMove = vi.fn(); render(PlaylistTrackRow, { props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn(), onMove } }); - const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: 'ArrowDown' }); - expect(onMove).toHaveBeenCalledWith(2, 3); - }); - - test('ArrowUp on the reorder handle calls onMove(pos, pos-1)', async () => { - const onMove = vi.fn(); - render(PlaylistTrackRow, { - props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn(), onMove } - }); - const handle = screen.getByLabelText(/reorder track/i); - await fireEvent.keyDown(handle, { key: 'ArrowUp' }); - expect(onMove).toHaveBeenCalledWith(2, 1); + await fireEvent.keyDown(screen.getByLabelText(/reorder track/i), { key }); + expect(onMove).toHaveBeenCalledWith(2, to); }); test('greyed-out + strikethrough when track_id is null', () => { render(PlaylistTrackRow, { props: { row: removed, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } }); - const titleEl = screen.getByText('Roygbiv'); + const titleEl = screen.getByText('Prismatic'); expect(titleEl.className).toContain('line-through'); }); @@ -126,7 +118,7 @@ describe('PlaylistTrackRow', () => { render(PlaylistTrackRow, { props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay } }); - await fireEvent.click(screen.getByText('Roygbiv')); + await fireEvent.click(screen.getByText('Prismatic')); expect(onPlay).toHaveBeenCalledWith(2); }); @@ -137,7 +129,7 @@ describe('PlaylistTrackRow', () => { props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } }); expect(screen.getByText(/file missing/i)).toBeTruthy(); - expect(screen.getByText('Roygbiv').className).not.toContain('line-through'); + expect(screen.getByText('Prismatic').className).not.toContain('line-through'); }); test('clicking a missing-file row does not play it', async () => { @@ -145,7 +137,7 @@ describe('PlaylistTrackRow', () => { render(PlaylistTrackRow, { props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay } }); - await fireEvent.click(screen.getByText('Roygbiv')); + await fireEvent.click(screen.getByText('Prismatic')); expect(onPlay).not.toHaveBeenCalled(); }); @@ -154,6 +146,6 @@ describe('PlaylistTrackRow', () => { render(PlaylistTrackRow, { props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } }); - expect(screen.getByLabelText(/remove roygbiv from playlist/i)).toBeTruthy(); + expect(screen.getByLabelText(/remove prismatic from playlist/i)).toBeTruthy(); }); }); diff --git a/web/src/lib/components/PublicAddressCard.svelte b/web/src/lib/components/PublicAddressCard.svelte index feb2ed72..0bbc8f23 100644 --- a/web/src/lib/components/PublicAddressCard.svelte +++ b/web/src/lib/components/PublicAddressCard.svelte @@ -1,61 +1,33 @@ - {#if loadError} -

- Couldn't load the public address. - -

- {:else if saved === null} -

Loading…

+ {#if f.loadError || f.saved === null} + {:else} - - {#if here && value.trim() !== here} + {#if here && f.form?.trim() !== here} - + {/if} - {#if !saved} + {#if !f.saved?.public_url}

Not set, so password-reset emails are not being sent. diff --git a/web/src/lib/components/QueueTrackRow.svelte b/web/src/lib/components/QueueTrackRow.svelte index 095955ee..c3841f99 100644 --- a/web/src/lib/components/QueueTrackRow.svelte +++ b/web/src/lib/components/QueueTrackRow.svelte @@ -2,7 +2,8 @@ import { GripVertical, X } from 'lucide-svelte'; import type { TrackRef } from '#lib/api/types.js'; import { playFromQueueIndex, removeFromQueue, moveQueueItem } from '#lib/player/store.svelte.js'; - import { coverUrl, FALLBACK_COVER } from '#lib/media/covers.js'; + import { coverUrl } from '#lib/media/covers.js'; + import Cover from './Cover.svelte'; import { reorderDrag } from './reorder-drag'; import LikeButton from './LikeButton.svelte'; @@ -58,12 +59,9 @@ shadow is what keeps the glyph readable over pale covers without one. -->

- ((e.currentTarget as HTMLImageElement).src = FALLBACK_COVER)} - class="h-10 w-10 rounded object-cover" - /> +
+ +
-

- {:else if form === null} -

Loading…

- {:else} - - - - - - hours - - - - - {#if saved && saved.unnameable_albums > 0} - -

- {plural(saved.unnameable_albums, 'album has', 'albums have')} missing files but no MusicBrainz ID, - so {saved.unnameable_albums === 1 ? 'it' : 'they'} can't be wanted. Tag and re-scan to fix. -

- {/if} -
- -
- {/if} - diff --git a/web/src/lib/components/ReacquisitionSettingsCard.test.ts b/web/src/lib/components/ReacquisitionSettingsCard.test.ts deleted file mode 100644 index 29ecd8f9..00000000 --- a/web/src/lib/components/ReacquisitionSettingsCard.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; -import type { ReacquisitionSettings } from '#lib/api/admin.js'; -import { ERROR_COPY } from '#lib/api/error-copy.js'; - -vi.mock('#lib/api/admin.js', () => ({ - getReacquisitionSettings: vi.fn(), - updateReacquisitionSettings: vi.fn() -})); - -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import ReacquisitionSettingsCard from './ReacquisitionSettingsCard.svelte'; -import { getReacquisitionSettings, updateReacquisitionSettings } from '#lib/api/admin.js'; -import { pushToast } from '#lib/stores/toast.svelte.js'; - -const base: ReacquisitionSettings = { - enabled: true, - grace_hours: 24, - max_per_pass: 20, - unnameable_albums: 0 -}; - -afterEach(() => vi.clearAllMocks()); - -async function renderCard(over: Partial = {}) { - vi.mocked(getReacquisitionSettings).mockResolvedValue({ ...base, ...over }); - const r = render(ReacquisitionSettingsCard); - await waitFor(() => expect(getReacquisitionSettings).toHaveBeenCalled()); - return r; -} - -describe('ReacquisitionSettingsCard', () => { - // Searching and retrying belong to the wanted list's search schedule, so - // the card holds no retry policy of its own. - test('has no retry or approval settings', async () => { - await renderCard(); - await screen.findByRole('spinbutton', { name: /wait before wanting it back/i }); - expect(screen.queryByText(/attempts/i)).toBeNull(); - expect(screen.queryByText(/retry/i)).toBeNull(); - expect(screen.queryByText(/without approval/i)).toBeNull(); - }); - - // Saving an unchanged form would be a pointless round-trip, and a live Save - // button invites an admin to wonder whether anything happened. - test('save is disabled until something changes', async () => { - await renderCard(); - const save = await screen.findByRole('button', { name: /save/i }); - expect(save).toHaveProperty('disabled', true); - - const grace = screen.getByRole('spinbutton', { name: /wait before wanting it back/i }); - await fireEvent.input(grace, { target: { value: '48' } }); - await waitFor(() => expect(save).toHaveProperty('disabled', false)); - }); - - test('saving sends the edited values', async () => { - vi.mocked(updateReacquisitionSettings).mockResolvedValue({ ...base, grace_hours: 48 }); - await renderCard(); - - const grace = screen.getByRole('spinbutton', { name: /wait before wanting it back/i }); - await fireEvent.input(grace, { target: { value: '48' } }); - await fireEvent.click(await screen.findByRole('button', { name: /save/i })); - - await waitFor(() => - expect(updateReacquisitionSettings).toHaveBeenCalledWith( - expect.objectContaining({ grace_hours: 48 }) - ) - ); - }); - - // The server names the offending field ("grace_hours must be 1-720"); a - // generic "couldn't save" would throw that away. - // - // Rejects with what api.put actually throws — a plain {code, message, status} - // object, not an Error. Rejecting with an Error, which no code path - // produces, would let this pass while the card discarded every server - // message. - test('a rejected save surfaces the server message', async () => { - const message = 'grace_hours must be 1-720'; - vi.mocked(updateReacquisitionSettings).mockRejectedValue({ - code: 'invalid_setting', - message, - status: 400 - }); - await renderCard(); - - const grace = screen.getByRole('spinbutton', { name: /wait before wanting it back/i }); - await fireEvent.input(grace, { target: { value: '900' } }); - await fireEvent.click(await screen.findByRole('button', { name: /save/i })); - - await waitFor(() => - expect(pushToast).toHaveBeenCalledWith(`${ERROR_COPY.invalid_setting} ${message}`, 'error') - ); - }); - - // Without this an admin watches those albums never get wanted and - // reasonably concludes the feature is broken. - test('unnameable albums are called out with the reason', async () => { - await renderCard({ unnameable_albums: 3 }); - await waitFor(() => expect(screen.getByText(/no\s+MusicBrainz ID/i)).toBeTruthy()); - expect(screen.getByText(/3\s+albums have/i)).toBeTruthy(); - }); - - test('no warning when every missing album is identifiable', async () => { - await renderCard({ unnameable_albums: 0 }); - await screen.findByRole('spinbutton', { name: /wait before wanting it back/i }); - expect(screen.queryByText(/MusicBrainz ID/i)).toBeNull(); - }); - - test('a failed load offers a retry rather than an empty card', async () => { - vi.mocked(getReacquisitionSettings).mockRejectedValue(new Error('nope')); - render(ReacquisitionSettingsCard); - await waitFor(() => - expect(screen.getByText(/couldn't load re-acquisition settings/i)).toBeTruthy() - ); - expect(screen.getByRole('button', { name: /try again/i })).toBeTruthy(); - }); -}); diff --git a/web/src/lib/components/RecommendationMetrics.svelte b/web/src/lib/components/RecommendationMetrics.svelte index b2980e1c..ae09f493 100644 --- a/web/src/lib/components/RecommendationMetrics.svelte +++ b/web/src/lib/components/RecommendationMetrics.svelte @@ -83,7 +83,10 @@ {#if $metrics.isPending}

Loading…

{:else if $metrics.isError} -

Couldn't load metrics.

+ {:else if $metrics.data && ($metrics.data.groups.length > 0 || $metrics.data.baseline)} {@const baseline = $metrics.data.baseline} {#if baseline} diff --git a/web/src/lib/components/RecommendationMetrics.test.ts b/web/src/lib/components/RecommendationMetrics.test.ts index d3a7d465..ff3ee7b3 100644 --- a/web/src/lib/components/RecommendationMetrics.test.ts +++ b/web/src/lib/components/RecommendationMetrics.test.ts @@ -36,7 +36,7 @@ describe('RecommendationMetrics (Library › Your listening)', () => { ...over }); - test('breakdown rows are collapsed by default and expand on toggle (#1249/#1270)', async () => { + test('breakdown rows are collapsed by default and expand on toggle', async () => { metricsMock.data = { window_days: 30, baseline: metric('manual', 'Manual library plays', { plays: 100 }), diff --git a/web/src/lib/components/ReleaseProfilesCard.svelte b/web/src/lib/components/ReleaseProfilesCard.svelte deleted file mode 100644 index 9bb6fdd6..00000000 --- a/web/src/lib/components/ReleaseProfilesCard.svelte +++ /dev/null @@ -1,233 +0,0 @@ - - -{#snippet editor()} -
- - -
- Kinds of release -
- {#each primaryTypes as t (t)} - - {/each} -
-
- -
- Also allow - - Leave these unticked for studio releases only. A live album is wanted only when Live is - ticked here. - -
- {#each secondaryTypes as t (t)} - - {/each} -
-
- - - -
- - -
-
-{/snippet} - -
-
-

Release-type profiles

-

- Each followed artist is on one profile, which says which of their new releases are - wanted. Requests for a specific album aren't filtered. -

-
- - {#if query.isPending} -

Loading…

- {:else if query.isError} -

Couldn't load the profiles.

- {:else} -
    - {#each profiles as p (p.id)} -
  • -
    -
    -
    - {p.name} - {#if p.is_default} - Default - {/if} -
    -
    - {describe(p)} · {plural(p.follow_count, 'artist', 'artists')} -
    -
    - - {#if !p.is_default} - - {/if} -
    - {#if editing === p.id} - {@render editor()} - {/if} -
  • - {/each} -
- - {#if editing === 'new'} - {@render editor()} - {:else} - - {/if} - {/if} -
diff --git a/web/src/lib/components/ReleaseProfilesCard.test.ts b/web/src/lib/components/ReleaseProfilesCard.test.ts deleted file mode 100644 index f36d5e9d..00000000 --- a/web/src/lib/components/ReleaseProfilesCard.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor, within } from '@testing-library/svelte'; -import { mockQuery } from '../../test-utils/query'; -import type { ReleaseProfilesResponse } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', () => ({ - createReleaseProfilesQuery: vi.fn(), - createReleaseProfile: vi.fn().mockResolvedValue({}), - updateReleaseProfile: vi.fn().mockResolvedValue({}), - deleteReleaseProfile: vi.fn().mockResolvedValue(undefined) -})); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import ReleaseProfilesCard from './ReleaseProfilesCard.svelte'; -import { - createReleaseProfile, - createReleaseProfilesQuery, - deleteReleaseProfile, - updateReleaseProfile -} from '#lib/api/wanted.js'; - -const data: ReleaseProfilesResponse = { - profiles: [ - { id: 'p-std', name: 'Standard', primary_types: ['Album', 'EP', 'Single'], secondary_types: [], is_default: true, follow_count: 3 }, - { id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 } - ], - primary_types: ['Album', 'EP', 'Single', 'Broadcast', 'Other'], - secondary_types: ['Compilation', 'Live', 'Remix'] -}; - -afterEach(() => vi.clearAllMocks()); - -function setup() { - vi.mocked(createReleaseProfilesQuery).mockReturnValue( - mockQuery({ data }) as unknown as ReturnType - ); - return render(ReleaseProfilesCard); -} - -describe('ReleaseProfilesCard', () => { - test('says what each profile wants', () => { - setup(); - const rows = screen.getAllByTestId('profile-row'); - expect(rows[0].textContent).toMatch(/studio only/i); - expect(rows[0].textContent).toMatch(/3 artists/i); - expect(rows[1].textContent).toMatch(/including live/i); - }); - - // The default can't be deleted; the server refuses it, so the card doesn't offer it. - test('the default profile has no delete button', () => { - setup(); - expect(screen.queryByRole('button', { name: /delete standard/i })).toBeNull(); - expect(screen.getByRole('button', { name: /delete with live/i })).toBeTruthy(); - }); - - test('editing ticks a secondary type and saves it', async () => { - setup(); - await fireEvent.click(screen.getByRole('button', { name: /edit standard/i })); - const editor = screen.getByTestId('profile-editor'); - await fireEvent.click(within(editor).getByLabelText('Live')); - await fireEvent.click(within(editor).getByRole('button', { name: /save profile/i })); - await waitFor(() => - expect(updateReleaseProfile).toHaveBeenCalledWith('p-std', { - name: 'Standard', - primary_types: ['Album', 'EP', 'Single'], - secondary_types: ['Live'], - is_default: true - }) - ); - }); - - test('a new profile is created', async () => { - setup(); - await fireEvent.click(screen.getByRole('button', { name: /new profile/i })); - const editor = screen.getByTestId('profile-editor'); - await fireEvent.input(within(editor).getByLabelText(/name/i), { target: { value: 'Everything live' } }); - await fireEvent.click(within(editor).getByLabelText('Live')); - await fireEvent.click(within(editor).getByRole('button', { name: /save profile/i })); - await waitFor(() => - expect(createReleaseProfile).toHaveBeenCalledWith( - expect.objectContaining({ name: 'Everything live', secondary_types: ['Live'] }) - ) - ); - }); - - test('delete removes a profile', async () => { - setup(); - await fireEvent.click(screen.getByRole('button', { name: /delete with live/i })); - await waitFor(() => expect(deleteReleaseProfile).toHaveBeenCalledWith('p-live')); - }); -}); diff --git a/web/src/lib/components/RequestRow.svelte b/web/src/lib/components/RequestRow.svelte deleted file mode 100644 index 9807734c..00000000 --- a/web/src/lib/components/RequestRow.svelte +++ /dev/null @@ -1,74 +0,0 @@ - - - - -
  • - - -
    -
    - {r.kind[0].toUpperCase() + r.kind.slice(1)} - -
    -
    {title}
    -
    {meta}
    - {#if r.imported_album_count > 0 || r.imported_track_count > 0} -
    - {#if r.kind === 'artist'} - {plural(r.imported_album_count, 'album', 'albums')} - · {plural(r.imported_track_count, 'track', 'tracks')} ingested - {:else if r.kind === 'album'} - {plural(r.imported_track_count, 'track', 'tracks')} ingested - {:else} - Track ingested - {/if} -
    - {/if} - {@render details?.()} -
    - - {#if actions} -
    {@render actions()}
    - {/if} -
  • diff --git a/web/src/lib/components/RequestRow.test.ts b/web/src/lib/components/RequestRow.test.ts deleted file mode 100644 index 3da44fa4..00000000 --- a/web/src/lib/components/RequestRow.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { render, screen } from '@testing-library/svelte'; -import type { MusicRequest } from '#lib/api/types.js'; -import RequestRow, { requestName } from './RequestRow.svelte'; - -function req(over: Partial = {}): MusicRequest { - return { - id: 'r1', - user_id: 'u1', - status: 'approved', - kind: 'album', - artist_mbid: 'art-mbid', - artist_name: 'Boards of Canada', - album_title: 'Geogaddi', - track_title: null, - requested_at: '2026-04-28T12:00:00Z', - updated_at: '2026-04-28T12:00:00Z', - imported_album_count: 0, - imported_track_count: 0, - ...over - }; -} - -const text = (el: HTMLElement) => (el.textContent ?? '').replace(/\s+/g, ' ').trim(); - -// The row both Requests pages draw: the admin queue and the -// requester's own list read the same request the same way. -describe('RequestRow', () => { - test('says what was asked for, where it stands, and who or when', () => { - render(RequestRow, { request: req(), meta: 'by Boards of Canada · 4/28/2026', testid: 'request-row' }); - const row = screen.getByTestId('request-row'); - expect(row.dataset.status).toBe('approved'); - expect(text(row)).toMatch(/^Album Approved · downloading Geogaddi by Boards of Canada · 4\/28\/2026$/); - }); - - test('says how much has arrived, in the words for each kind', () => { - const { unmount } = render(RequestRow, { - request: req({ kind: 'artist', imported_album_count: 3, imported_track_count: 41 }), - meta: '', - testid: 'r' - }); - expect(text(screen.getByTestId('ingest-progress'))).toBe('3 albums · 41 tracks ingested'); - unmount(); - - render(RequestRow, { request: req({ kind: 'track', track_title: 'Roygbiv', imported_track_count: 1 }), meta: '', testid: 'r' }); - expect(text(screen.getByTestId('ingest-progress'))).toBe('Track ingested'); - }); - - test('nothing arrived yet says nothing about it', () => { - render(RequestRow, { request: req(), meta: '', testid: 'r' }); - expect(screen.queryByTestId('ingest-progress')).toBeNull(); - }); - - test('a request with no title still has a name a screen reader can say', () => { - render(RequestRow, { request: req({ album_title: null }), meta: '', testid: 'r' }); - expect(text(screen.getByTestId('r'))).toMatch(/—/); - expect(requestName(req({ album_title: null }))).toBe('this album by Boards of Canada'); - expect(requestName(req({ kind: 'artist' }))).toBe('Boards of Canada'); - }); -}); diff --git a/web/src/lib/components/RowActionsMenu.svelte b/web/src/lib/components/RowActionsMenu.svelte index 281a9a79..10c3b1f8 100644 --- a/web/src/lib/components/RowActionsMenu.svelte +++ b/web/src/lib/components/RowActionsMenu.svelte @@ -1,7 +1,5 @@ - { menuOpen = false; }} onkeydown={(e) => e.key === 'Escape' && (menuOpen = false)} /> -
    - - {#if menuOpen} - - {/if} -
    + + {#each secondary as action (action.label)} + fire(action)} + danger={action.danger} + disabled={action.disabled} + /> + {/each} + {/if}
    diff --git a/web/src/lib/components/SearchSettingsCard.svelte b/web/src/lib/components/SearchSettingsCard.svelte deleted file mode 100644 index f23bb25c..00000000 --- a/web/src/lib/components/SearchSettingsCard.svelte +++ /dev/null @@ -1,240 +0,0 @@ - - - - {#if query.isPending} -

    Loading…

    - {:else if query.isError || !form || !query.data} -

    - Couldn't load the search settings. - -

    - {:else} - {@const data = query.data} - - {#snippet hint()}{lastPass(data)}{/snippet} - Wanted - - - edit({ auto_grab: e.currentTarget.checked })} - class="h-4 w-4 cursor-pointer accent-accent" - /> - - - edit({ search_interval_hours: Number(e.currentTarget.value) })} - class={field} - /> - hours - - - {#each data.tiers as t (t.tier)} -
    - - toggle(t.tier)} - class="h-4 w-4 cursor-pointer accent-accent" - /> - -
    - {/each} - - - Upgrades - - {#if data.scan_paths.length > 1} - - - - {:else if data.scan_paths.length === 1} - - {data.scan_paths[0]} - - {/if} - - edit({ seed_ratio: Number(e.currentTarget.value) })} - class={field} - /> - - - edit({ seed_days: Number(e.currentTarget.value) })} - class={field} - /> - days - - - edit({ stall_hours: Number(e.currentTarget.value) })} - class={field} - /> - hours - -
    - -
    - {/if} -
    diff --git a/web/src/lib/components/SearchSettingsCard.test.ts b/web/src/lib/components/SearchSettingsCard.test.ts deleted file mode 100644 index 9d14858c..00000000 --- a/web/src/lib/components/SearchSettingsCard.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import { mockQuery } from '../../test-utils/query'; -import type { SearchSettings } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', () => ({ - createSearchSettingsQuery: vi.fn(), - putSearchSettings: vi.fn() -})); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import SearchSettingsCard from './SearchSettingsCard.svelte'; -import { createSearchSettingsQuery, putSearchSettings } from '#lib/api/wanted.js'; - -const settings: SearchSettings = { - auto_grab: true, - search_interval_hours: 24, - allowed_qualities: ['lossless', 'lossy_high'], - tiers: [ - { tier: 'lossless', label: 'Lossless', what: 'FLAC, ALAC' }, - { tier: 'lossy_high', label: 'High quality lossy', what: 'MP3 320 or V0' }, - { tier: 'unknown', label: 'Unknown', what: 'Nothing says what format it is' } - ], - last_pass_at: new Date(Date.now() - 5 * 60_000).toISOString(), - last_pass: { looked: 12, grabbed: 3, waiting: 2, nothing: 7, failed: 0, paced: true }, - import_root: '', - scan_paths: ['/music', '/music2'], - seed_ratio: 2, - seed_days: 14, - stall_hours: 6, - upgrade_until: 'lossy_high' -}; - -afterEach(() => vi.clearAllMocks()); - -function setup(s: SearchSettings = settings) { - vi.mocked(createSearchSettingsQuery).mockReturnValue( - mockQuery({ data: s }) as unknown as ReturnType - ); - vi.mocked(putSearchSettings).mockImplementation(async (body) => ({ ...s, ...body })); - return render(SearchSettingsCard); -} - -describe('SearchSettingsCard', () => { - test('shows the settings and what the last pass did', () => { - setup(); - expect((screen.getByLabelText(/take the best release without asking/i) as HTMLInputElement).checked).toBe(true); - expect((screen.getByLabelText(/search again after/i) as HTMLInputElement).value).toBe('24'); - expect((screen.getByLabelText(/^unknown/i) as HTMLInputElement).checked).toBe(false); - const last = screen.getByTestId('last-pass').textContent ?? ''; - expect(last).toMatch(/searched 12, took 3, 2 waiting for you, 7 with nothing found\./); - expect(last).toMatch(/searches per hour/); - }); - - test('saves what changed', async () => { - setup(); - const save = screen.getByRole('button', { name: /^save$/i }) as HTMLButtonElement; - expect(save.disabled).toBe(true); - await fireEvent.click(screen.getByLabelText(/take the best release without asking/i)); - await fireEvent.click(screen.getByLabelText(/^unknown/i)); - await fireEvent.click(save); - await waitFor(() => - expect(putSearchSettings).toHaveBeenCalledWith({ - auto_grab: false, - search_interval_hours: 24, - allowed_qualities: ['lossless', 'lossy_high', 'unknown'], - import_root: '', - seed_ratio: 2, - seed_days: 14, - stall_hours: 6, - upgrade_until: 'lossy_high' - }) - ); - }); - - test('new music is filed into the chosen library folder, the first by default', async () => { - setup(); - const folder = screen.getByLabelText(/file new music into/i) as HTMLSelectElement; - expect(folder.value).toBe('/music'); - await fireEvent.change(folder, { target: { value: '/music2' } }); - await fireEvent.click(screen.getByRole('button', { name: /^save$/i })); - await waitFor(() => - expect(putSearchSettings).toHaveBeenCalledWith(expect.objectContaining({ import_root: '/music2' })) - ); - }); - - test('with one library folder there is nothing to choose', () => { - setup({ ...settings, scan_paths: ['/music'] }); - expect(screen.queryByLabelText(/file new music into/i)).toBeNull(); - expect(screen.getByText('/music')).toBeTruthy(); - }); - - test('seeding and giving up on a stalled download are set here', async () => { - setup(); - expect((screen.getByLabelText(/seed ratio/i) as HTMLInputElement).value).toBe('2'); - await fireEvent.input(screen.getByLabelText(/seed ratio/i), { target: { value: '1.5' } }); - await fireEvent.input(screen.getByLabelText(/seed days/i), { target: { value: '7' } }); - await fireEvent.input(screen.getByLabelText(/give up on a stalled download/i), { target: { value: '0' } }); - await fireEvent.click(screen.getByRole('button', { name: /^save$/i })); - await waitFor(() => - expect(putSearchSettings).toHaveBeenCalledWith( - expect.objectContaining({ seed_ratio: 1.5, seed_days: 7, stall_hours: 0 }) - ) - ); - }); - - test('upgrades go up to the chosen quality, or are switched off', async () => { - setup(); - const until = screen.getByLabelText(/upgrade until/i) as HTMLSelectElement; - expect(until.value).toBe('lossy_high'); - expect([...until.options].map((o) => o.textContent)).toEqual([ - "Don't upgrade", - 'Lossless', - 'High quality lossy' - ]); - await fireEvent.change(until, { target: { value: '' } }); - await fireEvent.click(screen.getByRole('button', { name: /^save$/i })); - await waitFor(() => - expect(putSearchSettings).toHaveBeenCalledWith(expect.objectContaining({ upgrade_until: '' })) - ); - }); - - test('before the first pass it says so', () => { - setup({ ...settings, last_pass_at: null, last_pass: {} }); - expect(screen.getByTestId('last-pass').textContent).toMatch(/hasn’t run yet/); - }); -}); diff --git a/web/src/lib/components/SectionLayout.svelte b/web/src/lib/components/SectionLayout.svelte new file mode 100644 index 00000000..cdda0e60 --- /dev/null +++ b/web/src/lib/components/SectionLayout.svelte @@ -0,0 +1,40 @@ + + +
    +
    +

    {title}

    + {@render intro?.()} +
    +
    +
    +
    + {@render rail()} +
    +
    +
    + {@render children?.()} +
    +
    +
    diff --git a/web/src/lib/components/Shell.svelte b/web/src/lib/components/Shell.svelte index 1e8557d9..b88f420f 100644 --- a/web/src/lib/components/Shell.svelte +++ b/web/src/lib/components/Shell.svelte @@ -1,7 +1,7 @@ - - - -{entry.label} - - diff --git a/web/src/lib/components/StatusPill.test.ts b/web/src/lib/components/StatusPill.test.ts deleted file mode 100644 index 7f4d7632..00000000 --- a/web/src/lib/components/StatusPill.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { render, screen } from '@testing-library/svelte'; -import StatusPill from './StatusPill.svelte'; - -// Labels in Minstrel's voice, and their semantic tones. -// Each row is the contract: input status -> rendered label + data-tone attr. -const CASES = [ - { status: 'pending', label: 'Awaiting review', tone: 'warning' }, - { status: 'approved', label: 'Approved · downloading', tone: 'info' }, - { status: 'completed', label: 'Kept', tone: 'success' }, - { status: 'rejected', label: 'Set aside', tone: 'error' }, - { status: 'failed', label: "Couldn't add", tone: 'error' }, -] as const; - -describe('StatusPill', () => { - for (const { status, label, tone } of CASES) { - test(`${status} renders "${label}" with tone=${tone}`, () => { - render(StatusPill, { props: { status } }); - const pill = screen.getByText(label); - expect(pill).toBeInTheDocument(); - expect(pill.getAttribute('data-tone')).toBe(tone); - expect(pill.getAttribute('data-status')).toBe(status); - }); - } -}); diff --git a/web/src/lib/components/SuggestionFeed.svelte b/web/src/lib/components/SuggestionFeed.svelte deleted file mode 100644 index 5f00ee18..00000000 --- a/web/src/lib/components/SuggestionFeed.svelte +++ /dev/null @@ -1,212 +0,0 @@ - - -
    -
    -

    Suggested for you

    -

    Out-of-library artists drawn from what you've liked and played.

    -
    - - {#if !query.isPending && suggestions.length === 0} - -

    - {snoozes.length === 0 - ? 'Listen to something or like an artist to start getting suggestions.' - : "Nothing new right now — the artists you've parked are below."} -

    - {:else if suggestions.length > 0} -
    - {#each suggestions.filter(visible) as s (s.mbid)} - onRequest(s)} - onSnooze={() => onSnooze(s)} - onUnsnooze={() => onUnsnooze(s.mbid, s.name)} - /> - {/each} -
    - {/if} - - - {#if snoozes.length > 0} -
    -

    - Not right now -

    -

    - These come back on their own. Nothing here counts against your taste profile. -

    -
      - {#each snoozes as snoozed (snoozed.mbid)} -
    • -
      -
      {snoozed.name}
      -
      - Back {returnsIn(snoozed.snoozed_until)} -
      -
      - -
    • - {/each} -
    -
    - {/if} -
    diff --git a/web/src/lib/components/SuggestionFeed.test.ts b/web/src/lib/components/SuggestionFeed.test.ts deleted file mode 100644 index f22e6c4f..00000000 --- a/web/src/lib/components/SuggestionFeed.test.ts +++ /dev/null @@ -1,292 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/svelte'; -import { mockQuery } from '../../test-utils/query'; - -const invalidateMock = vi.fn(); -vi.mock('@tanstack/svelte-query', async (orig) => { - const actual = (await orig()) as Record; - return { ...actual, useQueryClient: () => ({ invalidateQueries: invalidateMock }) }; -}); - -vi.mock('#lib/api/suggestions.js', () => ({ - createSuggestionsQuery: vi.fn(), - createSnoozesQuery: vi.fn(), - snoozeSuggestion: vi.fn().mockResolvedValue(undefined), - unsnoozeSuggestion: vi.fn().mockResolvedValue(undefined) -})); - -vi.mock('#lib/api/requests.js', () => ({ - createRequest: vi.fn().mockResolvedValue({}) -})); - -const pushToastMock = vi.fn(); -vi.mock('#lib/stores/toast.svelte.js', () => ({ - pushToast: (...args: unknown[]) => pushToastMock(...args) -})); - -import SuggestionFeed from './SuggestionFeed.svelte'; -import { - createSuggestionsQuery, - createSnoozesQuery, - snoozeSuggestion, - unsnoozeSuggestion -} from '#lib/api/suggestions.js'; -import { createRequest } from '#lib/api/requests.js'; -import type { ArtistSuggestion, SuggestionSnooze } from '#lib/api/types.js'; - -const oneSeed: ArtistSuggestion = { - mbid: 'mb1', - name: 'Outsider', - score: 1.0, - attribution: [ - { artist_id: 'a1', name: 'Seed', contribution: 0.9, is_liked: true, play_count: 0 } - ] -}; - -const twoSeeds: ArtistSuggestion = { - mbid: 'mb2', - name: 'Outsider Two', - score: 2.0, - attribution: [ - { artist_id: 'a1', name: 'A', contribution: 0.8, is_liked: true, play_count: 0 }, - { artist_id: 'a2', name: 'B', contribution: 0.5, is_liked: false, play_count: 3 } - ] -}; - -const threeSeeds: ArtistSuggestion = { - mbid: 'mb3', - name: 'Outsider Three', - score: 3.0, - attribution: [ - { artist_id: 'a1', name: 'X', contribution: 0.9, is_liked: true, play_count: 0 }, - { artist_id: 'a2', name: 'Y', contribution: 0.6, is_liked: false, play_count: 5 }, - { artist_id: 'a3', name: 'Z', contribution: 0.3, is_liked: false, play_count: 1 } - ] -}; - -/** Days from now as an RFC3339 string, for snooze fixtures. */ -function inDays(n: number): string { - return new Date(Date.now() + n * 86_400_000).toISOString(); -} - -function setSuggestions(data: ArtistSuggestion[]) { - (createSuggestionsQuery as ReturnType).mockReturnValue(mockQuery({ data })); -} - -function setSnoozes(data: SuggestionSnooze[]) { - (createSnoozesQuery as ReturnType).mockReturnValue(mockQuery({ data })); -} - -beforeEach(() => setSnoozes([])); -afterEach(() => vi.clearAllMocks()); - -describe('SuggestionFeed', () => { - test('renders one card per suggestion', () => { - setSuggestions([oneSeed, twoSeeds]); - render(SuggestionFeed); - expect(screen.getByText('Outsider')).toBeInTheDocument(); - expect(screen.getByText('Outsider Two')).toBeInTheDocument(); - }); - - test('attribution copy: 1 seed → "Because you liked X."', () => { - setSuggestions([oneSeed]); - render(SuggestionFeed); - expect(screen.getByText(/because you liked seed\./i)).toBeInTheDocument(); - }); - - test('attribution copy: 2 seeds → "Because you liked A and played B."', () => { - setSuggestions([twoSeeds]); - render(SuggestionFeed); - expect(screen.getByText(/because you liked a and played b\./i)).toBeInTheDocument(); - }); - - test('attribution copy: 3 seeds → Oxford comma', () => { - setSuggestions([threeSeeds]); - render(SuggestionFeed); - expect(screen.getByText(/because you liked x, played y, and played z\./i)).toBeInTheDocument(); - }); - - test('Request button calls createRequest with artist-kind body', async () => { - setSuggestions([oneSeed]); - render(SuggestionFeed); - await fireEvent.click(screen.getByRole('button', { name: /request outsider/i })); - expect(createRequest).toHaveBeenCalledWith({ - kind: 'artist', - artist_mbid: 'mb1', - artist_name: 'Outsider' - }); - expect(invalidateMock).toHaveBeenCalled(); - }); - - test('empty state when data is []', () => { - setSuggestions([]); - render(SuggestionFeed); - expect(screen.getByText(/listen to something or like an artist/i)).toBeInTheDocument(); - }); -}); - -describe('SuggestionFeed snooze (#2375)', () => { - test('snooze sends BOTH mbid and name — the server 400s without the name', async () => { - setSuggestions([oneSeed]); - render(SuggestionFeed); - await fireEvent.click(screen.getByRole('button', { name: /not right now/i })); - expect(snoozeSuggestion).toHaveBeenCalledWith('mb1', 'Outsider'); - }); - - test('the card stays in place showing Undo, rather than vanishing', async () => { - setSuggestions([oneSeed]); - render(SuggestionFeed); - await fireEvent.click(screen.getByRole('button', { name: /not right now/i })); - // Still on screen — the disappearance happens on refetch, not under the - // cursor. - expect(screen.getByText('Outsider')).toBeInTheDocument(); - expect(screen.getByRole('button', { name: /bring outsider back/i })).toBeInTheDocument(); - expect(screen.getByRole('status')).toHaveTextContent('Not right now'); - }); - - test('a failed snooze reverts the card and says so', async () => { - (snoozeSuggestion as ReturnType).mockRejectedValueOnce(new Error('offline')); - setSuggestions([oneSeed]); - render(SuggestionFeed); - await fireEvent.click(screen.getByRole('button', { name: /not right now/i })); - // Back to requestable — a snooze that silently did nothing would leave - // the user tapping it again. - expect(screen.getByRole('button', { name: /request outsider/i })).toBeInTheDocument(); - expect(pushToastMock).toHaveBeenCalledWith("Couldn't hide Outsider", 'error'); - }); - - test('undo on the card calls unsnoozeSuggestion', async () => { - setSuggestions([oneSeed]); - render(SuggestionFeed); - await fireEvent.click(screen.getByRole('button', { name: /not right now/i })); - await fireEvent.click(screen.getByRole('button', { name: /bring outsider back/i })); - expect(unsnoozeSuggestion).toHaveBeenCalledWith('mb1'); - }); - - test('the snoozed list is the way back once the card is gone', async () => { - // Deck empty, one parked artist: exactly the state after a refetch. - setSuggestions([]); - setSnoozes([ - { mbid: 'mbX', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) } - ]); - render(SuggestionFeed); - expect(screen.getByRole('heading', { name: /not right now/i })).toBeInTheDocument(); - expect(screen.getByText('Parked')).toBeInTheDocument(); - await fireEvent.click(screen.getByRole('button', { name: /bring parked back now/i })); - expect(unsnoozeSuggestion).toHaveBeenCalledWith('mbX'); - }); - - test('a 404 from unsnooze is not surfaced as an error', async () => { - (unsnoozeSuggestion as ReturnType).mockRejectedValueOnce({ status: 404 }); - setSuggestions([]); - setSnoozes([ - { mbid: 'mbX', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) } - ]); - render(SuggestionFeed); - await fireEvent.click(screen.getByRole('button', { name: /bring parked back now/i })); - // Already-unsnoozed IS the end state the user asked for. - expect(pushToastMock).not.toHaveBeenCalled(); - }); - - test('a non-404 unsnooze failure does surface', async () => { - (unsnoozeSuggestion as ReturnType).mockRejectedValueOnce({ status: 500 }); - setSuggestions([]); - setSnoozes([ - { mbid: 'mbX', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) } - ]); - render(SuggestionFeed); - await fireEvent.click(screen.getByRole('button', { name: /bring parked back now/i })); - expect(pushToastMock).toHaveBeenCalledWith("Couldn't bring Parked back", 'error'); - }); - - test('return time reads as a relative phrase, not a calendar date', () => { - setSuggestions([]); - setSnoozes([ - { mbid: 'a', name: 'Quarter', snoozed_until: inDays(90), created_at: inDays(0) }, - { mbid: 'b', name: 'Fortnight', snoozed_until: inDays(14), created_at: inDays(0) } - ]); - render(SuggestionFeed); - expect(screen.getByText(/back in about 3 months/i)).toBeInTheDocument(); - expect(screen.getByText(/back in 14 days/i)).toBeInTheDocument(); - }); - - // Pins the days→months seam: with a threshold above the divisor (45 vs 30), - // no day count could round to one month without hitting the days branch - // first, and the singular branch would be dead code. Kept in lockstep with - // SuggestionSnoozeRefTest on Android. - test('the days-to-months boundary sits at 30 days, so "a month" is reachable', () => { - setSuggestions([]); - setSnoozes([ - { mbid: 'a', name: 'JustUnder', snoozed_until: inDays(29), created_at: inDays(0) }, - { mbid: 'b', name: 'JustOver', snoozed_until: inDays(30), created_at: inDays(0) } - ]); - render(SuggestionFeed); - expect(screen.getByText(/back in 29 days/i)).toBeInTheDocument(); - expect(screen.getByText(/back in about a month/i)).toBeInTheDocument(); - }); - - test('no snoozed section when nothing is parked', () => { - setSuggestions([oneSeed]); - setSnoozes([]); - render(SuggestionFeed); - expect(screen.queryByRole('heading', { name: /not right now/i })).not.toBeInTheDocument(); - }); - - // An empty deck has two causes now, and the advice differs. Telling someone - // who parked everything to go listen to music would be wrong. - test('empty-deck copy distinguishes "no signal" from "you parked them all"', () => { - setSuggestions([]); - setSnoozes([ - { mbid: 'a', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) } - ]); - render(SuggestionFeed); - expect(screen.getByText(/nothing new right now/i)).toBeInTheDocument(); - expect(screen.queryByText(/listen to something or like an artist/i)).not.toBeInTheDocument(); - }); -}); - -describe('SuggestionFeed taste-tag reason (#2377)', () => { - const tagged = (over: Partial = {}): ArtistSuggestion => ({ - ...oneSeed, - mbid: 'mbT', - name: 'Tag Match', - ...over - }); - - test('matched tags replace seed attribution as the reason line', () => { - setSuggestions([tagged({ matched_tags: ['shoegaze', 'dream pop'] })]); - render(SuggestionFeed); - expect( - screen.getByText(/matches your taste in shoegaze and dream pop\./i) - ).toBeInTheDocument(); - // The graph-adjacency line is superseded — describing the music beats - // describing the graph when we can do both. - expect(screen.queryByText(/because you liked/i)).not.toBeInTheDocument(); - }); - - test('one matched tag reads in the singular', () => { - setSuggestions([tagged({ matched_tags: ['shoegaze'] })]); - render(SuggestionFeed); - expect(screen.getByText(/matches your taste in shoegaze\./i)).toBeInTheDocument(); - }); - - test('three matched tags use an Oxford comma, matching the seed copy', () => { - setSuggestions([tagged({ matched_tags: ['a', 'b', 'c'] })]); - render(SuggestionFeed); - expect(screen.getByText(/matches your taste in a, b, and c\./i)).toBeInTheDocument(); - }); - - // The common case: most candidates have no cached tags, and the card must - // still explain itself rather than going blank. - test('no matched tags falls back to seed attribution', () => { - setSuggestions([oneSeed]); - render(SuggestionFeed); - expect(screen.getByText(/because you liked seed\./i)).toBeInTheDocument(); - }); - - test('an empty matched_tags array also falls back, not to an empty line', () => { - setSuggestions([tagged({ matched_tags: [] })]); - render(SuggestionFeed); - expect(screen.getByText(/because you liked seed\./i)).toBeInTheDocument(); - }); -}); diff --git a/web/src/lib/components/TabStrip.svelte b/web/src/lib/components/TabStrip.svelte index 6317e303..10ddc363 100644 --- a/web/src/lib/components/TabStrip.svelte +++ b/web/src/lib/components/TabStrip.svelte @@ -1,7 +1,6 @@ -
    +
    {@render children()}
    diff --git a/web/src/lib/components/TrackListRow.test.ts b/web/src/lib/components/TrackListRow.test.ts index 19701d4a..7c17383f 100644 --- a/web/src/lib/components/TrackListRow.test.ts +++ b/web/src/lib/components/TrackListRow.test.ts @@ -21,15 +21,15 @@ vi.mock('#lib/api/quarantine.js', () => emptyQuarantineMock()); import TrackListRow from './TrackListRow.svelte'; import { enqueueTrack, playRadio } from '#lib/player/store.svelte.js'; -const track = makeTrack({ id: 't1', title: 'Roygbiv', duration_sec: 137 }); +const track = makeTrack({ id: 't1', title: 'Prismatic', duration_sec: 137 }); function base(overrides: Record = {}) { return { - title: 'Roygbiv', - subtitle: 'Boards of Canada · MHTRTC', + title: 'Prismatic', + subtitle: 'Fields of Ontario · MHTRTW', durationSec: 137, track, - ariaLabel: 'Roygbiv', + ariaLabel: 'Prismatic', onActivate: vi.fn(), ...overrides }; @@ -43,19 +43,19 @@ afterEach(() => { describe('TrackListRow', () => { test('draws title, subtitle and duration', () => { render(TrackListRow, { props: base() }); - expect(screen.getByText('Roygbiv')).toBeInTheDocument(); - expect(screen.getByText('Boards of Canada · MHTRTC')).toBeInTheDocument(); + expect(screen.getByText('Prismatic')).toBeInTheDocument(); + expect(screen.getByText('Fields of Ontario · MHTRTW')).toBeInTheDocument(); expect(screen.getByText('2:17')).toBeInTheDocument(); }); test('a plain row is striped; the now-playing row is banded instead', () => { const { unmount } = render(TrackListRow, { props: base() }); - expect(screen.getByRole('button', { name: 'Roygbiv' }).className).toContain('odd:bg-surface/50'); + expect(screen.getByRole('button', { name: 'Prismatic' }).className).toContain('odd:bg-surface/50'); unmount(); player.current = { id: 't1' }; render(TrackListRow, { props: base() }); - const row = screen.getByRole('button', { name: 'Roygbiv' }); + const row = screen.getByRole('button', { name: 'Prismatic' }); expect(row.className).toContain('border-l-accent'); expect(row.className).not.toContain('odd:bg-surface/50'); }); @@ -63,7 +63,7 @@ describe('TrackListRow', () => { test('click and Enter activate the row', async () => { const props = base(); render(TrackListRow, { props }); - const row = screen.getByRole('button', { name: 'Roygbiv' }); + const row = screen.getByRole('button', { name: 'Prismatic' }); await fireEvent.click(row); await fireEvent.keyDown(row, { key: 'Enter' }); expect(props.onActivate).toHaveBeenCalledTimes(2); @@ -74,7 +74,7 @@ describe('TrackListRow', () => { test('Enter on an inner control does not activate the row', async () => { const props = base(); render(TrackListRow, { props }); - await fireEvent.keyDown(screen.getByRole('button', { name: /add roygbiv to queue/i }), { key: 'Enter' }); + await fireEvent.keyDown(screen.getByRole('button', { name: /add prismatic to queue/i }), { key: 'Enter' }); expect(props.onActivate).not.toHaveBeenCalled(); }); @@ -82,7 +82,7 @@ describe('TrackListRow', () => { const props = base(); render(TrackListRow, { props }); await fireEvent.click(screen.getByRole('button', { name: /play radio/i })); - await fireEvent.click(screen.getByRole('button', { name: /add roygbiv to queue/i })); + await fireEvent.click(screen.getByRole('button', { name: /add prismatic to queue/i })); expect(playRadio).toHaveBeenCalledWith('t1'); expect(enqueueTrack).toHaveBeenCalledWith(track); expect(props.onActivate).not.toHaveBeenCalled(); @@ -98,7 +98,7 @@ describe('TrackListRow', () => { test('a disabled row does not activate', async () => { const props = base({ disabled: true }); render(TrackListRow, { props }); - await fireEvent.click(screen.getByRole('button', { name: 'Roygbiv' })); + await fireEvent.click(screen.getByRole('button', { name: 'Prismatic' })); expect(props.onActivate).not.toHaveBeenCalled(); }); }); diff --git a/web/src/lib/components/TrackMenu.svelte b/web/src/lib/components/TrackMenu.svelte index ef7f0377..dcef750d 100644 --- a/web/src/lib/components/TrackMenu.svelte +++ b/web/src/lib/components/TrackMenu.svelte @@ -1,6 +1,5 @@ - { menuOpen = false; addOpen = false; }} onkeydown={onKeydown} /> + { + addOpen = false; + if (why === 'escape') flagOpen = false; + }} +> + + {#if !hideQueueActions} + + -
    - - - {#if menuOpen} - + {/if} - {#if flagOpen} - - {/if} + + { addOpen = true; menuOpen = false; }} + /> + - {#if addOpen} - (addOpen = false)} /> - {/if} -
    + + + + + + + + + + {#snippet after()} + {#if flagOpen} + + {/if} + + {#if addOpen} + (addOpen = false)} /> + {/if} + {/snippet} +
    diff --git a/web/src/lib/components/TrackMenu.test.ts b/web/src/lib/components/TrackMenu.test.ts index 1b0ece70..5bc7c1e5 100644 --- a/web/src/lib/components/TrackMenu.test.ts +++ b/web/src/lib/components/TrackMenu.test.ts @@ -36,7 +36,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({ import TrackMenu from './TrackMenu.svelte'; import { playNext, enqueueTrack, playRadio } from '#lib/player/store.svelte.js'; -const track = makeTrack({ title: 'Roygbiv' }); +const track = makeTrack({ title: 'Prismatic' }); afterEach(() => { vi.clearAllMocks(); @@ -46,7 +46,7 @@ afterEach(() => { describe('TrackMenu', () => { test('kebab toggles aria-expanded', async () => { render(TrackMenu, { props: { track } }); - const kebab = screen.getByRole('button', { name: /track actions for roygbiv/i }); + const kebab = screen.getByRole('button', { name: /track actions for prismatic/i }); expect(kebab.getAttribute('aria-expanded')).toBe('false'); await fireEvent.click(kebab); expect(kebab.getAttribute('aria-expanded')).toBe('true'); diff --git a/web/src/lib/components/TrackMenuItem.svelte b/web/src/lib/components/TrackMenuItem.svelte index 5c68324d..1ed5f5bf 100644 --- a/web/src/lib/components/TrackMenuItem.svelte +++ b/web/src/lib/components/TrackMenuItem.svelte @@ -1,4 +1,4 @@ - + - -
    - {#if query.isPending} -

    Loading what the last search found…

    - {:else if query.isError} -

    Couldn't load the releases.

    - {:else if items.length === 0} -

    - Nothing kept from a search yet. Search now, or wait for the schedule. -

    - {:else} -

    - {plural(items.length, 'release', 'releases')} found {relativeTime(items[0].searched_at)}, best first. -

    -
      - {#each items as c (c.key)} -
    • -
      -
      {c.name}
      -
      {meta(c)}
      -
      - - {c.downloading ? 'Downloading' : verdictLabel[c.verdict]} - - {c.reason} -
      -
      -
      - {#if c.verdict === 'blocked'} - - {:else if !c.downloading} - - {#if c.info_hash} - - {/if} - {/if} -
      -
    • - {/each} -
    - {/if} -
    diff --git a/web/src/lib/components/WantCandidates.test.ts b/web/src/lib/components/WantCandidates.test.ts deleted file mode 100644 index 3c7fcecf..00000000 --- a/web/src/lib/components/WantCandidates.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import { mockQuery } from '../../test-utils/query'; -import type { Candidate } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', () => ({ - createCandidatesQuery: vi.fn(), - grabCandidate: vi.fn().mockResolvedValue({ added: true, refused: false, gone: false, unconfigured: false, kept: false, replaced: false }), - blockCandidate: vi.fn().mockResolvedValue(undefined), - unblockRelease: vi.fn().mockResolvedValue(undefined) -})); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import WantCandidates from './WantCandidates.svelte'; -import { blockCandidate, createCandidatesQuery, grabCandidate, unblockRelease } from '#lib/api/wanted.js'; -import { pushToast } from '#lib/stores/toast.svelte.js'; - -function cand(key: string, extra: Partial = {}): Candidate { - return { - key, - name: `Daft Punk - Random Access Memories (2013) [${key}]`, - info_hash: key, - indexer: 'Knaben', - size_bytes: 450_000_000, - seeders: 12, - files_count: 13, - format: 'FLAC', - quality: 'lossless', - year: 2013, - verdict: 'grab', - reason: 'The album, FLAC.', - reasons: [], - folded_from: [], - searched_at: new Date().toISOString(), - downloading: false, - ...extra - }; -} - -afterEach(() => vi.clearAllMocks()); - -function setup(items: Candidate[]) { - vi.mocked(createCandidatesQuery).mockReturnValue( - mockQuery({ data: items }) as unknown as ReturnType - ); - return render(WantCandidates, { wantId: 'w1', title: 'Random Access Memories' }); -} - -describe('WantCandidates', () => { - test('every release shows its verdict and why', () => { - setup([ - cand('aaaa'), - cand('bbbb', { verdict: 'rejected', reason: 'This is a drumless edition (“drumless”).' }) - ]); - expect(screen.getAllByTestId('candidate-row')).toHaveLength(2); - expect(screen.getByText('Would take')).toBeTruthy(); - expect(screen.getByText('Not the album')).toBeTruthy(); - expect(screen.getByText(/drumless edition/)).toBeTruthy(); - expect(screen.getAllByText(/FLAC · 450 MB · 12 seeders · Knaben/)).toHaveLength(2); - }); - - test('a release the verdict would take is grabbed; any other is grabbed anyway', async () => { - setup([cand('aaaa'), cand('bbbb', { verdict: 'review', reason: 'Nobody is sharing it right now.' })]); - await fireEvent.click(screen.getByRole('button', { name: /^grab daft punk.*\[aaaa\]/i })); - await waitFor(() => expect(grabCandidate).toHaveBeenCalledWith('w1', 'aaaa', false)); - await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Taken for Random Access Memories.', 'info')); - await fireEvent.click(screen.getByRole('button', { name: /^grab anyway daft punk.*\[bbbb\]/i })); - await waitFor(() => expect(grabCandidate).toHaveBeenCalledWith('w1', 'bbbb', true)); - }); - - test('a release can be set aside, and allowed again', async () => { - setup([cand('aaaa'), cand('bbbb', { verdict: 'blocked', reason: 'You set this release aside.' })]); - await fireEvent.click(screen.getByRole('button', { name: /never take .*\[aaaa\]/i })); - await waitFor(() => expect(blockCandidate).toHaveBeenCalledWith('w1', 'aaaa')); - await fireEvent.click(screen.getByRole('button', { name: /allow .*\[bbbb\] again/i })); - await waitFor(() => expect(unblockRelease).toHaveBeenCalledWith('bbbb')); - expect(screen.queryByRole('button', { name: /grab.*\[bbbb\]/i })).toBeNull(); - }); - - test('the release downloading says so and offers nothing', () => { - setup([cand('aaaa', { downloading: true })]); - expect(screen.getByText('Downloading')).toBeTruthy(); - expect(screen.queryByRole('button', { name: /grab/i })).toBeNull(); - }); - - test('before any search, it says how to get one', () => { - setup([]); - expect(screen.getByText(/nothing kept from a search yet/i)).toBeTruthy(); - }); -}); diff --git a/web/src/lib/components/admin/BackupPanel.svelte b/web/src/lib/components/admin/BackupPanel.svelte new file mode 100644 index 00000000..e0455af1 --- /dev/null +++ b/web/src/lib/components/admin/BackupPanel.svelte @@ -0,0 +1,233 @@ + + +{#if loadError && !status} +

    + Couldn't load the backup status. + +

    +{:else if !status} +

    Loading the backup status…

    +{:else} + + {#snippet main()} + {#if status} + +
    +

    {verdict?.text}

    + {#if status.state === 'failing' && latest?.error && !status.running_since} +

    {latest.error}

    + {/if} + {#if status.config.enabled} + {#each status.problems as problem (problem)} +

    {problem}

    + {/each} + {/if} + {#if status.next_run && !status.running_since} +

    Next backup {when(status.next_run)}.

    + {/if} +
    +
    + +
    +
    + + {#if status.music} + {@const m = status.music} + +
    +

    + {#if m.total_files === 0} + No music in the library yet. + {:else if m.sent_files === m.total_files} + All {plural(m.total_files, 'file', 'files')} backed up · {formatBytes(m.sent_bytes)} + {:else} + {m.sent_files} of {plural(m.total_files, 'file', 'files')} backed up · {formatBytes(m.sent_bytes)} of + {formatBytes(m.total_bytes)} + {/if} +

    + {#if m.sent_files + m.refused_files < m.total_files && m.total_files > 0} +

    The rest goes with the next backups.

    + {/if} +
    + {#if m.refused_files > 0} +
    +

    + The destination refused {plural(m.refused_files, 'file', 'files')}. Each goes again once it changes, or + once you save the settings. +

    +
      + {#each m.refused as f (f.path)} +
    • + {f.path} + {f.error} · {when(f.at)} +
    • + {/each} +
    +
    + {/if} +
    + {/if} + + {#if status.runs.length > 0} + +
      + {#each status.runs as run (run.id)} +
    • + + {when(run.started_at)} + + {run.trigger === 'manual' ? 'Started by hand' : 'Scheduled'} + {#if run.status === 'succeeded'}· {run.location} · {formatBytes(run.bytes)}{/if} + {#if run.status === 'failed'}· {run.error}{/if} + + {#if run.music_files > 0} + + Music: {plural(run.music_files, 'file', 'files')} · {formatBytes(run.music_bytes)} + + {/if} + {#if run.music_note} + {run.music_note} + {/if} + + + {run.status === 'succeeded' ? 'Saved' : run.status === 'failed' ? 'Failed' : 'Running'} + +
    • + {/each} +
    +
    + {/if} + {/if} + {/snippet} + {#snippet side()} + {#if status} + (status = s)} /> + {/if} + {/snippet} +
    +{/if} diff --git a/web/src/lib/components/admin/BackupPanel.test.ts b/web/src/lib/components/admin/BackupPanel.test.ts new file mode 100644 index 00000000..cc6750d7 --- /dev/null +++ b/web/src/lib/components/admin/BackupPanel.test.ts @@ -0,0 +1,248 @@ +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; +import type { BackupStatus } from '#lib/api/admin.js'; + +vi.mock('#lib/api/admin.js', () => ({ + getBackups: vi.fn(), + saveBackups: vi.fn(), + testBackups: vi.fn(), + runBackup: vi.fn() +})); + +vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); + +import BackupPanel from './BackupPanel.svelte'; +import { getBackups, runBackup, saveBackups, testBackups } from '#lib/api/admin.js'; +import { pushToast } from '#lib/stores/toast.svelte.js'; + +const base: BackupStatus = { + config: { + enabled: true, + destination: 's3', + folder: '', + endpoint: 'https://s3.example.com', + bucket: 'minstrel', + access_key: 'ak', + has_secret_key: true, + run_hour: 3, + upload_limit_kib: 4096, + include_music: false + }, + state: 'ok', + problems: [], + running_since: null, + last_success: '2026-11-02T03:00:00Z', + failing_since: null, + next_run: '2026-11-03T03:00:00Z', + run_limit_seconds: 1800, + runs: [ + { + id: 'r1', + trigger: 'schedule', + status: 'succeeded', + started_at: '2026-11-02T03:00:00Z', + finished_at: '2026-11-02T03:00:09Z', + location: 'database/minstrel-20261102T030000Z.tar', + bytes: 12_000_000, + error: '', + music_files: 0, + music_bytes: 0, + music_note: '' + } + ], + music: null +}; + +function status(over: Partial = {}): BackupStatus { + return { ...base, ...over, config: { ...base.config, ...over.config } }; +} + +afterEach(() => { + vi.clearAllMocks(); + vi.useRealTimers(); +}); + +async function renderPanel(s: BackupStatus = base) { + vi.mocked(getBackups).mockResolvedValue(s); + render(BackupPanel); + await screen.findByTestId('backup-verdict'); +} + +const verdict = () => screen.getByTestId('backup-verdict').textContent?.replace(/\s+/g, ' ') ?? ''; + +describe('BackupPanel', () => { + test('leads with the verdict and lists the latest runs', async () => { + await renderPanel(); + expect(verdict()).toMatch(/^ ?Backed up /); + expect(verdict()).toMatch(/Next backup /); + const runs = screen.getByRole('list', { name: /latest backups/i }); + expect(runs.textContent).toMatch(/Scheduled · database\/minstrel-20261102T030000Z\.tar · 12\.0 MB/); + expect(runs.textContent).toMatch(/Saved/); + }); + + test('a failing backup says since when and why', async () => { + await renderPanel( + status({ + state: 'failing', + failing_since: '2026-11-02T03:00:00Z', + runs: [{ ...base.runs[0], status: 'failed', error: 'HTTP 403 SignatureDoesNotMatch: the secret key is wrong' }] + }) + ); + expect(verdict()).toMatch(/Backups failing since /); + expect(verdict()).toMatch(/the secret key is wrong/); + }); + + test('switched on but not set up: names what is missing and holds Back up now', async () => { + await renderPanel(status({ state: 'incomplete', problems: ['Enter the secret key.'], next_run: null })); + expect(verdict()).toMatch(/not set up yet/); + expect(verdict()).toMatch(/Enter the secret key\./); + expect(screen.getByRole('button', { name: /back up now/i })).toHaveProperty('disabled', true); + }); + + test('switched off reads as off, without nagging about the destination', async () => { + await renderPanel(status({ state: 'off', config: { ...base.config, enabled: false }, problems: ['Enter the secret key.'] })); + expect(verdict()).toMatch(/^ ?Off\./); + expect(verdict()).not.toMatch(/secret key/); + }); + + test('Back up now starts a run and polls only while it runs', async () => { + vi.useFakeTimers(); + vi.mocked(runBackup).mockResolvedValue(); + const running = status({ running_since: '2026-11-02T10:00:00Z' }); + vi.mocked(getBackups).mockResolvedValueOnce(base).mockResolvedValueOnce(running).mockResolvedValueOnce(running).mockResolvedValue(base); + render(BackupPanel); + await vi.waitFor(() => screen.getByTestId('backup-verdict')); + + await fireEvent.click(screen.getByRole('button', { name: /back up now/i })); + await vi.waitFor(() => expect(runBackup).toHaveBeenCalled()); + await vi.waitFor(() => expect(verdict()).toMatch(/Backing up, since /)); + expect(pushToast).toHaveBeenCalledWith('Backup started.'); + + await vi.advanceTimersByTimeAsync(3000); + await vi.advanceTimersByTimeAsync(3000); + await vi.waitFor(() => expect(verdict()).toMatch(/Backed up /)); + const calls = vi.mocked(getBackups).mock.calls.length; + await vi.advanceTimersByTimeAsync(30_000); + expect(vi.mocked(getBackups).mock.calls.length).toBe(calls); + }); + + test('a stuck run stops being polled after the run limit and a margin', async () => { + vi.useFakeTimers(); + vi.mocked(getBackups).mockResolvedValue(status({ running_since: '2026-11-02T10:00:00Z', run_limit_seconds: 60 })); + render(BackupPanel); + await vi.waitFor(() => screen.getByTestId('backup-verdict')); + // 60 s limit + 5 min margin, and a little more. + await vi.advanceTimersByTimeAsync(7 * 60 * 1000); + const calls = vi.mocked(getBackups).mock.calls.length; + await vi.advanceTimersByTimeAsync(60_000); + expect(vi.mocked(getBackups).mock.calls.length).toBe(calls); + }); + + test('never shows the stored secret key, and sends one only when typed', async () => { + vi.mocked(saveBackups).mockResolvedValue(base); + await renderPanel(); + const key = screen.getByLabelText(/secret key/i) as HTMLInputElement; + expect(key.value).toBe(''); + expect(key.placeholder).toBe('Key saved'); + const save = screen.getByRole('button', { name: /^save$/i }); + expect(save).toHaveProperty('disabled', true); + + await fireEvent.input(screen.getByLabelText(/^bucket$/i), { target: { value: 'music-backup' } }); + await fireEvent.click(save); + await waitFor(() => + expect(saveBackups).toHaveBeenCalledWith({ + enabled: true, + destination: 's3', + folder: '', + endpoint: 'https://s3.example.com', + bucket: 'music-backup', + access_key: 'ak', + secret_key: '', + run_hour: 3, + upload_limit_kib: 4096, + include_music: false + }) + ); + }); + + test('Test destination checks the form as typed and says what it found', async () => { + vi.mocked(testBackups).mockResolvedValue({ backups: 3, latest: '2026-11-02T03:00:05Z' }); + await renderPanel(); + await fireEvent.click(screen.getByRole('button', { name: /test destination/i })); + const out = await screen.findByTestId('backup-test'); + expect(out.textContent).toMatch(/Reached it\.\s+3 backups there, the newest from /); + }); + + test('a refused test shows the destination’s answer', async () => { + vi.mocked(testBackups).mockRejectedValue({ + code: 'destination_failed', + message: 'HTTP 404 NoSuchBucket: there is no bucket by that name' + }); + await renderPanel(); + await fireEvent.click(screen.getByRole('button', { name: /test destination/i })); + expect((await screen.findByTestId('backup-test')).textContent).toMatch( + /Couldn't reach the backup destination\. HTTP 404 NoSuchBucket/ + ); + }); + + test('with the music included, says how much of the library the backup holds', async () => { + await renderPanel( + status({ + config: { ...base.config, include_music: true }, + music: { total_files: 10, total_bytes: 300_000_000, sent_files: 4, sent_bytes: 120_000_000, refused_files: 0, refused: [] }, + runs: [ + { + ...base.runs[0], + music_files: 4, + music_bytes: 120_000_000, + music_note: 'Music stopped for tonight after 6 hours; it carries on with the next backup.' + } + ] + }) + ); + const music = screen.getByTestId('backup-music').textContent?.replace(/\s+/g, ' ') ?? ''; + expect(music).toMatch(/4 of 10 files backed up · 120 MB of 300 MB/); + expect(music).toMatch(/The rest goes with the next backups\./); + const runs = screen.getByRole('list', { name: /latest backups/i }).textContent?.replace(/\s+/g, ' ') ?? ''; + expect(runs).toMatch(/Music: 4 files · 120 MB/); + expect(runs).toMatch(/carries on with the next backup/); + }); + + test('a file the destination refused is named with its answer', async () => { + await renderPanel( + status({ + config: { ...base.config, include_music: true }, + music: { + total_files: 2, + total_bytes: 20, + sent_files: 1, + sent_bytes: 10, + refused_files: 1, + refused: [{ path: '/music/A/one.flac', error: 'HTTP 403 AccessDenied: object is locked', at: '2026-11-02T03:00:09Z' }] + } + }) + ); + const refused = screen.getByRole('list', { name: /refused files/i }); + expect(refused.textContent).toMatch(/\/music\/A\/one\.flac/); + expect(refused.textContent).toMatch(/object is locked/); + expect(screen.getByTestId('backup-music').textContent).not.toMatch(/The rest goes/); + }); + + test('the music switch is off by default and, switched on, says how a changed file is kept', async () => { + vi.mocked(saveBackups).mockResolvedValue(base); + await renderPanel(); + const music = screen.getByRole('switch', { name: /include the music/i }) as HTMLInputElement; + expect(music.checked).toBe(false); + expect(screen.queryByTestId('backup-music-retention')).toBeNull(); + await fireEvent.click(music); + expect(screen.getByTestId('backup-music-retention').textContent).toMatch(/retention/); + await fireEvent.click(screen.getByRole('button', { name: /^save$/i })); + await waitFor(() => expect(saveBackups).toHaveBeenCalledWith(expect.objectContaining({ include_music: true }))); + }); + + test('the folder destination asks for a path, not a bucket', async () => { + await renderPanel(status({ config: { ...base.config, destination: 'folder', folder: '/backups' } })); + expect(screen.getByRole('textbox', { name: /^folder$/i })).toHaveProperty('value', '/backups'); + expect(screen.queryByLabelText(/^bucket$/i)).toBeNull(); + }); +}); diff --git a/web/src/lib/components/admin/BackupSettings.svelte b/web/src/lib/components/admin/BackupSettings.svelte new file mode 100644 index 00000000..30939159 --- /dev/null +++ b/web/src/lib/components/admin/BackupSettings.svelte @@ -0,0 +1,206 @@ + + + + + + + + (draft.destination = v)} + /> + + + {#if draft.destination === 'folder'} + + + + {:else} + + + + + + + + + + + + + + + + {/if} + + + + + {#if draft.include_music} +

    + A changed file goes to the same name. On a bucket that keeps versions or locks objects, set its retention to + keep only what you want. +

    + {/if} + + + + + +
    +
    + + +
    + {#if testError} + + {:else if check} +

    + Reached it. + {#if check.backups === 0} + No backups there yet. + {:else} + {plural(check.backups, 'backup', 'backups')} there, the newest from {when(check.latest!)}. + {/if} +

    + {/if} +
    +
    diff --git a/web/src/lib/components/admin/LookupSettingsCard.svelte b/web/src/lib/components/admin/LookupSettingsCard.svelte new file mode 100644 index 00000000..de4e6187 --- /dev/null +++ b/web/src/lib/components/admin/LookupSettingsCard.svelte @@ -0,0 +1,81 @@ + + + + {#if settings} + {#each rows as row (row.key)} + + flip(row.key, e.currentTarget.checked)} + class="h-4 w-4 cursor-pointer accent-accent" + /> + + {/each} + {:else if loadError} +

    + Couldn't load these settings. + +

    + {:else} +

    Loading…

    + {/if} +
    diff --git a/web/src/lib/components/admin/LookupSettingsCard.test.ts b/web/src/lib/components/admin/LookupSettingsCard.test.ts new file mode 100644 index 00000000..c8b1fb73 --- /dev/null +++ b/web/src/lib/components/admin/LookupSettingsCard.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; + +vi.mock('#lib/api/admin.js', () => ({ + getLookupSettings: vi.fn(), + updateLookupSettings: vi.fn() +})); +vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); + +import LookupSettingsCard from './LookupSettingsCard.svelte'; +import { getLookupSettings, updateLookupSettings } from '#lib/api/admin.js'; +import { pushToast } from '#lib/stores/toast.svelte.js'; + +const bothOn = { listenbrainz_similarity: true, musicbrainz_track_lists: true }; + +afterEach(() => vi.clearAllMocks()); + +describe('LookupSettingsCard', () => { + test('shows both lookups on, and saves a switch as it is flipped', async () => { + vi.mocked(getLookupSettings).mockResolvedValue(bothOn); + vi.mocked(updateLookupSettings).mockImplementation(async (s) => s); + render(LookupSettingsCard); + + const lb = await screen.findByRole('switch', { name: /listenbrainz similar songs/i }); + const mb = screen.getByRole('switch', { name: /musicbrainz track lists/i }); + expect(lb).toBeChecked(); + expect(mb).toBeChecked(); + + await fireEvent.click(lb); + await waitFor(() => + expect(updateLookupSettings).toHaveBeenCalledWith({ + listenbrainz_similarity: false, + musicbrainz_track_lists: true + }) + ); + await waitFor(() => expect(lb).not.toBeChecked()); + expect(mb).toBeChecked(); + }); + + test('a failed save puts the switch back and says so', async () => { + vi.mocked(getLookupSettings).mockResolvedValue(bothOn); + vi.mocked(updateLookupSettings).mockRejectedValue(new Error('offline')); + render(LookupSettingsCard); + + const mb = await screen.findByRole('switch', { name: /musicbrainz track lists/i }); + await fireEvent.click(mb); + await waitFor(() => expect(pushToast).toHaveBeenCalled()); + expect(mb).toBeChecked(); + }); +}); diff --git a/web/src/lib/components/admin/SmtpSettings.svelte b/web/src/lib/components/admin/SmtpSettings.svelte index 5e99a36f..389f09f1 100644 --- a/web/src/lib/components/admin/SmtpSettings.svelte +++ b/web/src/lib/components/admin/SmtpSettings.svelte @@ -25,7 +25,7 @@ username: '', password: '', from_address: '', - from_name: 'Minstrel', + from_name: 'Fabled Minstrel', use_tls: true }); let passwordInput = $state(''); diff --git a/web/src/lib/components/admin/backupTime.ts b/web/src/lib/components/admin/backupTime.ts new file mode 100644 index 00000000..7efb5747 --- /dev/null +++ b/web/src/lib/components/admin/backupTime.ts @@ -0,0 +1,14 @@ +/** An exact moment in the viewer's own zone, with its date. */ +export function when(iso: string): string { + return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }); +} + +/** + * The server keeps the run hour in UTC; this is that hour on the viewer's + * clock today. Today's offset is used, so across daylight saving the local + * label moves while the run stays at the same UTC hour. + */ +export function hourLabel(utcHour: number, now: Date = new Date()): string { + const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), utcHour)); + return d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' }); +} diff --git a/web/src/lib/components/auth/RestoreForm.svelte b/web/src/lib/components/auth/RestoreForm.svelte new file mode 100644 index 00000000..1bffc939 --- /dev/null +++ b/web/src/lib/components/auth/RestoreForm.svelte @@ -0,0 +1,98 @@ + + +{#if done} +
    +

    + Restored {plural(done.accounts, 'account', 'accounts')}. + {done.restarting + ? 'Minstrel is restarting to load them; in a few seconds, sign in with the password you had.' + : 'Sign in with the password you had.'} +

    +

    + The library scan finds each music file and fetches the artwork and tags again. +

    +

    + Subsonic apps are signed out: each person makes a new Subsonic password, and saves their + ListenBrainz token again, in Settings › Connections. +

    + Sign in +
    +{:else} +
    + + + + {#if error} + + {/if} +
    +{/if} diff --git a/web/src/lib/components/queue-row-math.test.ts b/web/src/lib/components/queue-row-math.test.ts index b31f032c..bae95812 100644 --- a/web/src/lib/components/queue-row-math.test.ts +++ b/web/src/lib/components/queue-row-math.test.ts @@ -1,40 +1,23 @@ import { describe, it, expect } from 'vitest'; import { offsetToDelta } from './queue-row-math'; +// A drag moves a row by the whole rows it crosses, counting half a row or +// more as one. A row of no height moves nothing. describe('offsetToDelta', () => { - it('returns 0 for zero offset', () => { - expect(offsetToDelta(0, 64)).toBe(0); - }); - - it('returns 1 for a full row down', () => { - expect(offsetToDelta(64, 64)).toBe(1); - }); - - it('rounds half-rows down (just under midpoint)', () => { - expect(offsetToDelta(31, 64)).toBe(0); - }); - - it('rounds half-rows up (at or past midpoint)', () => { - expect(offsetToDelta(32, 64)).toBe(1); - }); - - it('handles negative offsets symmetrically (drag up)', () => { - expect(offsetToDelta(-64, 64)).toBe(-1); - expect(offsetToDelta(-32, 64)).toBe(0); // Math.round(-0.5) === 0 in JS - }); - - it('handles multi-row offsets', () => { - expect(offsetToDelta(192, 64)).toBe(3); - expect(offsetToDelta(-128, 64)).toBe(-2); - }); - - it('returns 0 when rowHeight is non-positive (defensive)', () => { - expect(offsetToDelta(100, 0)).toBe(0); - expect(offsetToDelta(100, -1)).toBe(0); - }); - - it('respects the measured row height (e.g., h-14 = 56px)', () => { - expect(offsetToDelta(56, 56)).toBe(1); - expect(offsetToDelta(28, 56)).toBe(1); // 0.5 → 1 (half-up) + it.each([ + [0, 64, 0], + [64, 64, 1], + [31, 64, 0], + [32, 64, 1], + [56, 56, 1], + [28, 56, 1], + [192, 64, 3], + [-64, 64, -1], + [-32, 64, 0], // Math.round(-0.5) is 0 + [-128, 64, -2], + [100, 0, 0], + [100, -1, 0] + ])('%spx on %spx rows → %s', (offset, rowHeight, want) => { + expect(offsetToDelta(offset, rowHeight)).toBe(want); }); }); diff --git a/web/src/lib/components/settings/SettingsLoadStatus.svelte b/web/src/lib/components/settings/SettingsLoadStatus.svelte new file mode 100644 index 00000000..5434dbc0 --- /dev/null +++ b/web/src/lib/components/settings/SettingsLoadStatus.svelte @@ -0,0 +1,14 @@ + + +{#if failed} +

    + Couldn't load {what}. + +

    +{:else} +

    Loading…

    +{/if} diff --git a/web/src/lib/components/wanted/BlockList.svelte b/web/src/lib/components/wanted/BlockList.svelte deleted file mode 100644 index c30a43a4..00000000 --- a/web/src/lib/components/wanted/BlockList.svelte +++ /dev/null @@ -1,95 +0,0 @@ - - -{#if blocks.isPending} -

    Reading the blocked releases…

    -{:else if blocks.isError && !blocks.isFetchNextPageError} -

    Couldn't load the blocked releases.

    -{:else if items.length === 0} -
    - -

    No releases are blocked.

    -

    - A release you set aside, or one an import found wasn't the album, lands here so it's never - taken again. -

    -
    -{:else} -
      - {#each items as b (b.info_hash)} -
    • -
      -
      {b.name || b.info_hash}
      - {#if b.want_title} -
      For {b.want_artist} – {b.want_title}
      - {/if} -
      {by(b)} {relativeTime(b.blocked_at)}{until(b)}
      - {#if b.detail} -

      {b.detail}

      - {/if} -
      - -
    • - {/each} -
    - - blocks.fetchNextPage()} - /> -{/if} diff --git a/web/src/lib/components/wanted/BlockList.test.ts b/web/src/lib/components/wanted/BlockList.test.ts deleted file mode 100644 index ae4817e0..00000000 --- a/web/src/lib/components/wanted/BlockList.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import { mockInfiniteQuery } from '../../../test-utils/query'; -import type { ReleaseBlock } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', () => ({ - createReleaseBlocksQuery: vi.fn(), - unblockRelease: vi.fn().mockResolvedValue(undefined) -})); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import BlockList from './BlockList.svelte'; -import { createReleaseBlocksQuery, unblockRelease } from '#lib/api/wanted.js'; - -const block: ReleaseBlock = { - info_hash: 'abc123', - name: 'Daft Punk - Random Access Memories (Drumless Edition)', - reason: 'import', - detail: 'The album tag says another version.', - blocked_at: new Date(Date.now() - 3_600_000).toISOString(), - expires_at: null, - want_title: 'Random Access Memories', - want_artist: 'Daft Punk' -}; - -afterEach(() => vi.clearAllMocks()); - -function setup(items: ReleaseBlock[]) { - vi.mocked(createReleaseBlocksQuery).mockReturnValue( - mockInfiniteQuery({ pages: [{ items, total: items.length, limit: 50, offset: 0 }] }) as unknown as ReturnType< - typeof createReleaseBlocksQuery - > - ); - return render(BlockList); -} - -describe('BlockList', () => { - test('a blocked release says why and can be allowed again', async () => { - setup([block]); - expect(screen.getByText(/refused on import/i)).toBeTruthy(); - expect(screen.getByText(/another version/)).toBeTruthy(); - expect(screen.getByText(/for daft punk – random access memories/i)).toBeTruthy(); - await fireEvent.click(screen.getByRole('button', { name: /allow .* again/i })); - await waitFor(() => expect(unblockRelease).toHaveBeenCalledWith('abc123')); - }); - - test('a release given up on says until when it is held back', () => { - setup([{ ...block, reason: 'stalled', detail: 'Nobody was sharing it.', expires_at: '2026-10-17T12:00:00Z' }]); - const line = screen.getByText(/given up on: it would not finish/i).textContent ?? ''; - expect(line).toMatch(/held back until/); - }); - - test('with nothing blocked it says so', () => { - setup([]); - expect(screen.getByText(/no releases are blocked/i)).toBeTruthy(); - }); -}); diff --git a/web/src/lib/components/wanted/CatalogueArtistCard.svelte b/web/src/lib/components/wanted/CatalogueArtistCard.svelte deleted file mode 100644 index 9384c0d0..00000000 --- a/web/src/lib/components/wanted/CatalogueArtistCard.svelte +++ /dev/null @@ -1,46 +0,0 @@ - - - -
    - -
    -
    -
    -
    -
    -
    {a.artist_name}
    -
    {a.held} / {a.albums} held
    - {#if notes.length} -
    {notes.join(' · ')}
    - {/if} -
    -
    diff --git a/web/src/lib/components/wanted/CatalogueGrid.svelte b/web/src/lib/components/wanted/CatalogueGrid.svelte deleted file mode 100644 index e95e09b6..00000000 --- a/web/src/lib/components/wanted/CatalogueGrid.svelte +++ /dev/null @@ -1,72 +0,0 @@ - - -{#if library && !library.listed_at} -

    - Your library's albums are being added to the catalogue. Albums whose tags don't name them are - matched on MusicBrainz first, by their artist, title and tracks, about one a second. -

    -{/if} - -{#if !artists.isPending && (items.length > 0 || q)} -
    - -
    -{/if} - -{#if artists.isPending} -

    Reading the catalogue…

    -{:else if artists.isError && !artists.isFetchNextPageError} -

    Couldn't load the catalogue.

    -{:else if items.length === 0 && q} -

    - No artist in the catalogue, or album of theirs, is named like '{q}'. -

    -{:else if items.length === 0} -
    - -

    The catalogue is empty.

    -

    - Your library's albums land here once it's been scanned, as do the albums users request and - the releases of artists Minstrel follows. -

    -
    -{:else} - a.sort_name || a.artist_name} - hasMore={!!artists.hasNextPage} - onLoadMore={() => artists.fetchNextPage()} - > - {#snippet item(a: WantArtist)} - - {/snippet} - - - artists.fetchNextPage()} - /> -{/if} diff --git a/web/src/lib/components/wanted/CatalogueGrid.test.ts b/web/src/lib/components/wanted/CatalogueGrid.test.ts deleted file mode 100644 index 5c49cf87..00000000 --- a/web/src/lib/components/wanted/CatalogueGrid.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import { mockInfiniteQuery } from '../../../test-utils/query'; -import type { LibraryListing, WantArtist, WantArtistsPage } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', () => ({ createWantArtistsQuery: vi.fn() })); - -import CatalogueGrid from './CatalogueGrid.svelte'; -import { createWantArtistsQuery } from '#lib/api/wanted.js'; - -const DAY = 24 * 3_600_000; -const ago = (ms: number) => new Date(Date.now() - ms).toISOString(); - -function artist(mbid: string, name: string, extra: Partial = {}): WantArtist { - return { - artist_mbid: mbid, - artist_name: name, - sort_name: name, - image_url: `/api/catalogue/art/artist/${mbid}`, - albums: 4, - held: 3, - wanted: 1, - missing: 0, - downloading: 0, - following: false, - ...extra - }; -} - -function setup( - items: WantArtist[] = [ - artist('blur', 'Blur', { following: true, downloading: 1 }), - artist('beatles', 'The Beatles', { sort_name: 'Beatles, The', albums: 13, held: 13, wanted: 0 }) - ], - library: LibraryListing = { listed_at: ago(DAY), unlisted: 0 } -) { - const page: WantArtistsPage = { - items, - total: items.length, - limit: 96, - offset: 0, - counts: { artists: items.length, wanted: 1, missing: 0, held: 16, upgrades: 0, following: 1, activity: 1, attention: 0, blocked: 0, unmatched: 0 }, - library - }; - vi.mocked(createWantArtistsQuery).mockReturnValue( - mockInfiniteQuery({ pages: [page] }) as unknown as ReturnType - ); - return render(CatalogueGrid); -} - -afterEach(() => vi.clearAllMocks()); - -describe('CatalogueGrid', () => { - test('each artist is a card: how many albums are held, and whether they are followed', () => { - setup(); - const cards = screen.getAllByTestId('catalogue-artist'); - expect(cards.map((c) => c.getAttribute('href'))).toEqual(['/collection/artist/blur', '/collection/artist/beatles']); - expect(cards[0].textContent?.replace(/\s+/g, ' ')).toMatch(/Blur 3 \/ 4 held Following · 1 downloading/); - const bar = screen.getByRole('progressbar', { name: '13 of 13 albums held' }); - expect(bar.getAttribute('aria-valuenow')).toBe('13'); - expect((bar.firstElementChild as HTMLElement).style.width).toBe('100%'); - }); - - test('the alphabet rail files an artist under their sort name', () => { - setup(); - expect(document.getElementById('alpha-B')?.textContent).toMatch(/Blur/); - }); - - test('the filter asks the server for artists by name or album', async () => { - setup(); - await fireEvent.input(screen.getByRole('searchbox', { name: /filter artists and albums/i }), { - target: { value: 'parklife' } - }); - await waitFor(() => expect(createWantArtistsQuery).toHaveBeenLastCalledWith('parklife')); - }); - - test('an empty catalogue says what lands there', () => { - setup([]); - expect(screen.getByText(/the catalogue is empty/i)).toBeTruthy(); - }); - - test('says while the library is being listed', () => { - setup([], { listed_at: null, unlisted: 0 }); - expect(screen.getByTestId('library-listing').textContent).toMatch(/being added to the catalogue/i); - }); -}); diff --git a/web/src/lib/components/wanted/CollectionRail.svelte b/web/src/lib/components/wanted/CollectionRail.svelte deleted file mode 100644 index 56a12be5..00000000 --- a/web/src/lib/components/wanted/CollectionRail.svelte +++ /dev/null @@ -1,33 +0,0 @@ - - - diff --git a/web/src/lib/components/wanted/DownloadList.svelte b/web/src/lib/components/wanted/DownloadList.svelte deleted file mode 100644 index ee3222d8..00000000 --- a/web/src/lib/components/wanted/DownloadList.svelte +++ /dev/null @@ -1,264 +0,0 @@ - - -{#each clientsDown as c (c.client)} -

    - Can't reach the download client {c.client} since {relativeTime(c.since)}: {c.detail}. Its - downloads are left as they are until it answers. -

    -{/each} - -{#if downloads.isPending} -

    Reading the downloads…

    -{:else if downloads.isError && !downloads.isFetchNextPageError} -

    Couldn't load the downloads.

    -{:else if items.length === 0} -
    - -

    Nothing has been downloaded yet.

    -

    - A release the search takes, or one you take from a want's Releases, shows here while it - downloads and once it's imported. -

    -
    -{:else} -
      - {#each items as d (d.id)} -
    • -
      -
      -
      - {d.want_artist ? `${d.want_artist} – ${d.want_title}` : d.name} -
      -
      - {d.name}{#if d.quality} · {d.quality}{/if} -
      -
      - - {label(d)} - -
      - - {#if !d.ended_at && (d.import_state === 'downloading' || d.import_state === '')} -
      -
      -
      - {/if} - - {#if running(d) && d.condition} -

      {condition(d.condition)}

      - {/if} - {#if ending(d)} -

      {ending(d)}

      - {/if} - {#if d.import_reason} -

      - {d.import_reason} -

      - {/if} - {#if d.evidence} -

      {counted(d.evidence)}

      - {/if} - {#if filed(d)} -

      {filed(d)}

      - {/if} - {#if seeded(d)} -

      {seeded(d)}

      - {/if} - {#if d.rehomed_from} -

      Taken for {d.rehomed_from}; it turned out to be this album.

      - {/if} -

      {when(d)}

      - - {#if running(d)} -
      - -
      - {:else if needsYou(d)} -
      - {#if d.import_state === 'review'} - - {:else} - - {/if} - -
      - {/if} -
    • - {/each} -
    - - downloads.fetchNextPage()} - /> -{/if} diff --git a/web/src/lib/components/wanted/DownloadList.test.ts b/web/src/lib/components/wanted/DownloadList.test.ts deleted file mode 100644 index 605b42e2..00000000 --- a/web/src/lib/components/wanted/DownloadList.test.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import { mockInfiniteQuery } from '../../../test-utils/query'; -import type { ClientDown, Download } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', () => ({ - createDownloadsQuery: vi.fn(), - importAnyway: vi.fn().mockResolvedValue(undefined), - retryImport: vi.fn().mockResolvedValue(undefined), - refuseDownload: vi.fn().mockResolvedValue(undefined), - abandonDownload: vi.fn().mockResolvedValue(undefined) -})); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import DownloadList from './DownloadList.svelte'; -import { abandonDownload, createDownloadsQuery, importAnyway, refuseDownload, retryImport } from '#lib/api/wanted.js'; - -const ago = (ms: number) => new Date(Date.now() - ms).toISOString(); - -function download(id: string, extra: Partial = {}): Download { - return { - id, - want_id: 'w1', - want_title: 'Random Access Memories', - want_artist: 'Daft Punk', - name: 'Daft Punk - Random Access Memories (2013) [FLAC]', - indexer: 'Prowlarr', - client: 'qbittorrent', - quality: 'lossless', - origin: 'schedule', - grabbed_at: ago(3_600_000), - ended_at: null, - end_reason: '', - progress: 0, - import_state: 'downloading', - import_reason: '', - imported_at: null, - imported_files: 0, - destination: '', - files: [], - skipped: 0, - end_detail: '', - seeding: false, - ratio: 0, - seed_released_at: null, - condition: null, - ...extra - }; -} - -afterEach(() => vi.clearAllMocks()); - -function setup(items: Download[], clientsDown: ClientDown[] = []) { - // The Activity page carries the clients not answering beside its items. - const page = { items, total: items.length, limit: 50, offset: 0, clients_down: clientsDown }; - vi.mocked(createDownloadsQuery).mockReturnValue( - mockInfiniteQuery({ pages: [page] }) as unknown as ReturnType< - typeof createDownloadsQuery - > - ); - return render(DownloadList); -} - -describe('DownloadList', () => { - test('a running download shows how far it has got, and can be given up', async () => { - setup([download('d1', { progress: 0.375 })]); - expect(screen.getByTestId('download-state').textContent).toMatch(/downloading/i); - expect(screen.getByRole('progressbar', { name: /downloaded/i }).getAttribute('aria-valuenow')).toBe('37'); - expect(screen.queryByTestId('download-condition')).toBeNull(); - await fireEvent.click(screen.getByRole('button', { name: /give up/i })); - await waitFor(() => expect(abandonDownload).toHaveBeenCalledWith('d1')); - }); - - test('a stalled download says what is wrong and how often it was asked for again', () => { - setup([ - download('d1', { - progress: 0.4, - condition: { trigger: 'no_peers', detail: 'Nobody has shared it in 7 hours; 40% downloaded.', retries: 2, since: ago(1_200_000) } - }) - ]); - expect(screen.getByTestId('download-condition').textContent).toMatch( - /nobody has shared it in 7 hours; 40% downloaded\. asked for again 2 of 3 times/i - ); - }); - - test('a download given up on says why it ended', () => { - setup([ - download('d1', { - ended_at: ago(60_000), - end_reason: 'stalled', - end_detail: 'Taken 7 hours ago and never finished: nobody was sharing it. Held back until 17 Oct.' - }) - ]); - expect(screen.getByTestId('download-state').textContent).toMatch(/given up/i); - expect(screen.getByTestId('download-ending').textContent).toMatch(/nobody was sharing it/); - expect(screen.queryByRole('button')).toBeNull(); - }); - - test('a download client that does not answer is named above the list', () => { - setup([download('d1')], [{ client: 'qbittorrent', detail: 'connection refused', since: ago(600_000) }]); - expect(screen.getByTestId('client-down').textContent).toMatch(/can't reach the download client qbittorrent .*connection refused/i); - }); - - test('a doubtful download says why and can be imported anyway or refused', async () => { - setup([ - download('d1', { - import_state: 'review', - import_reason: 'Only the lengths agree. A person decides.', - evidence: { files: 13, tracks: 13, identified: 0, recordings: 0, lengths: 13, titles: 0, fingerprinted: false } - }) - ]); - expect(screen.getByTestId('download-state').textContent).toMatch(/needs you/i); - expect(screen.getByTestId('download-reason').textContent).toMatch(/a person decides/i); - expect(screen.getByText(/13 files against 13 tracks · no AcoustID · 13 lengths agree/)).toBeTruthy(); - await fireEvent.click(screen.getByRole('button', { name: /import anyway/i })); - await waitFor(() => expect(importAnyway).toHaveBeenCalledWith('d1')); - await fireEvent.click(screen.getByRole('button', { name: /refuse/i })); - await waitFor(() => expect(refuseDownload).toHaveBeenCalledWith('d1')); - }); - - test('a failed import can be tried again', async () => { - setup([download('d1', { import_state: 'failed', import_reason: 'The library folder is not writable.' })]); - expect(screen.queryByRole('button', { name: /import anyway/i })).toBeNull(); - await fireEvent.click(screen.getByRole('button', { name: /try again/i })); - await waitFor(() => expect(retryImport).toHaveBeenCalledWith('d1')); - }); - - test('an imported download says what was filed where', () => { - setup([ - download('d1', { - ended_at: ago(60_000), - end_reason: 'imported', - import_state: 'imported', - imported_at: ago(60_000), - imported_files: 12, - skipped: 1, - destination: '/music/Daft Punk/Random Access Memories (2013)' - }) - ]); - expect(screen.getByTestId('download-state').textContent).toMatch(/imported/i); - expect(screen.getByText(/12 tracks filed, 1 already held into \/music\/Daft Punk/)).toBeTruthy(); - expect(screen.queryByRole('button')).toBeNull(); - }); - - test('an imported download says how its seeding goes', () => { - const imported = { ended_at: ago(60_000), end_reason: 'imported', import_state: 'imported' as const }; - setup([ - download('d1', { ...imported, seeding: true, ratio: 0.8 }), - download('d2', { ...imported, seeding: true, ratio: 2.1, seed_released_at: ago(60_000) }) - ]); - const lines = screen.getAllByTestId('download-seeding').map((e) => e.textContent); - expect(lines[0]).toMatch(/seeding: share ratio 0\.80/i); - expect(lines[1]).toMatch(/seeded, then removed/i); - }); - - test('with nothing downloaded it says what lands here', () => { - setup([]); - expect(screen.getByText(/nothing has been downloaded yet/i)).toBeTruthy(); - }); -}); diff --git a/web/src/lib/components/wanted/FollowList.svelte b/web/src/lib/components/wanted/FollowList.svelte deleted file mode 100644 index f5702487..00000000 --- a/web/src/lib/components/wanted/FollowList.svelte +++ /dev/null @@ -1,118 +0,0 @@ - - -{#if follows.isPending} -

    Reading who's followed…

    -{:else if follows.isError} -

    Couldn't load the followed artists.

    -{:else if (follows.data ?? []).length === 0} -

    No artists are followed. Follow one from its artist page.

    -{:else} -
      - {#each follows.data ?? [] as f (f.artist_mbid)} -
    • - -
      -
      - {#if f.artist_id} - {f.artist_name} - {:else} - {f.artist_name} - {/if} -
      -
      - {plural(f.open_wants, 'album wanted', 'albums wanted')} · - {f.checked_at ? `checked ${relativeTime(f.checked_at)}` : 'not checked yet'} -
      -
      - - -
    • - {/each} -
    -{/if} diff --git a/web/src/lib/components/wanted/FollowList.test.ts b/web/src/lib/components/wanted/FollowList.test.ts deleted file mode 100644 index 7ae23c05..00000000 --- a/web/src/lib/components/wanted/FollowList.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import { mockQuery } from '../../../test-utils/query'; -import type { Follow, ReleaseProfilesResponse } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', () => ({ - createFollowsQuery: vi.fn(), - createReleaseProfilesQuery: vi.fn(), - putFollow: vi.fn().mockResolvedValue({ following: true }), - deleteFollow: vi.fn().mockResolvedValue(undefined) -})); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import FollowList from './FollowList.svelte'; -import { createFollowsQuery, createReleaseProfilesQuery, deleteFollow, putFollow } from '#lib/api/wanted.js'; - -const ago = (ms: number) => new Date(Date.now() - ms).toISOString(); - -const follow: Follow = { - artist_mbid: 'blur', - artist_name: 'Blur', - artist_id: 'art-1', - profile_id: 'p-std', - profile_name: 'Standard', - followed_at: ago(10 * 86_400_000), - checked_at: ago(3 * 3_600_000), - open_wants: 2, - image_url: '' -}; - -const profiles: ReleaseProfilesResponse = { - profiles: [ - { id: 'p-std', name: 'Standard', primary_types: ['Album'], secondary_types: [], is_default: true, follow_count: 1 }, - { id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 } - ], - primary_types: ['Album'], - secondary_types: ['Live'] -}; - -afterEach(() => vi.clearAllMocks()); - -function setup(follows: Follow[] = [follow]) { - vi.mocked(createFollowsQuery).mockReturnValue( - mockQuery({ data: follows }) as unknown as ReturnType - ); - vi.mocked(createReleaseProfilesQuery).mockReturnValue( - mockQuery({ data: profiles }) as unknown as ReturnType - ); - return render(FollowList); -} - -describe('FollowList', () => { - test('lists artists; the profile can change and the artist be unfollowed', async () => { - setup(); - expect(screen.getAllByTestId('follow-row')).toHaveLength(1); - expect(screen.getByText(/2 albums wanted/)).toBeTruthy(); - - const select = screen.getByLabelText(/profile for blur/i) as HTMLSelectElement; - expect(select.value).toBe('p-std'); - await fireEvent.change(select, { target: { value: 'p-live' } }); - await waitFor(() => - expect(putFollow).toHaveBeenCalledWith('blur', { artist_name: 'Blur', profile_id: 'p-live' }) - ); - - await fireEvent.click(screen.getByRole('button', { name: /unfollow blur/i })); - await waitFor(() => expect(deleteFollow).toHaveBeenCalledWith('blur')); - }); - - test('with no follows it says where to follow from', () => { - setup([]); - expect(screen.getByText(/follow one from its artist page/i)).toBeTruthy(); - }); -}); diff --git a/web/src/lib/components/wanted/UnmatchedList.svelte b/web/src/lib/components/wanted/UnmatchedList.svelte deleted file mode 100644 index aaaeb93d..00000000 --- a/web/src/lib/components/wanted/UnmatchedList.svelte +++ /dev/null @@ -1,150 +0,0 @@ - - -{#if unmatched.isPending} -

    Reading the unmatched albums…

    -{:else if unmatched.isError} -

    Couldn't load the unmatched albums.

    -{:else} - {#if toMatch.length === 0} -
    - -

    Every album in your library is matched.

    -

    - An album no MusicBrainz album matches by its artist, title and tracks lands here, to be - matched by hand or left off. -

    -
    - {:else} -

    - No MusicBrainz album matched {toMatch.length === 1 ? 'this album' : `these ${toMatch.length} albums`} - by artist, title and tracks, so {toMatch.length === 1 ? "it isn't" : "they aren't"} fetched back if - {toMatch.length === 1 ? 'its' : 'their'} files go missing. Match each to its MusicBrainz album, or - leave it off if MusicBrainz doesn't have it. -

    -
      - {#each toMatch as u (u.album_id)} -
    • -
      -
      - {u.title} -
      {u.artist} · {plural(u.tracks, 'track', 'tracks')}
      -

      {u.detail}

      -
      -
      - - -
      -
      - {#if open === u.album_id} - onMatch(u, ref)} /> - {/if} -
    • - {/each} -
    - {/if} - - {#if leftOff.length > 0} -
    -

    Left off

    -

    - Kept in the library, never matched again, and not fetched back if their files go missing. -

    -
      - {#each leftOff as u (u.album_id)} -
    • -
      - {u.title} -
      - {u.artist} · {plural(u.tracks, 'track', 'tracks')} · left off {relativeTime(u.decided_at)} -
      -
      - -
    • - {/each} -
    -
    - {/if} -{/if} diff --git a/web/src/lib/components/wanted/UnmatchedList.test.ts b/web/src/lib/components/wanted/UnmatchedList.test.ts deleted file mode 100644 index 2245246c..00000000 --- a/web/src/lib/components/wanted/UnmatchedList.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import type { CatalogueSearchResult, UnmatchedAlbum } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', async () => { - const { mockQuery } = await import('../../../test-utils/query'); - return { - createUnmatchedQuery: vi.fn(() => mockQuery({ data: [] })), - matchUnmatched: vi.fn().mockResolvedValue({ - release_group_mbid: 'rg-1', - title: 'Songs for the Deaf', - artist: 'Queens of the Stone Age', - agree: 9, - tracks: 10 - }), - leaveUnmatchedOff: vi.fn().mockResolvedValue(undefined), - putUnmatchedBack: vi.fn().mockResolvedValue(undefined) - }; -}); -vi.mock('#lib/api/catalogue.js', () => ({ createCatalogueSearchQuery: vi.fn() })); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import UnmatchedList from './UnmatchedList.svelte'; -import { mockQuery } from '../../../test-utils/query'; -import { createUnmatchedQuery, leaveUnmatchedOff, matchUnmatched, putUnmatchedBack } from '#lib/api/wanted.js'; -import { createCatalogueSearchQuery } from '#lib/api/catalogue.js'; -import { pushToast } from '#lib/stores/toast.svelte.js'; - -const DAY = 24 * 3_600_000; - -function album(id: string, title: string, artist: string, extra: Partial = {}): UnmatchedAlbum { - return { - album_id: id, - title, - artist, - detail: `MusicBrainz has no album called "${title}" by ${artist}.`, - tracks: 10, - left_off: false, - decided_at: new Date(Date.now() - 2 * DAY).toISOString(), - ...extra - }; -} - -const result: CatalogueSearchResult = { - mbid: 'rg-1', - name: 'Songs for the Deaf', - secondary_text: 'Queens of the Stone Age · 2002 · Album', - image_url: '', - artist_mbid: 'qotsa', - album_mbid: '', - in_library: false, - requested: false -}; - -afterEach(() => vi.clearAllMocks()); - -function setup(items: UnmatchedAlbum[], results: CatalogueSearchResult[] = [result]) { - vi.mocked(createUnmatchedQuery).mockReturnValue( - mockQuery({ data: items }) as unknown as ReturnType - ); - vi.mocked(createCatalogueSearchQuery).mockReturnValue( - mockQuery({ data: results }) as unknown as ReturnType - ); - return render(UnmatchedList); -} - -describe('UnmatchedList', () => { - test('each unmatched album says why, with its tracks, and links to the album', () => { - setup([album('al-1', 'Dial Tone', 'Annadale', { tracks: 1 })]); - const row = screen.getByTestId('unmatched-row'); - expect(row.textContent).toMatch(/Annadale · 1 track/); - expect(row.textContent).toMatch(/no album called "Dial Tone"/); - expect(screen.getByRole('link', { name: 'Dial Tone' }).getAttribute('href')).toBe('/albums/al-1'); - }); - - test('Match searches MusicBrainz for the album by its own title and artist, and matches a result', async () => { - setup([album('al-2', 'Songs for the Deaf', 'Queens of the Stone Age')]); - await fireEvent.click(screen.getByRole('button', { name: /match…/i })); - expect(createCatalogueSearchQuery).toHaveBeenLastCalledWith('Songs for the Deaf Queens of the Stone Age', 'album'); - await fireEvent.click(screen.getByRole('button', { name: /match to songs for the deaf/i })); - await waitFor(() => expect(matchUnmatched).toHaveBeenCalledWith('al-2', 'rg-1')); - await waitFor(() => expect(pushToast).toHaveBeenCalledWith(expect.stringMatching(/9 of 10 tracks agree/))); - }); - - test('a pasted MusicBrainz link matches the album', async () => { - setup([album('al-3', '+++', 'DROELOE')]); - await fireEvent.click(screen.getByRole('button', { name: /match…/i })); - const link = 'https://musicbrainz.org/release/11111111-0000-4000-8000-000000000003'; - await fireEvent.input(screen.getByRole('textbox', { name: /musicbrainz album link/i }), { target: { value: link } }); - await fireEvent.click(screen.getByRole('button', { name: /^match$/i })); - await waitFor(() => expect(matchUnmatched).toHaveBeenCalledWith('al-3', link)); - }); - - test("a local band's album is left off, and one left off can be put back", async () => { - setup([album('al-1', 'Dial Tone', 'Annadale'), album('al-4', 'Demo', 'Annadale', { left_off: true })]); - await fireEvent.click(screen.getByRole('button', { name: /leave it off/i })); - await waitFor(() => expect(leaveUnmatchedOff).toHaveBeenCalledWith('al-1')); - const leftOff = screen.getByTestId('left-off-row'); - expect(leftOff.textContent).toMatch(/left off 2d ago/); - await fireEvent.click(screen.getByRole('button', { name: /put back/i })); - await waitFor(() => expect(putUnmatchedBack).toHaveBeenCalledWith('al-4')); - }); - - test('with every album matched it says so, and still lists those left off', () => { - setup([album('al-4', 'Demo', 'Annadale', { left_off: true })]); - expect(screen.getByText(/every album in your library is matched/i)).toBeTruthy(); - expect(screen.getByTestId('left-off')).toBeTruthy(); - }); -}); diff --git a/web/src/lib/components/wanted/UnmatchedMatch.svelte b/web/src/lib/components/wanted/UnmatchedMatch.svelte deleted file mode 100644 index b09059fc..00000000 --- a/web/src/lib/components/wanted/UnmatchedMatch.svelte +++ /dev/null @@ -1,106 +0,0 @@ - - -
    -
    { - e.preventDefault(); - asked = text.trim(); - }} - > - - -
    - - {#if search.isPending && asked} -

    Asking MusicBrainz…

    - {:else if search.isError} -

    Couldn't reach MusicBrainz. A pasted link works the same.

    - {:else if asked && results.length === 0} -

    MusicBrainz has no album like that.

    - {:else if results.length > 0} -
      - {#each results as r (r.mbid)} -
    • -
      -
      {r.name}
      -
      {r.secondary_text}
      -
      - MusicBrainz - -
    • - {/each} -
    - {/if} - -
    { - e.preventDefault(); - if (link.trim()) onMatch(link.trim()); - }} - > - - -
    -
    diff --git a/web/src/lib/components/wanted/WantList.svelte b/web/src/lib/components/wanted/WantList.svelte deleted file mode 100644 index 65838a73..00000000 --- a/web/src/lib/components/wanted/WantList.svelte +++ /dev/null @@ -1,308 +0,0 @@ - - -{#if artist && head} -
    -
    - -
    -
    - ← Catalogue -

    {head.artist_name}

    -

    - {head.held} of {plural(head.albums, 'album', 'albums')} held{head.wanted ? ` · ${head.wanted} wanted` : ''}{head.missing - ? ` · ${head.missing} with files missing` - : ''}{head.downloading ? ` · ${head.downloading} downloading` : ''} -

    -
    - - {#if head.artist_id} - Open in the library - {/if} -
    -
    -
    -{/if} - -{#if !artist && !wants.isPending && (items.length > 0 || q)} -
    - -
    -{/if} - -{#if wants.isPending} -

    Reading the wanted list…

    -{:else if wants.isError && !wants.isFetchNextPageError} -

    Couldn't load {artist ? "this artist's albums" : 'the wanted list'}.

    -{:else if items.length === 0 && q} -

    - Nothing on this list has an artist or album named like '{q}'. -

    -{:else if items.length === 0} -
    - -

    - {#if artist}None of this artist's albums are in the catalogue. - {:else if list === 'upgrade'}No album is wanted for a better copy. - {:else}Nothing is wanted.{/if} -

    -

    - {#if list === 'upgrade'} - An album you have below the quality set under - Acquisition, or with a video - rip among its tracks, lands here. - {:else} - A request you approve, a new release from a followed artist, or an album whose files went - missing lands here. - {/if} -

    -
    -{:else} -
    - {#each sections as a, i (a.key + ':' + i)} -
    - {#if !artist}

    - - {#if a.mbid} - {a.name} - {:else} - {a.name} - {/if} - - {plural(a.wants.length, 'album', 'albums')} -

    {/if} -
      - {#each a.wants as w (w.id)} -
    • -
      - -
      -
      - {#if w.album_id && w.held_at} - {w.title} - {:else} - {w.title} - {/if} - {#if kind(w)} · {kind(w)}{/if} -
      -
      - {why(w)} · {w.held_at ? `held ${relativeTime(w.held_at)}` : `wanted ${relativeTime(w.wanted_at)}`} -
      - {#if w.held_at && w.upgrade} -
      {upgradeLine(w)}
      - {/if} - {#if searchable(w)} -
      - {wantStatus(w)} - {#if needsYou(w)} - Decide on Activity - {/if} -
      - {:else if arrived(w)} -
      {arrived(w)}
      - {/if} -
      -
      - - {#if searchable(w)} - - - {/if} - -
      -
      - {#if shown === w.id} -
      - -
      - {/if} - {#if open === w.id && searchable(w)} -
      - -
      - {/if} -
    • - {/each} -
    -
    - {/each} -
    - - wants.fetchNextPage()} - /> -{/if} diff --git a/web/src/lib/components/wanted/WantList.test.ts b/web/src/lib/components/wanted/WantList.test.ts deleted file mode 100644 index 662f2ed0..00000000 --- a/web/src/lib/components/wanted/WantList.test.ts +++ /dev/null @@ -1,345 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; -import { mockInfiniteQuery, mockQuery } from '../../../test-utils/query'; -import type { LibraryListing, Want, WantGrab, WantsPage } from '#lib/api/types.js'; - -vi.mock('#lib/api/wanted.js', async () => { - const { mockQuery } = await import('../../../test-utils/query'); - return { - // The artist page's FollowControl. - createFollowQuery: vi.fn(() => mockQuery({ data: { following: true } })), - createReleaseProfilesQuery: vi.fn(() => mockQuery({ data: { profiles: [], primary_types: [], secondary_types: [] } })), - putFollow: vi.fn(), - deleteFollow: vi.fn(), - createWantsQuery: vi.fn(), - removeWant: vi.fn().mockResolvedValue(undefined), - searchWant: vi.fn().mockResolvedValue({ - outcome: 'nothing', considered: 0, best_release: '', best_verdict: '', narrowed: [] - }), - createCandidatesQuery: vi.fn(), - createWantTracksQuery: vi.fn(), - grabCandidate: vi.fn(), - blockCandidate: vi.fn(), - unblockRelease: vi.fn() - }; -}); -vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() })); - -import WantList from './WantList.svelte'; -import { pushToast } from '#lib/stores/toast.svelte.js'; -import { createCandidatesQuery, createWantTracksQuery, createWantsQuery, removeWant, searchWant } from '#lib/api/wanted.js'; -import type { WantState, WantTracks } from '#lib/api/types.js'; - -const DAY = 24 * 3_600_000; -const ago = (ms: number) => new Date(Date.now() - ms).toISOString(); - -function want(id: string, extra: Partial = {}): Want { - return { - id, - release_group_mbid: `rg-${id}`, - title: 'The Ballad of Darren', - artist_mbid: 'blur', - artist_name: 'Blur', - artist_id: 'art-1', - primary_type: 'Album', - secondary_types: [], - year: '2023', - reason: 'follow', - wanted_at: ago(2 * DAY), - held_at: null, - image_url: '', - ...extra - }; -} - -function page( - items: Want[], - library: LibraryListing = { listed_at: ago(DAY), unlisted: 0 }, - artist?: WantsPage['artist'] -): WantsPage { - return { - artist, - items, - total: items.length, - limit: 50, - offset: 0, - counts: { artists: 2, wanted: 2, missing: 1, held: 4, upgrades: 0, following: 1, activity: 1, attention: 0, blocked: 0, unmatched: 0 }, - library - }; -} - -function grab(extra: Partial = {}): WantGrab { - return { - id: 'g1', - name: 'Blur - Blur (1997) [FLAC]', - grabbed_at: ago(60_000), - origin: 'schedule', - quality: 'lossless', - live: true, - end_reason: '', - progress: 0, - import_state: '', - import_reason: '', - end_detail: '', - imported_at: null, - imported_files: 0, - ...extra - }; -} - -afterEach(() => vi.clearAllMocks()); - -function setup( - items: Want[] = [want('w1'), want('w2', { reason: 'request', requested_by: 'sam', title: 'Parklife' })], - state: WantState = 'wanted', - library?: LibraryListing, - tracks: WantTracks = { - source: 'musicbrainz', - edition: '2023 · CD · GB', - tracks: [ - { disc: 1, number: 1, title: 'The Ballad', length_ms: 214000, missing: false }, - { disc: 1, number: 2, title: 'St. Charles Square', length_ms: 3_725_000, missing: false } - ] - } -) { - vi.mocked(createWantsQuery).mockReturnValue( - mockInfiniteQuery({ pages: [page(items, library)] }) as unknown as ReturnType - ); - vi.mocked(createCandidatesQuery).mockReturnValue( - mockQuery({ data: [] }) as unknown as ReturnType - ); - vi.mocked(createWantTracksQuery).mockReturnValue( - mockQuery({ data: tracks }) as unknown as ReturnType - ); - return render(WantList, { list: state }); -} - -describe('WantList', () => { - test('asks for its own state', () => { - setup([], 'upgrade'); - expect(createWantsQuery).toHaveBeenCalledWith('upgrade', ''); - expect(screen.getByText(/no album is wanted for a better copy/i)).toBeTruthy(); - }); - - test('a want says why it is wanted', () => { - setup(); - const why = screen.getAllByTestId('want-why').map((e) => e.textContent ?? ''); - expect(why[0]).toMatch(/new from a followed artist/i); - expect(why[1]).toMatch(/requested by sam/i); - }); - - test('remove takes a want off the list', async () => { - setup(); - await fireEvent.click(screen.getByRole('button', { name: /stop wanting parklife/i })); - await waitFor(() => expect(removeWant).toHaveBeenCalledWith('w2')); - }); - - test('a held album can be taken off the list, and is not searched for', async () => { - setup([want('w1', { held_at: ago(DAY), album_id: 'al-1', reason: 'library' })], 'held'); - expect(screen.queryByRole('button', { name: /stop wanting|search for/i })).toBeNull(); - expect(screen.getByRole('link', { name: /the ballad of darren/i }).getAttribute('href')).toBe('/albums/al-1'); - expect(screen.getByTestId('want-why').textContent).toMatch(/in your library when the list began/i); - await fireEvent.click(screen.getByRole('button', { name: /take the ballad of darren off the list/i })); - await waitFor(() => expect(removeWant).toHaveBeenCalledWith('w1')); - }); - - test('an empty list explains what lands there', () => { - setup([]); - expect(screen.getByText(/nothing is wanted/i)).toBeTruthy(); - }); - - test('each open want says what its last search found', () => { - setup([ - want('w1'), - want('w2', { - title: 'Parklife', - search: { searched_at: ago(3_600_000), outcome: 'nothing', considered: 4, best_release: 'x', best_verdict: 'rejected', error: '' } - }), - want('w3', { title: 'Blur', grab: grab() }), - want('w4', { title: '13', grab: grab({ import_state: 'downloading', progress: 0.42 }) }) - ]); - const lines = screen.getAllByTestId('want-search').map((e) => e.textContent ?? ''); - expect(lines[0]).toMatch(/not searched yet/i); - expect(lines[1]).toMatch(/4 found, none of them this album/i); - expect(lines[2]).toMatch(/downloading blur - blur \(1997\) \[flac\], taken by the schedule/i); - expect(lines[3]).toMatch(/downloading 42%/i); - }); - - test('a download waiting on a person says why and points to Activity', () => { - setup([ - want('w1', { grab: grab({ import_state: 'review', import_reason: 'Only the lengths agree. A person decides.' }) }) - ]); - const line = screen.getByTestId('want-search'); - expect(line.textContent).toMatch(/needs you: only the lengths agree/i); - expect(screen.getByRole('link', { name: /decide on activity/i }).getAttribute('href')).toBe('/collection/activity'); - // A live download can't be searched for again. - expect((screen.getByRole('button', { name: /search for the ballad of darren now/i }) as HTMLButtonElement).disabled).toBe(true); - }); - - test('a refused download is named beside the search that follows it', () => { - setup([ - want('w1', { - search: { searched_at: ago(3_600_000), outcome: 'nothing', considered: 0, best_release: '', best_verdict: '', error: '' }, - grab: grab({ live: false, end_reason: 'refused', import_state: 'refused', import_reason: 'Another album.' }) - }) - ]); - expect(screen.getByTestId('want-search').textContent).toMatch(/last download refused: another album/i); - }); - - test('a download given up on is named beside the search that follows it', () => { - setup([ - want('w1', { - search: { searched_at: ago(3_600_000), outcome: 'waiting', considered: 4, best_release: '', best_verdict: '', error: '' }, - grab: grab({ live: false, end_reason: 'stalled', import_state: 'downloading', end_detail: 'Nobody was sharing it.' }) - }) - ]); - expect(screen.getByTestId('want-search').textContent).toMatch(/last download given up: nobody was sharing it/i); - }); - - test('a held album says how it arrived', () => { - setup( - [ - want('w1', { - held_at: ago(DAY), - album_id: 'al-1', - grab: grab({ live: false, end_reason: 'imported', import_state: 'imported', imported_at: ago(DAY), imported_files: 11 }) - }) - ], - 'held' - ); - expect(screen.getByTestId('want-arrived').textContent).toMatch(/imported 11 tracks .* from blur - blur/i); - }); - - test('Search runs one now and says what came of it', async () => { - setup(); - await fireEvent.click(screen.getByRole('button', { name: /search for parklife now/i })); - await waitFor(() => expect(searchWant).toHaveBeenCalledWith('w2')); - await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Nothing found for Parklife.', 'info')); - }); - - test('Releases opens what the last search found', async () => { - setup(); - expect(screen.queryByTestId('want-candidates')).toBeNull(); - const toggle = screen.getByRole('button', { name: /releases found for parklife/i }); - await fireEvent.click(toggle); - expect(toggle.getAttribute('aria-expanded')).toBe('true'); - expect(screen.getByTestId('want-candidates')).toBeTruthy(); - expect(createCandidatesQuery).toHaveBeenCalledWith('w2'); - }); - - test('albums sit under their artist, as in the library', () => { - setup([ - want('w1', { artist_mbid: 'blur', artist_name: 'Blur', artist_id: 'art-1', title: 'Parklife' }), - want('w2', { artist_mbid: 'blur', artist_name: 'Blur', artist_id: 'art-1', title: '13' }), - want('w3', { artist_mbid: 'camel', artist_name: 'Camel', artist_id: undefined, title: 'Moonmadness' }) - ]); - const sections = screen.getAllByTestId('want-artist'); - expect(sections.map((s) => s.getAttribute('aria-label'))).toEqual(['Blur', 'Camel']); - expect(sections[0].querySelectorAll('[data-testid="want-row"]').length).toBe(2); - expect(sections[0].textContent).toMatch(/2 albums/); - expect(sections[1].textContent).toMatch(/1 album/); - // Each artist opens on their page in the catalogue. - expect(screen.getByRole('link', { name: 'Blur' }).getAttribute('href')).toBe('/collection/artist/blur'); - expect(screen.getByRole('link', { name: 'Camel' }).getAttribute('href')).toBe('/collection/artist/camel'); - }); - - test('Tracks shows the album\'s tracks, with the edition they come from', async () => { - setup(); - expect(screen.queryByTestId('want-tracks')).toBeNull(); - const toggle = screen.getByRole('button', { name: /tracks of parklife/i }); - await fireEvent.click(toggle); - expect(toggle.getAttribute('aria-expanded')).toBe('true'); - expect(createWantTracksQuery).toHaveBeenCalledWith('w2'); - const panel = screen.getByTestId('want-tracks'); - expect(panel.textContent).toMatch(/MusicBrainz's standard edition\s+·\s+2023 · CD · GB/); - const rows = screen.getAllByTestId('want-track').map((e) => e.textContent?.replace(/\s+/g, ' ').trim()); - expect(rows).toEqual(['1 The Ballad 3:34', '2 St. Charles Square 1:02:05']); - }); - - test('a held album\'s tracks are its own, a lost file marked', async () => { - setup([want('w1', { held_at: ago(DAY), album_id: 'al-1' })], 'held', undefined, { - source: 'library', - tracks: [ - { disc: 1, number: 1, title: 'The Ballad', length_ms: 214000, missing: true }, - { disc: 2, number: 1, title: 'Bonus', length_ms: 0, missing: false } - ] - }); - await fireEvent.click(screen.getByRole('button', { name: /tracks of the ballad of darren/i })); - const panel = screen.getByTestId('want-tracks'); - expect(panel.textContent).not.toMatch(/MusicBrainz/); - const rows = screen.getAllByTestId('want-track').map((e) => e.textContent?.replace(/\s+/g, ' ').trim()); - expect(rows).toEqual(['1-1 The Ballad file missing 3:34', '2-1 Bonus']); - }); - - test('the filter asks the server for the artists and albums it names', async () => { - setup(); - await fireEvent.input(screen.getByRole('searchbox', { name: /filter artists and albums/i }), { - target: { value: ' park ' } - }); - await waitFor(() => expect(createWantsQuery).toHaveBeenLastCalledWith('wanted', 'park')); - }); - - test("an artist's page lists every album of theirs under a header", () => { - vi.mocked(createWantsQuery).mockReturnValue( - mockInfiniteQuery({ - pages: [ - page([want('w1', { held_at: ago(DAY), album_id: 'al-1', title: 'Parklife' }), want('w2')], undefined, { - artist_mbid: 'blur', - artist_name: 'Blur', - sort_name: 'Blur', - artist_id: 'art-1', - image_url: '/art/blur', - albums: 2, - held: 1, - wanted: 1, - missing: 0, - downloading: 0, - following: true - }) - ] - }) as unknown as ReturnType - ); - vi.mocked(createCandidatesQuery).mockReturnValue( - mockQuery({ data: [] }) as unknown as ReturnType - ); - render(WantList, { artist: 'blur' }); - expect(createWantsQuery).toHaveBeenCalledWith('all', '', 'blur'); - const head = screen.getByTestId('catalogue-artist-head'); - expect(head.textContent).toMatch(/Blur/); - expect(screen.getByTestId('catalogue-artist-counts').textContent).toMatch(/1 of 2 albums held\s+·\s+1 wanted/); - expect(screen.getByRole('link', { name: /open in the library/i }).getAttribute('href')).toBe('/artists/art-1'); - expect(screen.getByRole('link', { name: /catalogue/i }).getAttribute('href')).toBe('/collection'); - // One artist: no filter, no artist headings, both albums. - expect(screen.queryByRole('searchbox')).toBeNull(); - expect(screen.getAllByTestId('want-row')).toHaveLength(2); - expect(screen.queryByRole('link', { name: 'Blur' })).toBeNull(); - }); - - test('an upgrade is a held album searched for a better copy', async () => { - setup( - [ - want('u1', { held_at: ago(DAY), reason: 'library', upgrade: 'quality', held_quality: 'MP3, about 192 kbps' }), - want('u2', { held_at: ago(DAY), reason: 'library', upgrade: 'rip', title: 'Humanz' }) - ], - 'upgrade' - ); - expect(createWantsQuery).toHaveBeenCalledWith('upgrade', ''); - const lines = screen.getAllByTestId('want-upgrade').map((e) => e.textContent ?? ''); - expect(lines[0]).toMatch(/you have mp3, about 192 kbps; looking for better/i); - expect(lines[1]).toMatch(/video rip; looking for a clean copy/i); - expect(screen.getAllByTestId('want-search')[0].textContent).toMatch(/not searched yet/i); - await fireEvent.click(screen.getByRole('button', { name: /search for humanz now/i })); - await waitFor(() => expect(searchWant).toHaveBeenCalledWith('u2')); - }); - - test('a held album not wanted for a better copy has no search', () => { - setup([want('h1', { held_at: ago(DAY), reason: 'library' })], 'held'); - expect(screen.queryByTestId('want-upgrade')).toBeNull(); - expect(screen.queryByRole('button', { name: /search for/i })).toBeNull(); - }); - - test('with no upgrades it says what would land here', () => { - setup([], 'upgrade'); - expect(screen.getByText(/no album is wanted for a better copy/i)).toBeTruthy(); - }); -}); diff --git a/web/src/lib/components/wanted/WantTracks.svelte b/web/src/lib/components/wanted/WantTracks.svelte deleted file mode 100644 index f57595cb..00000000 --- a/web/src/lib/components/wanted/WantTracks.svelte +++ /dev/null @@ -1,52 +0,0 @@ - - -
    - {#if tracks.isPending} -

    Reading the tracks…

    - {:else if tracks.isError} -

    - {away ? "MusicBrainz can't be reached, so the tracks can't be shown." : "Couldn't load the tracks."} -

    - {:else if tracks.data.source === 'none' || list.length === 0} -

    MusicBrainz lists no edition of this album, so there are no tracks to show.

    - {:else} - {#if tracks.data.source === 'musicbrainz'} -

    - MusicBrainz's standard edition{tracks.data.edition ? ` · ${tracks.data.edition}` : ''} -

    - {/if} -
      - {#each list as t, i (i)} -
    1. - {position(t)} - - {t.title} - - {#if t.missing}file missing{/if} - {#if t.length_ms > 0} - {formatDuration(t.length_ms / 1000)} - {/if} -
    2. - {/each} -
    - {/if} -
    diff --git a/web/src/lib/example.test.ts b/web/src/lib/example.test.ts deleted file mode 100644 index 50cae2e6..00000000 --- a/web/src/lib/example.test.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -describe('scaffold smoke', () => { - it('runs vitest', () => { - expect(1 + 1).toBe(2); - }); -}); diff --git a/web/src/lib/media/duration.test.ts b/web/src/lib/media/duration.test.ts index 91427e32..aa4722f8 100644 --- a/web/src/lib/media/duration.test.ts +++ b/web/src/lib/media/duration.test.ts @@ -2,32 +2,19 @@ import { describe, expect, test } from 'vitest'; import { formatDuration } from './duration'; describe('formatDuration', () => { - test('under a minute renders 0:SS', () => { - expect(formatDuration(42)).toBe('0:42'); - expect(formatDuration(5)).toBe('0:05'); - }); - - test('under an hour renders M:SS', () => { - expect(formatDuration(242)).toBe('4:02'); - expect(formatDuration(600)).toBe('10:00'); - }); - - test('at or above an hour renders H:MM:SS', () => { - expect(formatDuration(3600)).toBe('1:00:00'); - expect(formatDuration(3723)).toBe('1:02:03'); - expect(formatDuration(36000)).toBe('10:00:00'); - }); - - test('zero renders 0:00', () => { - expect(formatDuration(0)).toBe('0:00'); - }); - - test('negative values clamp to 0:00', () => { - expect(formatDuration(-1)).toBe('0:00'); - expect(formatDuration(-100)).toBe('0:00'); - }); - - test('fractional seconds floor', () => { - expect(formatDuration(61.9)).toBe('1:01'); + test.each([ + [0, '0:00'], + [5, '0:05'], + [42, '0:42'], + [242, '4:02'], + [600, '10:00'], + [3600, '1:00:00'], + [3723, '1:02:03'], + [36000, '10:00:00'], + [61.9, '1:01'], // fractions floor + [-1, '0:00'], // negatives clamp + [-100, '0:00'] + ])('%s s → %s', (sec, want) => { + expect(formatDuration(sec)).toBe(want); }); }); diff --git a/web/src/lib/player/audioLoader.test.ts b/web/src/lib/player/audioLoader.test.ts deleted file mode 100644 index 7076ad82..00000000 --- a/web/src/lib/player/audioLoader.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import type { TrackRef } from '#lib/api/types.js'; -import { audioLoader, setAudioLoader, __resetAudioLoader } from './audioLoader'; - -const sampleTrack: TrackRef = { - id: 't1', - title: 'Sample', - album_id: 'a1', - album_title: 'Album', - artist_id: 'ar1', - artist_name: 'Artist', - duration_sec: 180, - stream_url: '/api/tracks/t1/stream' -}; - -afterEach(() => { - __resetAudioLoader(); -}); - -describe('audioLoader', () => { - test('default resolve returns the track stream_url', () => { - expect(audioLoader.resolve(sampleTrack)).toBe('/api/tracks/t1/stream'); - }); - - test('default prefetch is a no-op (does not throw)', () => { - expect(() => audioLoader.prefetch?.(sampleTrack)).not.toThrow(); - }); - - test('setAudioLoader swaps the resolver', () => { - setAudioLoader({ - resolve: (t) => `blob:cached-${t.id}` - }); - expect(audioLoader.resolve(sampleTrack)).toBe('blob:cached-t1'); - }); - - test('setAudioLoader swaps the prefetch hook', () => { - const spy = vi.fn(); - setAudioLoader({ - resolve: (t) => t.stream_url, - prefetch: spy - }); - audioLoader.prefetch?.(sampleTrack); - expect(spy).toHaveBeenCalledWith(sampleTrack); - }); - - test('__resetAudioLoader restores the default', () => { - setAudioLoader({ resolve: () => 'blob:swapped' }); - expect(audioLoader.resolve(sampleTrack)).toBe('blob:swapped'); - __resetAudioLoader(); - expect(audioLoader.resolve(sampleTrack)).toBe('/api/tracks/t1/stream'); - }); -}); diff --git a/web/src/lib/player/audioLoader.ts b/web/src/lib/player/audioLoader.ts deleted file mode 100644 index aaaf2739..00000000 --- a/web/src/lib/player/audioLoader.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Audio loader seam: returns the server-relative stream URL directly. A -// native shell can swap the loader to return blob URLs backed by its own -// cache, without touching the player UI. -// -// Two operations: -// - resolve(track) — returns the URL the
    - - -

    - The profile says which kinds of release following - {profileRow?.artist_name ?? 'this artist'} wants. Profiles are edited under Collection › Following. -

    - - - -
    - - -
    -
    - - -

    - Notes are shown to the requester. -

    - -
    - - -
    -
    diff --git a/web/src/routes/admin/requests/requests.test.ts b/web/src/routes/admin/requests/requests.test.ts deleted file mode 100644 index a748ce10..00000000 --- a/web/src/routes/admin/requests/requests.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; -import { mockQuery } from '../../../test-utils/query'; -import type { MusicRequest } from '#lib/api/types.js'; - -// Wrap useQueryClient so the page can call invalidateQueries() without a -// real QueryClient context. Everything else from svelte-query passes through. -vi.mock('#lib/api/admin.js', () => ({ - createAdminRequestsQuery: vi.fn(), - approveRequest: vi.fn(), - rejectRequest: vi.fn() -})); -vi.mock('#lib/api/wanted.js', () => ({ - createReleaseProfilesQuery: vi.fn() -})); - -import AdminRequestsPage from './+page.svelte'; -import { createAdminRequestsQuery, approveRequest, rejectRequest } from '#lib/api/admin.js'; -import { createReleaseProfilesQuery } from '#lib/api/wanted.js'; - -const baseRow: MusicRequest = { - id: 'r1', - user_id: 'u1234567-aaaa-bbbb-cccc-deadbeef0001', - status: 'pending', - kind: 'album', - artist_mbid: 'a-mbid', - album_mbid: 'al-mbid', - artist_name: 'Boards of Canada', - album_title: 'Geogaddi', - requested_at: '2026-04-29T10:00:00Z', - updated_at: '2026-04-29T10:00:00Z', - imported_album_count: 0, - imported_track_count: 0 -}; - -afterEach(() => vi.clearAllMocks()); - -function setup(rows: MusicRequest[] = [baseRow]) { - (createAdminRequestsQuery as ReturnType).mockReturnValue( - mockQuery({ data: rows }) - ); - (createReleaseProfilesQuery as ReturnType).mockReturnValue( - mockQuery({ - data: { - profiles: [ - { id: 'p-std', name: 'Standard', primary_types: ['Album'], secondary_types: [], is_default: true, follow_count: 0 }, - { id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 } - ], - primary_types: ['Album'], - secondary_types: ['Live'] - } - }) - ); - return render(AdminRequestsPage); -} - -describe('/admin/requests', () => { - test('Tab switch refetches with new status filter', async () => { - setup(); - await fireEvent.click(screen.getByRole('tab', { name: /approved/i })); - expect(createAdminRequestsQuery).toHaveBeenCalledWith('approved'); - }); - - test('Approve sends no profile', async () => { - setup(); - (approveRequest as ReturnType).mockResolvedValueOnce(baseRow); - await fireEvent.click(screen.getByRole('button', { name: /approve geogaddi/i })); - expect(approveRequest).toHaveBeenCalledWith('r1', undefined); - }); - - test('An album request has no profile choice', () => { - setup(); - expect(screen.queryByRole('button', { name: /on a profile/i })).toBeNull(); - }); - - test('An artist request is approved on the chosen profile', async () => { - setup([{ ...baseRow, kind: 'artist', album_mbid: undefined, album_title: undefined }]); - await fireEvent.click( - screen.getByRole('button', { name: /approve boards of canada on a profile/i }) - ); - const select = screen.getByLabelText(/release-type profile/i) as HTMLSelectElement; - expect(select.value).toBe('p-std'); - await fireEvent.change(select, { target: { value: 'p-live' } }); - (approveRequest as ReturnType).mockResolvedValueOnce(baseRow); - await fireEvent.click(screen.getByRole('button', { name: /approve and follow/i })); - expect(approveRequest).toHaveBeenCalledWith('r1', 'p-live'); - }); - - test('Reject opens notes textarea; confirm sends notes', async () => { - setup(); - await fireEvent.click(screen.getByRole('button', { name: /reject geogaddi/i })); - const textarea = screen.getByLabelText(/notes/i) as HTMLTextAreaElement; - await fireEvent.input(textarea, { target: { value: 'duplicate' } }); - (rejectRequest as ReturnType).mockResolvedValueOnce({ - ...baseRow, - status: 'rejected' - }); - await fireEvent.click( - screen.getByRole('button', { name: /confirm reject/i }) - ); - expect(rejectRequest).toHaveBeenCalledWith('r1', 'duplicate'); - }); - - test('An approve error shows a toast', async () => { - setup(); - (approveRequest as ReturnType).mockRejectedValueOnce({ - code: 'request_not_pending', - message: 'not pending', - status: 409 - }); - await fireEvent.click(screen.getByRole('button', { name: /approve geogaddi/i })); - await waitFor(() => - expect(screen.getByText(/no longer pending/i)).toBeInTheDocument() - ); - }); - - test('Track-kind row renders disclosure copy about adding the album', () => { - setup([ - { - ...baseRow, - kind: 'track', - track_title: 'Roygbiv', - album_title: 'Geogaddi' - } - ]); - expect(screen.getByText(/wants the album/i)).toBeInTheDocument(); - }); - - test('A row names who asked for it', () => { - setup([{ ...baseRow, username: 'alice' }]); - expect(screen.getByText(/^by alice · /)).toBeInTheDocument(); - expect(screen.queryByText(/u1234567/)).not.toBeInTheDocument(); - }); - - test('A row without a name falls back to the user id', () => { - setup(); - expect(screen.getByText(/^by user u1234567 · /)).toBeInTheDocument(); - }); -}); diff --git a/web/src/routes/admin/tuning/+page.svelte b/web/src/routes/admin/tuning/+page.svelte index 64c6cc8c..a5368258 100644 --- a/web/src/routes/admin/tuning/+page.svelte +++ b/web/src/routes/admin/tuning/+page.svelte @@ -10,7 +10,6 @@ type TuningSnapshot, type WeightProfile, type TasteTuning, - type DiscoverTuning, type TrendsResponse, type TrendSeries, type TrendMarker @@ -47,11 +46,6 @@ { key: 'mood_scale', label: 'Mood weight', hint: 'How much the mood counts. 0 ignores it.' } ]; - const discoverFields: { key: keyof DiscoverTuning; label: string; hint: string }[] = [ - { key: 'tag_overlap_weight', label: 'Taste-tag weight', hint: 'Boost for a suggestion whose tags fit your taste. 0 ranks on likeness alone.' }, - { key: 'snooze_days', label: 'Snooze length (days)', hint: 'How long "not right now" hides a suggestion.' } - ]; - const profileScopes: { scope: WeightProfileScope; label: string; blurb: string }[] = [ { scope: 'radio', label: 'Radio', blurb: 'Listening that starts from a seed.' }, { scope: 'daily_mix', label: 'Daily mixes', blurb: 'For You, the discovery mixes and "You might like".' }, @@ -73,14 +67,12 @@ radio: {}, daily_mix: {}, songs_like: {}, - taste: {}, - discover: {} + taste: {} }; for (const p of profileScopes.map((s) => s.scope)) { for (const { key } of weightFields) f[p][key] = String(snap.profiles[p][key]); } for (const { key } of tasteFields) f.taste[key] = String(snap.taste[key]); - for (const { key } of discoverFields) f.discover[key] = String(snap.discover[key]); form = f; } @@ -104,12 +96,6 @@ if (scope === 'taste') { return snapshot.taste[key as keyof TasteTuning] !== snapshot.shipped.taste[key as keyof TasteTuning]; } - if (scope === 'discover') { - return ( - snapshot.discover[key as keyof DiscoverTuning] !== - snapshot.shipped.discover[key as keyof DiscoverTuning] - ); - } return ( snapshot.profiles[scope][key as keyof WeightProfile] !== snapshot.shipped.profiles[scope][key as keyof WeightProfile] @@ -119,7 +105,6 @@ function currentValue(scope: TuningScope, key: string): number { if (!snapshot) return 0; if (scope === 'taste') return snapshot.taste[key as keyof TasteTuning]; - if (scope === 'discover') return snapshot.discover[key as keyof DiscoverTuning]; return snapshot.profiles[scope][key as keyof WeightProfile]; } @@ -277,7 +262,6 @@ id="{scope}-{f.key}" type="number" step={step(f.key)} - min={scope === 'discover' ? '0' : undefined} bind:value={form[scope][f.key]} class="w-24 rounded-md border border-border bg-background px-2 py-1.5 text-right text-sm tabular-nums" /> @@ -327,14 +311,6 @@ (k) => (k === 'half_life_days' ? '1' : '0.05'), (k) => snap.shipped.taste[k as keyof TasteTuning] )} - {@render knobs( - 'discover', - 'Discover requests', - "How Discover ranks artists you don't have.", - discoverFields, - (k) => (k === 'snooze_days' ? '1' : '0.1'), - (k) => snap.shipped.discover[k as keyof DiscoverTuning] - )}
    {/if} diff --git a/web/src/routes/admin/tuning/tuning.test.ts b/web/src/routes/admin/tuning/tuning.test.ts index f4ca8908..a637b284 100644 --- a/web/src/routes/admin/tuning/tuning.test.ts +++ b/web/src/routes/admin/tuning/tuning.test.ts @@ -43,12 +43,6 @@ const taste = (over: Partial> = {}) => ({ ...over }); -const discover = (over: Partial> = {}) => ({ - tag_overlap_weight: 1, - snooze_days: 90, - ...over -}); - // NOTE the `as TuningSnapshot` cast below: it silences the type error when the // server snapshot grows a field, so a missing key here surfaces as every test // on this page throwing inside fillForm rather than as a compile failure. Add @@ -61,15 +55,13 @@ function snapshot(over: Partial = {}): TuningSnapshot { songs_like: weights({ similarity_weight: 4, like_boost: 0.5, taste_weight: 0.25 }) }, taste: taste(), - discover: discover(), shipped: { profiles: { radio: weights({ taste_weight: 1 }), daily_mix: weights(), songs_like: weights({ similarity_weight: 4, like_boost: 0.5, taste_weight: 0.25 }) }, - taste: taste(), - discover: discover() + taste: taste() }, ...over } as TuningSnapshot; @@ -165,7 +157,7 @@ describe('Admin tuning page', () => { ).toBeInTheDocument(); }); - test('renders weekly trend rows with sparklines and knob-turn markers (#1251)', async () => { + test('renders weekly trend rows with sparklines and knob-turn markers', async () => { (getTuning as ReturnType).mockResolvedValue(snapshot()); (getTrends as ReturnType).mockResolvedValue({ weeks: 12, @@ -262,62 +254,4 @@ describe('Admin tuning page', () => { expect(screen.getByText(/trends appear once listening accumulates/i)).toBeInTheDocument() ); }); - // --- Discover scope --- - - test('renders the Discover card with its two knobs', async () => { - (getTuning as ReturnType).mockResolvedValue(snapshot()); - render(TuningPage); - await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument()); - expect(screen.getByLabelText(/taste-tag weight/i)).toBeInTheDocument(); - expect(screen.getByLabelText(/snooze length/i)).toBeInTheDocument(); - }); - - test('saving Discover patches only the changed field under the discover scope', async () => { - (getTuning as ReturnType).mockResolvedValue(snapshot()); - (patchTuning as ReturnType).mockResolvedValue(snapshot()); - render(TuningPage); - await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument()); - await fireEvent.input(screen.getByLabelText(/taste-tag weight/i), { - target: { value: '2.5' } - }); - await fireEvent.click(screen.getByRole('button', { name: /save discover/i })); - await waitFor(() => - expect(patchTuning).toHaveBeenCalledWith('discover', { tag_overlap_weight: 2.5 }) - ); - }); - - // 0 is an admin's off switch for the whole tag term, so the form must be - // able to send it — a falsy-value bug here would silently make the feature - // impossible to disable. - test('a Discover weight of 0 is sent, not dropped as falsy', async () => { - (getTuning as ReturnType).mockResolvedValue(snapshot()); - (patchTuning as ReturnType).mockResolvedValue(snapshot()); - render(TuningPage); - await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument()); - await fireEvent.input(screen.getByLabelText(/taste-tag weight/i), { target: { value: '0' } }); - await fireEvent.click(screen.getByRole('button', { name: /save discover/i })); - await waitFor(() => - expect(patchTuning).toHaveBeenCalledWith('discover', { tag_overlap_weight: 0 }) - ); - }); - - test('reset targets the discover scope', async () => { - (getTuning as ReturnType).mockResolvedValue(snapshot()); - (resetTuning as ReturnType).mockResolvedValue(snapshot()); - render(TuningPage); - await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument()); - await fireEvent.click( - screen.getByRole('button', { name: /reset discover requests to defaults/i }) - ); - await waitFor(() => expect(resetTuning).toHaveBeenCalledWith('discover')); - }); - - test('a deviating Discover knob is dotted', async () => { - const snap = snapshot(); - snap.discover = discover({ tag_overlap_weight: 3 }); - (getTuning as ReturnType).mockResolvedValue(snap); - render(TuningPage); - await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument()); - expect(screen.getByTitle(/deviates from the shipped default \(1\)/i)).toBeInTheDocument(); - }); }); diff --git a/web/src/routes/admin/users/+page.svelte b/web/src/routes/admin/users/+page.svelte index 59f0b213..019271e2 100644 --- a/web/src/routes/admin/users/+page.svelte +++ b/web/src/routes/admin/users/+page.svelte @@ -1,4 +1,6 @@ -
    -
    -

    Collection

    + + {#snippet intro()}

    - Every artist and album in your collection: what the library holds, and what Minstrel is - getting for it, from user requests, new releases of the artists it follows, and albums whose - files went missing. It searches your indexers on a schedule, checks each download against - MusicBrainz, and files what's right into the library. Searching and quality are set under - Acquisition. + What in the library needs looking at: tracks people reported, songs held twice, files from + doubtful sources, and the tracks waiting for a good file.

    - {#if verdict} -

    - {verdict} - {#if counts?.attention} - See Activity - {:else if counts?.unmatched} - See Unmatched - {/if} -

    + {#if summary} + {#if waiting.length > 0} +

    + To look at: + {#each waiting as d, i (d.key)}{queueLabel(d, countOf(summary, d.key))}{i < waiting.length - 1 ? ', ' : '.'} + {/each} +

    + {:else} +

    Nothing needs you.

    + {/if} {/if} - {#if health.length > 0} -

    - To look at: - {#each health as d, i (d.key)}{queueLabel(d, countOf(summary, d.key))}{i < health.length - 1 ? ', ' : '.'} - {/each} -

    - {/if} -
    - -
    -
    -
    - -
    -
    -
    - {@render children?.()} -
    -
    -
    + {/snippet} + {#snippet rail()} + + {/snippet} + {@render children?.()} + diff --git a/web/src/routes/collection/+layout.ts b/web/src/routes/collection/+layout.ts index 067439a6..aa1773e8 100644 --- a/web/src/routes/collection/+layout.ts +++ b/web/src/routes/collection/+layout.ts @@ -2,10 +2,12 @@ import { redirect } from '@sveltejs/kit'; import { user } from '#lib/auth/store.svelte.js'; import type { LayoutLoad } from './$types'; -// Hard route gate: the Wanted view is an admin's. Runs before the -// layout renders; auth is bootstrapped by the root +layout.ts, so user.value is -// either a settled User object or null. -export const load: LayoutLoad = () => { +// Hard route gate: the Collection is an admin's. SvelteKit runs layout loads +// side by side, so this waits for the root +layout.ts to finish signing the +// user in; otherwise opening a Collection page directly (a refresh, a +// bookmark) would find no user yet and bounce an admin to Home. +export const load: LayoutLoad = async ({ parent }) => { + await parent(); if (!user.value || !user.value.is_admin) { throw redirect(302, '/'); } diff --git a/web/src/routes/collection/+page.svelte b/web/src/routes/collection/+page.svelte index 5a07e2e2..8ef5b30a 100644 --- a/web/src/routes/collection/+page.svelte +++ b/web/src/routes/collection/+page.svelte @@ -1,8 +1,47 @@ {pageTitle('Collection')} - +
    + {#if summaryQ.isPending} +

    Reading the queues…

    + {:else if summaryQ.isError} +

    + Couldn't read the queues. + +

    + {:else} + {#if waiting.length > 0} +
      + {#each waiting as d (d.key)} + {@const q = summary?.[d.key]} + + {/each} +
    + {/if} + {#if clear.length > 0} +

    + No {clear.map((d) => d.none).join(', ')}. +

    + {/if} + {/if} +
    diff --git a/web/src/routes/collection/activity/+page.svelte b/web/src/routes/collection/activity/+page.svelte deleted file mode 100644 index d36f1008..00000000 --- a/web/src/routes/collection/activity/+page.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - -{pageTitle('Collection · Activity')} - - diff --git a/web/src/routes/collection/artist/[mbid]/+page.svelte b/web/src/routes/collection/artist/[mbid]/+page.svelte deleted file mode 100644 index 53b4ada0..00000000 --- a/web/src/routes/collection/artist/[mbid]/+page.svelte +++ /dev/null @@ -1,15 +0,0 @@ - - -{pageTitle('Collection · Artist')} - -{#key mbid} - -{/key} diff --git a/web/src/routes/collection/blocked/+page.svelte b/web/src/routes/collection/blocked/+page.svelte deleted file mode 100644 index 07c7b02d..00000000 --- a/web/src/routes/collection/blocked/+page.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - -{pageTitle('Collection · Blocked')} - - diff --git a/web/src/routes/collection/collection.test.ts b/web/src/routes/collection/collection.test.ts index 19132d70..aacfc504 100644 --- a/web/src/routes/collection/collection.test.ts +++ b/web/src/routes/collection/collection.test.ts @@ -1,97 +1,57 @@ import { afterEach, describe, expect, test, vi } from 'vitest'; import { render, screen } from '@testing-library/svelte'; import { createRawSnippet } from 'svelte'; -import { mockInfiniteQuery } from '../../test-utils/query'; import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { mockQuery } from '../../test-utils/query'; -import type { AdminSummary, WantArtistsPage, WantCounts } from '#lib/api/types.js'; +import type { AdminSummary } from '#lib/api/types.js'; const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/collection') })); vi.mock('$app/state', () => pageUrlModule(state)); -vi.mock('#lib/api/wanted.js', () => ({ createWantArtistsQuery: vi.fn() })); vi.mock('#lib/api/admin.js', () => ({ createAdminSummaryQuery: vi.fn() })); -import WantedLayout from './+layout.svelte'; -import { createWantArtistsQuery } from '#lib/api/wanted.js'; +import CollectionLayout from './+layout.svelte'; +import CollectionPage from './+page.svelte'; import { createAdminSummaryQuery } from '#lib/api/admin.js'; -const counts: WantCounts = { artists: 7, wanted: 5, missing: 1, held: 9, upgrades: 6, following: 2, activity: 3, attention: 0, blocked: 4, unmatched: 3 }; const children = createRawSnippet(() => ({ render: () => `

    body

    ` })); afterEach(() => vi.clearAllMocks()); const none = { count: 0, since: null }; -const clear: AdminSummary = { requests: none, reports: none, duplicates: none, suspect: none, missing: none }; +const clear: AdminSummary = { reports: none, duplicates: none, suspect: none, missing: none }; -function setup(c: WantCounts = counts, path = '/collection', summary: AdminSummary = clear) { - state.pageUrl = new URL(`http://localhost${path}`); +function mockSummary(summary: AdminSummary) { vi.mocked(createAdminSummaryQuery).mockReturnValue( mockQuery({ data: summary }) as unknown as ReturnType ); - const page: WantArtistsPage = { - items: [], - total: 0, - limit: 50, - offset: 0, - counts: c, - library: { listed_at: null, unlisted: 0 } - }; - vi.mocked(createWantArtistsQuery).mockReturnValue( - mockInfiniteQuery({ pages: [page] }) as unknown as ReturnType - ); +} + +function setup(path = '/collection', summary: AdminSummary = clear) { + state.pageUrl = new URL(`http://localhost${path}`); + mockSummary(summary); // eslint-disable-next-line @typescript-eslint/no-explicit-any - return render(WantedLayout, { children } as any); + return render(CollectionLayout, { children } as any); } describe('/collection layout', () => { - test('the sections down the left carry their counts, the current one marked', () => { - setup(counts, '/collection/activity'); + test('the sections down the left are the overview and the health queues, the current one marked', () => { + setup('/collection/missing'); const nav = screen.getByRole('navigation', { name: /collection sections/i }); const links = Array.from(nav.querySelectorAll('a')).map((a) => [a.getAttribute('href'), a.textContent?.replace(/\s+/g, ' ').trim()]); expect(links).toEqual([ - ['/collection', 'Catalogue 7'], - ['/collection/wanted', 'Wanted 5'], - ['/collection/upgrades', 'Upgrades 6'], - ['/collection/activity', 'Activity 3'], - ['/collection/following', 'Following 2'], - ['/collection/blocked', 'Blocked 4'], - ['/collection/unmatched', 'Unmatched 3'], + ['/collection', 'Overview'], ['/collection/reports', 'Reports'], ['/collection/duplicates', 'Duplicates'], ['/collection/suspect-sources', 'Suspect sources'], - ['/collection/missing', 'Missing files'] + ['/collection/missing', 'Needs a file'] ]); - expect(screen.getByRole('link', { name: /activity/i })).toHaveAttribute('aria-current', 'page'); - expect(screen.getByRole('link', { name: /^catalogue/i })).not.toHaveAttribute('aria-current'); + expect(screen.getByRole('link', { name: /needs a file/i })).toHaveAttribute('aria-current', 'page'); + expect(screen.getByRole('link', { name: /^overview/i })).not.toHaveAttribute('aria-current'); expect(screen.getByTestId('tab-body')).toBeTruthy(); }); - test('when nothing needs a person the verdict says so', () => { - setup({ ...counts, unmatched: 0 }); - expect(screen.getByTestId('collection-verdict').textContent).toMatch(/5 albums wanted, 3 downloading\. Nothing needs you\./); - expect(screen.queryByTestId('tab-attention')).toBeNull(); - }); - - test('downloads waiting on a person lead the page and mark Activity', () => { - setup({ ...counts, attention: 2 }); - const verdict = screen.getByTestId('collection-verdict'); - expect(verdict.textContent).toMatch(/2 downloads need you/); - expect(screen.getByRole('link', { name: /see activity/i }).getAttribute('href')).toBe('/collection/activity'); - expect(screen.getByTestId('tab-attention').textContent).toBe('2'); - }); - - test('library albums waiting to be matched need a person, and link to Unmatched', () => { - setup(); - expect(screen.getByTestId('collection-verdict').textContent).toMatch( - /5 albums wanted, 3 downloading\. 3 albums in your library need matching\./ - ); - expect(screen.getByRole('link', { name: /see unmatched/i }).getAttribute('href')).toBe('/collection/unmatched'); - }); - - // The library's health queues moved here from Admin: their counts - // come from the admin summary, accented, and a line names the ones waiting. - test('the library health queues carry what waits on you, and a line links to each', () => { - setup(counts, '/collection', { + test('the health queues carry what waits on you, and a line links to each', () => { + setup('/collection', { ...clear, reports: { count: 2, since: null }, duplicates: { count: 5, since: null }, @@ -102,7 +62,7 @@ describe('/collection layout', () => { expect(dup.textContent?.replace(/\s+/g, ' ').trim()).toBe('Duplicates 5'); const health = screen.getByTestId('collection-health'); expect(health.textContent?.replace(/\s+/g, ' ').trim()).toBe( - 'To look at: 2 broken tracks reported, 5 sets of duplicates to review, 9 missing files.' + 'To look at: 2 broken tracks reported, 5 sets of duplicates to review, 9 tracks need a file.' ); expect(Array.from(health.querySelectorAll('a')).map((a) => a.getAttribute('href'))).toEqual([ '/collection/reports', @@ -111,13 +71,20 @@ describe('/collection layout', () => { ]); }); - test('with nothing waiting there is no health line', () => { + test('with nothing waiting the line says nothing needs you', () => { setup(); - expect(screen.queryByTestId('collection-health')).toBeNull(); + expect(screen.getByTestId('collection-health').textContent?.trim()).toBe('Nothing needs you.'); }); +}); - test("an artist's page sits under Catalogue", () => { - setup(counts, '/collection/artist/blur'); - expect(screen.getByRole('link', { name: /^catalogue/i })).toHaveAttribute('aria-current', 'page'); +describe('/collection overview', () => { + test('lists each queue with something in it, then the empty ones on one line', () => { + mockSummary({ ...clear, missing: { count: 3, since: new Date().toISOString() } }); + render(CollectionPage); + const rows = screen.getAllByTestId('collection-queue'); + expect(rows).toHaveLength(1); + expect(rows[0].textContent).toMatch(/3 tracks need a file/); + expect(rows[0].querySelector('a')?.getAttribute('href')).toBe('/collection/missing'); + expect(screen.getByTestId('collection-clear').textContent?.trim()).toBe('No reports, duplicates, suspect sources.'); }); }); diff --git a/web/src/routes/collection/duplicates/+page.svelte b/web/src/routes/collection/duplicates/+page.svelte index 6a3484cb..695084a4 100644 --- a/web/src/routes/collection/duplicates/+page.svelte +++ b/web/src/routes/collection/duplicates/+page.svelte @@ -10,7 +10,7 @@ runDuplicateSweep, dismissDuplicateGroup, mergeDuplicateGroup, - refetchDuplicateGroup + removeWrongSlotFiles } from '#lib/api/admin.js'; import { errMessage } from '#lib/api/errors.js'; import { pushToast } from '#lib/stores/toast.svelte.js'; @@ -27,12 +27,12 @@ import ListContinuation from '#lib/components/ListContinuation.svelte'; import TabStrip from '#lib/components/TabStrip.svelte'; - // Tracks the duplicate sweep believes hold one recording. The - // resolver settles what is safe on its own: a song held twice on - // one album, and a video rip with a clean copy elsewhere. What is left comes - // in two tabs: groups that need an admin, and the same song on different - // releases, which is kept on purpose. A third tab lists what the resolver - // did. + // Tracks the duplicate sweep believes hold one recording. The resolver + // never removes a file on its own, since other programs file music into the + // library too: it links copies of one song so they count once, and dismisses + // distinct versions. Groups come in two tabs: those that need an admin, and + // the same song on different releases, which is kept on purpose. A third tab + // lists what the resolver settled. // // Dismissing a group says "these are not duplicates", and the sweep will not // propose that set again. On the cross-release tab it reads "Not the same @@ -42,11 +42,11 @@ // // Except for one recording filling several of an album's slots (class // mismatch), where a merge is the wrong answer: it keeps one copy's - // title whether or not it is the audio's, and fetches nothing. There an - // admin says which song the recording is, or that they can't tell, and the - // group settles as the resolver would have: copies in other songs' slots are - // removed, the release they came from is set aside, and the album is fetched - // again. + // title whether or not it is the audio's. There an admin says which song the + // recording is (the group's note says when MusicBrainz or AcoustID could + // tell), or that they can't tell: copies in other songs' slots are removed, + // and those tracks wait in Needs a file until a good copy is in the library + // folder. type Tab = DuplicatesView | 'resolved'; const fromUrl = page.url.searchParams.get('view'); @@ -65,8 +65,8 @@ // Per wrong-slot group: the copy whose title the recording is, absent when // an admin can't tell, and the same two-click confirm. let slotPick = $state>({}); - let confirmingRefetch = $state(null); - let refetching = $state(null); + let confirmingRemoveSlots = $state(null); + let removingSlots = $state(null); const queryStore = $derived(createDuplicatesQuery(groupView)); const query = $derived($queryStore); @@ -156,32 +156,28 @@ // The copies that go: every one when an admin can't tell, else those // under another title. A copy under the picked title is the song held twice, // and the next sweep merges it. - function refetchRemoves(g: AdminDuplicateGroup): AdminDuplicateMember[] { + function slotRemovals(g: AdminDuplicateGroup): AdminDuplicateMember[] { const picked = pickedOf(g); if (!picked) return g.members; return g.members.filter((m) => songKey(m.title) !== songKey(picked.title)); } - async function onRefetch(group: AdminDuplicateGroup) { - if (confirmingRefetch !== group.id) { - confirmingRefetch = group.id; + async function onRemoveSlots(group: AdminDuplicateGroup) { + if (confirmingRemoveSlots !== group.id) { + confirmingRemoveSlots = group.id; return; } - confirmingRefetch = null; - refetching = group.id; + confirmingRemoveSlots = null; + removingSlots = group.id; try { - const result = await refetchDuplicateGroup(group.id, { keep_track_id: slotPick[group.id] ?? '' }); + const result = await removeWrongSlotFiles(group.id, { keep_track_id: slotPick[group.id] ?? '' }); const removed = `Removed ${plural(result.removed_paths.length, 'file', 'files')}`; - pushToast( - result.blocked.length > 0 - ? `${removed} and set aside the release they came from. The album will be fetched again.` - : `${removed}. The album will be fetched again, but Minstrel didn't download these files, so the same ones may come back.` - ); + pushToast(`${removed}. Their tracks wait in Needs a file until a good copy is in the library.`); query.refetch(); } catch (e: unknown) { pushToast(errMessage(e), 'error'); } finally { - refetching = null; + removingSlots = null; } } @@ -283,8 +279,8 @@

    Tracks that hold the same recording more than once. Most settle on their own: a song held twice on one album is merged, copies on different releases count as one song, two versions of a song - are left alone, and a file filling another song's track slot is removed so the album is fetched - again. What's left here needs you. + are left alone, and a file filling another song's track slot is removed, its track waiting in + Needs a file. What's left here needs you.

    @@ -344,12 +340,12 @@ {:else if item.action === 'duplicate_wrong_file' && !item.details.kept_title}

    {item.details.artist}: one recording was filed as {removed.map((r) => r.title).join(' and ')}, - and it is none of them. Removed; the album will be fetched again. + and it is none of them. Removed; those tracks wait in Needs a file.

    {:else if item.action === 'duplicate_wrong_file'}

    {item.details.artist}: the recording of {item.details.kept_title} was also filed as - {removed.map((r) => r.title).join(', ')}. Removed from there; the album will be fetched again. + {removed.map((r) => r.title).join(', ')}. Removed from there; those tracks wait in Needs a file.

    {:else}

    @@ -437,7 +433,7 @@ {:else} @@ -517,23 +513,23 @@

    {/if} - {#if confirmingRefetch === group.id} + {#if confirmingRemoveSlots === group.id} {@const picked = pickedOf(group)}

    {#if picked} - The copy titled “{picked.title}” stays, and {plural(refetchRemoves(group).length, 'copy', 'copies')} + The copy titled “{picked.title}” stays, and {plural(slotRemovals(group).length, 'copy', 'copies')} under other titles will be deleted from disk. {:else} All {plural(group.members.length, 'copy', 'copies')} will be deleted from disk. {/if} - Their tracks stay, marked missing, with their likes and plays. The release the files came - from is set aside, and the album is fetched again from another one. + Their tracks stay, marked missing, with their likes and plays, until a good copy is in the + library folder.

    diff --git a/web/src/routes/collection/duplicates/duplicates.test.ts b/web/src/routes/collection/duplicates/duplicates.test.ts index 3fb657b7..550da0c4 100644 --- a/web/src/routes/collection/duplicates/duplicates.test.ts +++ b/web/src/routes/collection/duplicates/duplicates.test.ts @@ -14,12 +14,11 @@ vi.mock('#lib/api/admin.js', () => ({ dismissDuplicateGroup: vi.fn().mockResolvedValue(undefined), mergeDuplicateGroup: vi.fn().mockResolvedValue({ survivor_track_id: 'www-01', - removed_paths: ['/music/Moe Shop/WWW (2020)/www-02.mp3'] + removed_paths: ['/music/Mochi Shop/XYZ (2020)/www-02.mp3'] }), - refetchDuplicateGroup: vi.fn().mockResolvedValue({ + removeWrongSlotFiles: vi.fn().mockResolvedValue({ kept_track_id: null, - removed_paths: ['/music/Moe Shop/WWW (2020)/www-01.mp3', '/music/Moe Shop/WWW (2020)/www-02.mp3'], - blocked: ['Moe Shop - WWW [WEB]'] + removed_paths: ['/music/Mochi Shop/XYZ (2020)/www-01.mp3', '/music/Mochi Shop/XYZ (2020)/www-02.mp3'] }) })); vi.mock('#lib/player/store.svelte.js', () => ({ playQueue: vi.fn() })); @@ -31,7 +30,7 @@ import { createResolvedDuplicatesQuery, dismissDuplicateGroup, mergeDuplicateGroup, - refetchDuplicateGroup, + removeWrongSlotFiles, runDuplicateSweep } from '#lib/api/admin.js'; @@ -52,12 +51,12 @@ const allFingerprinted = { total: 1200, fingerprinted: 1200, rejected: 0, pendin function member(id: string, extra: Partial = {}) { return { track_id: id, - title: 'WWW', + title: 'XYZ', artist_id: 'ar-1', - artist_name: 'Moe Shop', + artist_name: 'Mochi Shop', album_id: 'al-1', - album_title: 'WWW', - file_path: `/music/Moe Shop/WWW (2020)/${id}.mp3`, + album_title: 'XYZ', + file_path: `/music/Mochi Shop/XYZ (2020)/${id}.mp3`, file_format: 'mp3', file_size: 6_900_000, duration_sec: 215, @@ -200,14 +199,14 @@ describe('admin duplicates', () => { ); }); - // Identical audio titled "WWW" and "WWW (instrumental)". One file + // Identical audio titled "XYZ" and "XYZ (instrumental)". One file // claimed to be the vocal and wasn't, and nothing said the vocal was missing. describe('identical audio under different titles', () => { function www() { const r = response(); r.groups[0] = { ...r.groups[0], - members: [member('www-01'), member('www-02', { title: 'WWW (instrumental)' })] + members: [member('www-01'), member('www-02', { title: 'XYZ (instrumental)' })] }; return r; } @@ -215,16 +214,16 @@ describe('admin duplicates', () => { test('says the copies are titled differently and names both titles', () => { renderWith(www()); const notice = text(screen.getByTestId('title-mismatch')); - expect(notice).toContain('titled “WWW” and “WWW (instrumental)”'); + expect(notice).toContain('titled “XYZ” and “XYZ (instrumental)”'); expect(notice).toContain("isn't in your library"); }); test('three different titles are all named', () => { const r = www(); - r.groups[0].members.push(member('www-03', { title: 'WWW (Radio Edit)' })); + r.groups[0].members.push(member('www-03', { title: 'XYZ (Radio Edit)' })); renderWith(r); expect(text(screen.getByTestId('title-mismatch'))).toContain( - '“WWW”, “WWW (instrumental)” and “WWW (Radio Edit)”' + '“XYZ”, “XYZ (instrumental)” and “XYZ (Radio Edit)”' ); }); @@ -233,8 +232,8 @@ describe('admin duplicates', () => { r.groups[0] = { ...r.groups[0], members: [ - member('www-01', { title: 'WWW (Instrumental)' }), - member('www-02', { title: ' www (instrumental) ' }) + member('www-01', { title: 'XYZ (Instrumental)' }), + member('www-02', { title: ' xyz (instrumental) ' }) ] }; renderWith(r); @@ -254,14 +253,14 @@ describe('admin duplicates', () => { expect(screen.queryByTestId('title-mismatch')).toBeNull(); }); - // Unless the resolver found different songs on one album: Savant's Mortals + // Unless the resolver found different songs on one album: Savanta's Immortals // held one recording as 16 tracks, each cut to its own song's length. test('an acoustic group the resolver found to be different songs says so', () => { const r = www(); r.groups[0] = { ...r.groups[0], tier: 'acoustic', worst_bit_error_rate: 0, class: 'mismatch' }; renderWith(r); const notice = text(screen.getByTestId('title-mismatch')); - expect(notice).toContain('The music is the same, but the copies are titled “WWW” and “WWW (instrumental)”'); + expect(notice).toContain('The music is the same, but the copies are titled “XYZ” and “XYZ (instrumental)”'); expect(notice).toContain("If you can't tell, get the album again"); }); }); @@ -277,48 +276,48 @@ describe('admin duplicates', () => { tier: 'acoustic', worst_bit_error_rate: 0.04, class: 'mismatch', - members: [member('www-01'), member('www-02', { title: 'WWW (instrumental)' })] + members: [member('www-01'), member('www-02', { title: 'XYZ (instrumental)' })] }; return r; } - test('offers Get it again instead of Merge, with no copy proposed', () => { + test('offers Remove the copies instead of Merge, with no copy proposed', () => { renderWith(slots()); expect(screen.queryByRole('button', { name: 'Merge…' })).toBeNull(); - expect(screen.getByRole('button', { name: 'Get it again…' })).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Remove the copies…' })).toBeTruthy(); expect(screen.getAllByRole('radio').some((r) => (r as HTMLInputElement).checked)).toBe(false); expect(screen.queryByTestId('survivor-badge')).toBeNull(); }); test("can't tell: every copy goes, after a second click", async () => { renderWith(slots()); - await fireEvent.click(screen.getByRole('button', { name: 'Get it again…' })); - expect(refetchDuplicateGroup).not.toHaveBeenCalled(); + await fireEvent.click(screen.getByRole('button', { name: 'Remove the copies…' })); + expect(removeWrongSlotFiles).not.toHaveBeenCalled(); const confirm = text(screen.getByTestId('refetch-confirm')); expect(confirm).toContain('All 2 copies will be deleted from disk'); - expect(confirm).toContain('the album is fetched again from another one'); + expect(confirm).toContain('until a good copy is in the library folder'); - await fireEvent.click(screen.getByRole('button', { name: 'Remove 2 files and get it again' })); - expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: '' }); + await fireEvent.click(screen.getByRole('button', { name: 'Remove 2 files' })); + expect(removeWrongSlotFiles).toHaveBeenCalledWith('g-1', { keep_track_id: '' }); }); test('naming the song keeps that copy and removes the others', async () => { renderWith(slots()); - await fireEvent.click(screen.getByRole('radio', { name: /This is WWW \(instrumental\)/ })); + await fireEvent.click(screen.getByRole('radio', { name: /This is XYZ \(instrumental\)/ })); expect(screen.getByTestId('song-badge')).toBeTruthy(); - await fireEvent.click(screen.getByRole('button', { name: 'Keep “WWW (instrumental)”…' })); + await fireEvent.click(screen.getByRole('button', { name: 'Keep “XYZ (instrumental)”…' })); expect(text(screen.getByTestId('refetch-confirm'))).toContain( - 'The copy titled “WWW (instrumental)” stays, and 1 copy under other titles will be deleted from disk' + 'The copy titled “XYZ (instrumental)” stays, and 1 copy under other titles will be deleted from disk' ); - await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file and get it again' })); - expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' }); + await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file' })); + expect(removeWrongSlotFiles).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' }); }); test("I can't tell takes the pick back", async () => { renderWith(slots()); await fireEvent.click(screen.getAllByRole('radio')[0]); await fireEvent.click(screen.getByRole('button', { name: "I can't tell which song it is" })); - expect(screen.getByRole('button', { name: 'Get it again…' })).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Remove the copies…' })).toBeTruthy(); expect(screen.queryByTestId('song-badge')).toBeNull(); }); }); @@ -444,15 +443,15 @@ describe('admin duplicates', () => { action: 'duplicate_merge', created_at: ago(HOUR), details: { - survivor_path: '/music/Gorillaz/Humanz (2017)/03 - Saturnz Barz.mp3', + survivor_path: '/music/Plastic Apes/Mammalz (2017)/03 - Neptunez Barz.mp3', survivor_reason: 'the copy that is not a video rip', - removed: [{ track_id: 't-2', file_path: '/music/Gorillaz/Humanz (2017)/03 - Saturnz Barz (Official Video).mp3' }] + removed: [{ track_id: 't-2', file_path: '/music/Plastic Apes/Mammalz (2017)/03 - Neptunez Barz (Official Video).mp3' }] } } ]); await fireEvent.click(screen.getByRole('tab', { name: /resolved automatically/i })); const items = screen.getAllByTestId('resolved-item').map(text); - expect(items[0]).toContain('Kept 03 - Saturnz Barz.mp3 (the copy that is not a video rip) and removed 1 file.'); + expect(items[0]).toContain('Kept 03 - Neptunez Barz.mp3 (the copy that is not a video rip) and removed 1 file.'); expect(screen.queryByTestId('duplicate-group')).toBeNull(); }); @@ -462,16 +461,16 @@ describe('admin duplicates', () => { id: 'a-2', action: 'duplicate_dismiss', created_at: ago(HOUR), - details: { artist: 'Moe Shop', titles: ['Lovesick', 'Lovesick (Instrumental)'] } + details: { artist: 'Mochi Shop', titles: ['Homesick', 'Homesick (Instrumental)'] } }, { id: 'a-3', action: 'duplicate_wrong_file', created_at: ago(HOUR), details: { - artist: 'Savant', + artist: 'Savanta', kept_title: 'Void', - removed: [{ track_id: 't-9', file_path: '/data/Music/Savant/Void/17 - Reach.m4a', title: 'Reach' }] + removed: [{ track_id: 't-9', file_path: '/data/Music/Savanta/Void/17 - Reach.m4a', title: 'Reach' }] } }, { @@ -479,23 +478,23 @@ describe('admin duplicates', () => { action: 'duplicate_wrong_file', created_at: ago(HOUR), details: { - artist: 'Shnabubula', + artist: 'Shnorkelbub', removed: [ - { track_id: 't-5', file_path: '/data/Music/Shnabubula/05 - Fading Light.mp3', title: 'Fading Light' }, - { track_id: 't-10', file_path: '/data/Music/Shnabubula/10 - Looking for Answers.mp3', title: 'Looking for Answers' } + { track_id: 't-5', file_path: '/data/Music/Shnorkelbub/05 - Fading Light.mp3', title: 'Fading Light' }, + { track_id: 't-10', file_path: '/data/Music/Shnorkelbub/10 - Looking for Answers.mp3', title: 'Looking for Answers' } ] } } ]); await fireEvent.click(screen.getByRole('tab', { name: /resolved automatically/i })); const items = screen.getAllByTestId('resolved-item').map(text); - expect(items[0]).toContain('Moe Shop: Lovesick and Lovesick (Instrumental) are different versions, not duplicates. Both kept.'); + expect(items[0]).toContain('Mochi Shop: Homesick and Homesick (Instrumental) are different versions, not duplicates. Both kept.'); expect(items[1]).toContain( - 'Savant: the recording of Void was also filed as Reach. Removed from there; the album will be fetched again.' + 'Savanta: the recording of Void was also filed as Reach. Removed from there; those tracks wait in Needs a file.' ); - expect(items[1]).toContain('/data/Music/Savant/Void/17 - Reach.m4a'); + expect(items[1]).toContain('/data/Music/Savanta/Void/17 - Reach.m4a'); expect(items[2]).toContain( - 'Shnabubula: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; the album will be fetched again.' + 'Shnorkelbub: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; those tracks wait in Needs a file.' ); }); }); diff --git a/web/src/routes/collection/following/+page.svelte b/web/src/routes/collection/following/+page.svelte deleted file mode 100644 index b891a091..00000000 --- a/web/src/routes/collection/following/+page.svelte +++ /dev/null @@ -1,12 +0,0 @@ - - -{pageTitle('Collection · Following')} - -
    - - -
    diff --git a/web/src/routes/collection/missing/+page.svelte b/web/src/routes/collection/missing/+page.svelte index 92c2af49..89528e2e 100644 --- a/web/src/routes/collection/missing/+page.svelte +++ b/web/src/routes/collection/missing/+page.svelte @@ -1,31 +1,23 @@ -{pageTitle('Collection · Missing files')} +{pageTitle('Collection · Needs a file')}
    -
    -

    Missing files

    +
    +

    Needs a file

    {#if total > 0} {total} +
    + + Export CSV + + +
    {/if}

    - Tracks whose audio file the last scan couldn't find. They keep their play - history and likes, and stop being offered anywhere until the file returns. + Tracks without a file to play: removed from Reports, Duplicates or Suspect sources, or gone + from disk. Each keeps its play history and likes, and is not offered anywhere until a good + copy is in the library folder, which it then takes over. Export the list to find them.

    -

    - {#if policy} - {policy.enabled - ? `Albums missing for ${policy.grace_hours} hours go back on the wanted list by themselves.` - : 'Missing albums are not wanted back automatically.'} - {/if} - - {policy ? 'Change' : 'Set what happens to missing files'} - -

    - {#if query.isPending} -

    Checking what's missing…

    +

    Reading the list…

    {:else if query.isError}

    - Couldn't load the missing files. + Couldn't load the list.

    {:else if groups.length === 0} + row here or what takes it away. -->
    -

    Every track's file is where it should be.

    +

    Every track has its file.

    - A track lands here when a library scan can't find its file — moved outside - Minstrel, deleted, or on a drive that didn't mount. It leaves on its own - when the file comes back. + A track lands here when its file is removed from one of the Collection's queues, or when a + library scan can't find its file. It leaves on its own when a good copy is in the library, + or when you forget it.

    {:else} @@ -149,111 +145,52 @@
  • -
    -

    +
    +

    {group.directory}

    - - {plural(group.tracks.length, 'track', 'tracks')} · gone {relativeTime(group.missing_since)} - -
    - - - {#if group.reacquisition} - {@const r = group.reacquisition} - {@const w = r.want} -
    -
    -
    -

    - {#if r.held_at} - Held again {relativeTime(r.held_at)}. The rows here clear on the next scan. - {:else if r.wanted_at} - Wanted back since {relativeTime(r.wanted_at)}. - {/if} -

    - {#if w && !r.held_at} -

    - {wantStatus(w)} - {#if needsYou(w)} - Decide on Activity - {/if} -

    - {/if} -
    - {#if w && !r.held_at} -
    - - - -
    - {/if} -
    - {#if w && open === w.id} - +
    + + {plural(group.tracks.length, 'track', 'tracks')} · {relativeTime(group.missing_since)} + + {#if group.tracks.length > 1} + {/if}
    - {/if} +
      {#each group.tracks as t (t.track_id)}
    • - +
      {t.title}
      {t.artist_name} · {t.album_title}
      +
      + {why(t)} · {relativeTime(t.missing_since)} +
      - + {formatDuration(t.duration_sec)} +
    • {/each}
    @@ -269,7 +214,7 @@ {#if hasMore || offset > 0} -

  • - {/each} - - - -
    - {#if query.isError} - - {:else if query.isPending} -

    Searching…

    - {:else if results.length === 0} -

    Nothing to add for that search yet.

    - {:else} -
    - {#each results as r (r.mbid)} - handleRequestClick(r)} - /> - {/each} -
    - {/if} -
    - {/if} -
    - - - {#if modalResult} -

    - Requesting {modalResult.name} - will add {modalResult.secondary_text}. - Continue? -

    -
    - - -
    - {/if} -
    diff --git a/web/src/routes/discover/discover.test.ts b/web/src/routes/discover/discover.test.ts deleted file mode 100644 index 23b8aa77..00000000 --- a/web/src/routes/discover/discover.test.ts +++ /dev/null @@ -1,319 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; -import { mockQuery } from '../../test-utils/query'; -import { apiClientMock } from '../../test-utils/mocks/client'; -import type { CatalogueSearchResult } from '#lib/api/types.js'; -import { pageUrlModule } from '../../test-utils/mocks/appState'; - -// $app/state / $app/navigation must be mocked or rendering the page -// pulls in SvelteKit's client runtime (`notifiable_store is not a -// function`) at module load. Same pattern as the other route tests. -const pageState = vi.hoisted(() => ({ - pageUrl: new URL('http://localhost/discover') -})); -vi.mock('$app/state', () => pageUrlModule(pageState)); -vi.mock('$app/navigation', () => ({ goto: vi.fn() })); - -// The catalogue search query factory and createRequest are mocked at the module -// level so each test can shape what the page sees without standing up a -// real QueryClient + network. -vi.mock('#lib/api/catalogue.js', () => ({ - createCatalogueSearchQuery: vi.fn() -})); - -// SuggestionFeed reaches for the snooze surface too. These are -// stubbed here even though this page-level suite asserts nothing about -// snoozing: a factory-shaped module mock must export everything the -// component tree imports, or rendering the feed throws before any -// assertion runs. -vi.mock('#lib/api/suggestions.js', () => ({ - createSuggestionsQuery: vi.fn(), - createSnoozesQuery: vi.fn(), - snoozeSuggestion: vi.fn().mockResolvedValue(undefined), - unsnoozeSuggestion: vi.fn().mockResolvedValue(undefined) -})); - -vi.mock('#lib/api/requests.js', () => ({ - createRequest: vi.fn().mockResolvedValue({ id: 'r1' }) -})); - -vi.mock('#lib/api/client.js', () => apiClientMock()); - -// The page calls useQueryClient() to invalidate qk.myRequests() after a -// submit; stub it so rendering doesn't require a real QueryClient and -// we can assert the invalidation fires. -const queryClientMock = vi.hoisted(() => ({ invalidateQueries: vi.fn() })); -vi.mock('@tanstack/svelte-query', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, useQueryClient: () => queryClientMock }; -}); - -import DiscoverPage from './+page.svelte'; -import { createCatalogueSearchQuery } from '#lib/api/catalogue.js'; -import { createSuggestionsQuery, createSnoozesQuery } from '#lib/api/suggestions.js'; -import { createRequest } from '#lib/api/requests.js'; - -const mockedCreateQuery = createCatalogueSearchQuery as ReturnType; -const mockedCreateSuggestionsQuery = createSuggestionsQuery as ReturnType; -const mockedCreateSnoozesQuery = createSnoozesQuery as ReturnType; -const mockedCreateRequest = createRequest as ReturnType; - -function result(over: Partial = {}): CatalogueSearchResult { - return { - mbid: 'mbid-1', - name: 'Boards of Canada', - secondary_text: 'Electronic', - image_url: '', - artist_mbid: 'art-1', - album_mbid: '', - in_library: false, - requested: false, - ...over - }; -} - -beforeEach(() => { - // Default: empty results, non-pending. Tests override per-case. - mockedCreateQuery.mockReturnValue(mockQuery({ data: [] })); - // Default: empty suggestion feed so its empty-state copy renders without - // interfering with search-mode tests. - mockedCreateSuggestionsQuery.mockReturnValue(mockQuery({ data: [] })); - // Nothing parked, which keeps the feed's empty-state copy on the - // "no signal yet" branch that this suite's assertions expect. - mockedCreateSnoozesQuery.mockReturnValue(mockQuery({ data: [] })); -}); - -afterEach(() => { - vi.clearAllMocks(); -}); - -describe('Discover page', () => { - test('initial state (no query) shows the suggestion feed', () => { - render(DiscoverPage); - expect(screen.getByText(/suggested for you/i)).toBeInTheDocument(); - }); - - test('empty input shows the suggestion feed', () => { - render(DiscoverPage); - expect(screen.getByText(/suggested for you/i)).toBeInTheDocument(); - // Kind tabs should NOT be visible when input is empty. - expect( - screen.queryByRole('button', { name: 'Artists' }) - ).not.toBeInTheDocument(); - }); - - test('typing replaces feed with search', async () => { - vi.useFakeTimers(); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'miles' } }); - await vi.advanceTimersByTimeAsync(250); - expect(screen.queryByText(/suggested for you/i)).not.toBeInTheDocument(); - expect(screen.getByText(/add music to the library/i)).toBeInTheDocument(); - // Kind tabs visible when searching. - expect(screen.getByRole('button', { name: 'Artists' })).toBeInTheDocument(); - vi.useRealTimers(); - }); - - test('debounced input fires query factory with typed value after 250ms', async () => { - vi.useFakeTimers(); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'boards' } }); - // Before the timer elapses, the factory was called only with the - // initial empty string — never with 'boards'. - expect(mockedCreateQuery).not.toHaveBeenCalledWith('boards', 'artist'); - await vi.advanceTimersByTimeAsync(250); - expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'artist'); - vi.useRealTimers(); - }); - - test('switching tabs refetches with the new kind', async () => { - vi.useFakeTimers(); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'boards' } }); - await vi.advanceTimersByTimeAsync(250); - // Switch to Albums. - await fireEvent.click(screen.getByRole('button', { name: 'Albums' })); - expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'album'); - // Then to Tracks. - await fireEvent.click(screen.getByRole('button', { name: 'Tracks' })); - expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'track'); - vi.useRealTimers(); - }); - - test('empty results state renders the voice-rule copy', async () => { - vi.useFakeTimers(); - mockedCreateQuery.mockReturnValue(mockQuery({ data: [] })); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'zzz' } }); - await vi.advanceTimersByTimeAsync(250); - await waitFor(() => - expect( - screen.getByText(/nothing to add for that search yet\./i) - ).toBeInTheDocument() - ); - vi.useRealTimers(); - }); - - test('artist-kind Request click calls createRequest immediately (no modal)', async () => { - vi.useFakeTimers(); - const r = result({ - mbid: 'art-mbid', - artist_mbid: 'art-mbid', - name: 'Boards of Canada' - }); - mockedCreateQuery.mockReturnValue(mockQuery({ data: [r] })); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'boards' } }); - await vi.advanceTimersByTimeAsync(250); - vi.useRealTimers(); - - const requestBtn = await screen.findByRole('button', { - name: /request boards of canada/i - }); - await fireEvent.click(requestBtn); - expect(mockedCreateRequest).toHaveBeenCalledTimes(1); - expect(mockedCreateRequest).toHaveBeenCalledWith( - expect.objectContaining({ kind: 'artist' }) - ); - // Modal must not be present for non-track kinds. - expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); - }); - - test('requestable card flips to "Requested" after a successful request', async () => { - vi.useFakeTimers(); - const r = result({ - mbid: 'art-mbid', - artist_mbid: 'art-mbid', - name: 'Boards of Canada' - }); - mockedCreateQuery.mockReturnValue(mockQuery({ data: [r] })); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'boards' } }); - await vi.advanceTimersByTimeAsync(250); - vi.useRealTimers(); - - const requestBtn = await screen.findByRole('button', { - name: /request boards of canada/i - }); - await fireEvent.click(requestBtn); - await waitFor(() => { - const flipped = screen.getByRole('button', { name: /already requested/i }); - expect(flipped).toBeDisabled(); - }); - }); - - test('submitting a request invalidates myRequests so /requests updates (#369)', async () => { - vi.useFakeTimers(); - const r = result({ mbid: 'art-mbid', artist_mbid: 'art-mbid', name: 'Boards of Canada' }); - mockedCreateQuery.mockReturnValue(mockQuery({ data: [r] })); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'boards' } }); - await vi.advanceTimersByTimeAsync(250); - vi.useRealTimers(); - - const requestBtn = await screen.findByRole('button', { - name: /request boards of canada/i - }); - await fireEvent.click(requestBtn); - await waitFor(() => { - expect(queryClientMock.invalidateQueries).toHaveBeenCalledWith({ - queryKey: ['myRequests'] - }); - }); - }); - - test('track-kind Request click opens confirm modal; Confirm calls createRequest', async () => { - vi.useFakeTimers(); - const r = result({ - mbid: 'tr-mbid', - artist_mbid: 'art-mbid', - album_mbid: 'al-mbid', - name: 'Roygbiv', - secondary_text: 'Music Has The Right To Children · Boards of Canada' - }); - mockedCreateQuery.mockReturnValue(mockQuery({ data: [r] })); - render(DiscoverPage); - // Type first so the kind tabs become visible (empty-input mode shows the - // suggestion feed and hides tabs). - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'roy' } }); - await vi.advanceTimersByTimeAsync(250); - // Switch to track kind. - await fireEvent.click(screen.getByRole('button', { name: 'Tracks' })); - vi.useRealTimers(); - - const requestBtn = await screen.findByRole('button', { - name: /request roygbiv/i - }); - await fireEvent.click(requestBtn); - // Modal opens with the explanation copy. - const dialog = await screen.findByRole('dialog'); - expect(dialog).toBeInTheDocument(); - expect(dialog.textContent).toMatch(/continue/i); - // Confirm fires createRequest with kind=track. - await fireEvent.click(screen.getByRole('button', { name: /add the album/i })); - expect(mockedCreateRequest).toHaveBeenCalledTimes(1); - expect(mockedCreateRequest).toHaveBeenCalledWith( - expect.objectContaining({ - kind: 'track', - track_mbid: 'tr-mbid', - album_mbid: 'al-mbid', - artist_mbid: 'art-mbid' - }) - ); - }); - - test('track-kind modal Cancel does not call createRequest', async () => { - vi.useFakeTimers(); - const r = result({ - mbid: 'tr-mbid', - artist_mbid: 'art-mbid', - album_mbid: 'al-mbid', - name: 'Roygbiv', - secondary_text: 'Music Has The Right To Children · Boards of Canada' - }); - mockedCreateQuery.mockReturnValue(mockQuery({ data: [r] })); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'roy' } }); - await vi.advanceTimersByTimeAsync(250); - await fireEvent.click(screen.getByRole('button', { name: 'Tracks' })); - vi.useRealTimers(); - - const requestBtn = await screen.findByRole('button', { - name: /request roygbiv/i - }); - await fireEvent.click(requestBtn); - await screen.findByRole('dialog'); - await fireEvent.click(screen.getByRole('button', { name: /^cancel$/i })); - expect(mockedCreateRequest).not.toHaveBeenCalled(); - expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); - }); - - test('in_library result renders kept state regardless of requested', async () => { - vi.useFakeTimers(); - const r = result({ - mbid: 'kept-1', - name: 'Kind of Blue', - in_library: true, - requested: true - }); - mockedCreateQuery.mockReturnValue(mockQuery({ data: [r] })); - render(DiscoverPage); - const input = screen.getByLabelText(/search musicbrainz/i); - await fireEvent.input(input, { target: { value: 'kind' } }); - await vi.advanceTimersByTimeAsync(250); - vi.useRealTimers(); - - await waitFor(() => { - expect(screen.getByRole('button', { name: /in library/i })).toBeDisabled(); - }); - }); -}); diff --git a/web/src/routes/forgot-password/+page.svelte b/web/src/routes/forgot-password/+page.svelte index 80a2dad4..fc77671e 100644 --- a/web/src/routes/forgot-password/+page.svelte +++ b/web/src/routes/forgot-password/+page.svelte @@ -33,7 +33,7 @@
    -

    Forgot password

    +

    Forgot password

    {#if !submitted}

    diff --git a/web/src/routes/library/albums/+page.svelte b/web/src/routes/library/albums/+page.svelte index 04ca50ff..6b92c6b7 100644 --- a/web/src/routes/library/albums/+page.svelte +++ b/web/src/routes/library/albums/+page.svelte @@ -1,104 +1,26 @@ {pageTitle('Library · Albums')} -

    -
    -
    -

    Albums

    - {#if !query.isPending && !(query.isError && !query.isFetchNextPageError)} -

    - {plural(total, 'album', 'albums')} -

    - {/if} -
    - {#if albums.length > 0} - - {/if} -
    - - {#if query.isError && !query.isFetchNextPageError} - - {:else if showSkeleton.value && albums.length === 0} -

    Loading…

    - {:else if !query.isPending && total === 0} - - {#if user.value?.is_admin} - - {#snippet actions()} - - Run a scan - - {/snippet} - - {:else} - - {/if} - {:else if filter.trim() && filtered.length === 0} -

    - No albums in your loaded library match - '{filter.trim()}'. - - Search the full library → - -

    - {:else} - a.sort_title || a.title} - hasMore={!!query.hasNextPage} - onLoadMore={() => query.fetchNextPage()} - > - {#snippet item(album: AlbumRef)} - - {/snippet} - - - query.fetchNextPage()} - endLabel="End of library" - /> - {/if} -
    + a.title.toLowerCase().includes(q) || a.artist_name.toLowerCase().includes(q)} + getKey={(a: AlbumRef) => a.sort_title || a.title} + searchPath="/search/albums" +> + {#snippet item(album: AlbumRef)} + + {/snippet} + diff --git a/web/src/routes/library/artists/+page.svelte b/web/src/routes/library/artists/+page.svelte index 88ddf950..c8f34c9a 100644 --- a/web/src/routes/library/artists/+page.svelte +++ b/web/src/routes/library/artists/+page.svelte @@ -1,102 +1,26 @@ {pageTitle('Library · Artists')} -
    -
    -
    -

    Artists

    - {#if !query.isPending && !(query.isError && !query.isFetchNextPageError)} -

    - {plural(total, 'artist', 'artists')} -

    - {/if} -
    - {#if artists.length > 0} - - {/if} -
    - - {#if query.isError && !query.isFetchNextPageError} - - {:else if showSkeleton.value && artists.length === 0} -

    Loading…

    - {:else if !query.isPending && total === 0} - - {#if user.value?.is_admin} - - {#snippet actions()} - - Run a scan - - {/snippet} - - {:else} - - {/if} - {:else if filter.trim() && filtered.length === 0} -

    - No artists in your loaded library match - '{filter.trim()}'. - - Search the full library → - -

    - {:else} - a.sort_name || a.name} - hasMore={!!query.hasNextPage} - onLoadMore={() => query.fetchNextPage()} - > - {#snippet item(a: ArtistRef)} - - {/snippet} - - - query.fetchNextPage()} - endLabel="End of library" - /> - {/if} -
    + a.name.toLowerCase().includes(q)} + getKey={(a: ArtistRef) => a.sort_name || a.name} + searchPath="/search/artists" +> + {#snippet item(a: ArtistRef)} + + {/snippet} + diff --git a/web/src/routes/library/genres/+page.svelte b/web/src/routes/library/genres/+page.svelte index ba7b0e18..9eeda96a 100644 --- a/web/src/routes/library/genres/+page.svelte +++ b/web/src/routes/library/genres/+page.svelte @@ -2,19 +2,15 @@ import { plural } from '#lib/utils/plural.js'; import { page } from '$app/state'; import { pageTitle } from '#lib/branding.js'; - import { ChevronLeft } from 'lucide-svelte'; import { createGenresQuery, - listAlbumsByGenre, - BROWSE_PAGE_SIZE, + createAlbumsByGenreInfiniteQuery, type GenreCount } from '#lib/api/browse.js'; - import AlbumCard from '#lib/components/AlbumCard.svelte'; + import AlbumDrillDown from '#lib/components/AlbumDrillDown.svelte'; import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte'; import EmptyState from '#lib/components/EmptyState.svelte'; - import ListContinuation from '#lib/components/ListContinuation.svelte'; import QuickFilter from '#lib/components/QuickFilter.svelte'; - import type { AlbumRef } from '#lib/api/types.js'; const indexStore = createGenresQuery(); const index = $derived($indexStore); @@ -57,57 +53,8 @@ return list; // server order: count DESC, then name }); - let albums = $state([]); - let total = $state(0); - let loading = $state(false); - let failed = $state(false); - // A later page failed: the albums already shown stay, and the list offers a - // retry at its end instead of loading again on every scroll. - let moreFailed = $state(false); - - // Plain `let`, deliberately not $state: it's read inside the fetch path, and - // as reactive state that read would make this effect depend on its own - // writes. Its only job is to let a late response for a previous genre be - // discarded rather than painted over the current one. - let requestToken = 0; - - $effect(() => { - const g = selected; // the only tracked read — reload when selection moves - void reload(g); - }); - - async function reload(genre: string) { - requestToken += 1; - albums = []; - total = 0; - failed = false; - moreFailed = false; - if (!genre) return; - await fetchPage(genre, 0, requestToken); - } - - async function fetchPage(genre: string, offset: number, token: number) { - loading = true; - try { - const p = await listAlbumsByGenre(genre, BROWSE_PAGE_SIZE, offset); - if (token !== requestToken) return; // selection moved on; drop it - albums = offset === 0 ? p.items : [...albums, ...p.items]; - total = p.total; - } catch { - if (token === requestToken) { - if (offset === 0) failed = true; - else moreFailed = true; - } - } finally { - if (token === requestToken) loading = false; - } - } - - function loadMore() { - if (loading) return; - moreFailed = false; - void fetchPage(selected, albums.length, requestToken); - } + const albumsStore = $derived(selected ? createAlbumsByGenreInfiniteQuery(selected) : null); + const albums = $derived(albumsStore ? $albumsStore : null); function genreHref(genre: string): string { return `/library/genres?g=${encodeURIComponent(genre)}`; @@ -119,61 +66,18 @@ {#if selected} -
    -
    - - -
    -

    {selected}

    - {#if !loading || albums.length > 0} -

    - {plural(total, 'album', 'albums')} -

    - {/if} -
    -
    - - {#if failed} -

    - Couldn't load albums for this genre. - -

    - {:else if loading && albums.length === 0} -

    Loading…

    - {:else if albums.length === 0} - - - {:else} -
    - {#each albums as album (album.id)} - - {/each} -
    - - {/if} -
    + + {:else}
    diff --git a/web/src/routes/library/genres/genres.test.ts b/web/src/routes/library/genres/genres.test.ts index 8798275a..489fcc4c 100644 --- a/web/src/routes/library/genres/genres.test.ts +++ b/web/src/routes/library/genres/genres.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { render, screen, waitFor, fireEvent } from '@testing-library/svelte'; -import { mockQuery } from '#test-utils/query.js'; +import { mockInfiniteQuery, mockQuery } from '#test-utils/query.js'; +import { page } from '#test-utils/fixtures/page.js'; import { installIntersectionObserverMock } from '#test-utils/intersectionObserver.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { apiClientMock } from '#test-utils/mocks/client.js'; @@ -16,7 +17,7 @@ vi.mock('$app/state', () => pageUrlModule(pageState)); vi.mock('#lib/api/browse.js', () => ({ BROWSE_PAGE_SIZE: 2, createGenresQuery: vi.fn(), - listAlbumsByGenre: vi.fn() + createAlbumsByGenreInfiniteQuery: vi.fn() })); vi.mock('#lib/api/client.js', () => apiClientMock()); @@ -30,7 +31,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({ })); import GenresPage from './+page.svelte'; -import { createGenresQuery, listAlbumsByGenre } from '#lib/api/browse.js'; +import { createGenresQuery, createAlbumsByGenreInfiniteQuery } from '#lib/api/browse.js'; const asMock = (fn: unknown) => fn as ReturnType; @@ -176,57 +177,67 @@ describe('/library/genres index', () => { }); describe('/library/genres drill-down', () => { - test('fetches and renders albums for the selected genre', async () => { + test('fetches and renders albums for the selected genre', () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock%2FPop'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre).mockResolvedValue({ - items: [album('a1', 'First Album')], - total: 1, - limit: 2, - offset: 0 - }); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ pages: [page([album('a1', 'First Album')], 1)] }) + ); render(GenresPage); // The decoded genre must reach the API, not the percent-encoded form. - await waitFor(() => expect(listAlbumsByGenre).toHaveBeenCalledWith('Rock/Pop', 2, 0)); - expect(await screen.findByText('First Album')).toBeInTheDocument(); + expect(createAlbumsByGenreInfiniteQuery).toHaveBeenCalledWith('Rock/Pop'); + expect(screen.getByText('First Album')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Rock/Pop' })).toBeInTheDocument(); }); - test('scrolling to the end loads the next page, then reports the end', async () => { + test('scrolling to the end loads the next page', async () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre) - .mockResolvedValueOnce({ - items: [album('a1', 'One'), album('a2', 'Two')], - total: 3, - limit: 2, - offset: 0 + const fetchNextPage = vi.fn(); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + hasNextPage: true, + fetchNextPage }) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + ); render(GenresPage); - await screen.findByText('One'); // No button: reaching the bottom of the grid loads the next page. expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument(); await waitFor(() => { io.scrollToEnd(); - expect(listAlbumsByGenre).toHaveBeenLastCalledWith('Rock', 2, 2); + expect(fetchNextPage).toHaveBeenCalled(); }); + }); - expect(await screen.findByText('Three')).toBeInTheDocument(); - // Earlier pages are appended, not replaced. + test('the last page says the list has ended', () => { + pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); + asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3), page([album('a3', 'Three')], 3, 2)] + }) + ); + render(GenresPage); + + // Pages are appended, not replaced. expect(screen.getByText('One')).toBeInTheDocument(); - expect(await screen.findByText('End of genre')).toBeInTheDocument(); + expect(screen.getByText('Three')).toBeInTheDocument(); + expect(screen.getByText('End of genre')).toBeInTheDocument(); }); test('a failed drill-down offers a retry rather than an empty grid', async () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre).mockRejectedValue(new Error('nope')); + const refetch = vi.fn(); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue(mockInfiniteQuery({ isError: true, refetch })); render(GenresPage); - expect(await screen.findByText(/Couldn't load albums for this genre/i)).toBeInTheDocument(); + expect(screen.getByText(/Couldn't load albums for this genre/i)).toBeInTheDocument(); + await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); + expect(refetch).toHaveBeenCalled(); }); // A failed later page keeps what is shown and offers a retry at the end, @@ -234,21 +245,23 @@ describe('/library/genres drill-down', () => { test('a failed later page keeps the albums and offers Try again', async () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre) - .mockResolvedValueOnce({ items: [album('a1', 'One'), album('a2', 'Two')], total: 3, limit: 2, offset: 0 }) - .mockRejectedValueOnce(new Error('nope')) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + const fetchNextPage = vi.fn(); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + isError: true, + hasNextPage: true, + isFetchNextPageError: true, + fetchNextPage + }) + ); render(GenresPage); - await screen.findByText('One'); - await waitFor(() => { - io.scrollToEnd(); - expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); - }); + expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.queryByText(/Couldn't load albums for this genre/i)).not.toBeInTheDocument(); await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); - expect(await screen.findByText('Three')).toBeInTheDocument(); + expect(fetchNextPage).toHaveBeenCalled(); }); }); diff --git a/web/src/routes/library/hidden/+page.svelte b/web/src/routes/library/hidden/+page.svelte index f8fe1669..64f7097f 100644 --- a/web/src/routes/library/hidden/+page.svelte +++ b/web/src/routes/library/hidden/+page.svelte @@ -1,7 +1,8 @@ @@ -104,58 +51,16 @@ {#if selected !== null} -
    -
    - - -
    -

    {selected}

    - {#if !loading || albums.length > 0} -

    - {plural(total, 'album', 'albums')} -

    - {/if} -
    -
    - - {#if failed} -

    - Couldn't load albums for {selected}. - -

    - {:else if loading && albums.length === 0} -

    Loading…

    - {:else if albums.length === 0} - - {:else} -
    - {#each albums as album (album.id)} - - {/each} -
    - - {/if} -
    + {:else}
    diff --git a/web/src/routes/library/years/years.test.ts b/web/src/routes/library/years/years.test.ts index ac833f84..698d754b 100644 --- a/web/src/routes/library/years/years.test.ts +++ b/web/src/routes/library/years/years.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { render, screen, waitFor, fireEvent } from '@testing-library/svelte'; -import { mockQuery } from '#test-utils/query.js'; +import { mockInfiniteQuery, mockQuery } from '#test-utils/query.js'; +import { page } from '#test-utils/fixtures/page.js'; import { installIntersectionObserverMock } from '#test-utils/intersectionObserver.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { apiClientMock } from '#test-utils/mocks/client.js'; @@ -16,7 +17,7 @@ vi.mock('$app/state', () => pageUrlModule(pageState)); vi.mock('#lib/api/browse.js', () => ({ BROWSE_PAGE_SIZE: 2, createAlbumYearsQuery: vi.fn(), - listAlbumsByYear: vi.fn() + createAlbumsByYearInfiniteQuery: vi.fn() })); vi.mock('#lib/api/client.js', () => apiClientMock()); @@ -30,7 +31,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({ })); import YearsPage from './+page.svelte'; -import { createAlbumYearsQuery, listAlbumsByYear } from '#lib/api/browse.js'; +import { createAlbumYearsQuery, createAlbumsByYearInfiniteQuery } from '#lib/api/browse.js'; const asMock = (fn: unknown) => fn as ReturnType; @@ -125,19 +126,17 @@ describe('/library/years index', () => { }); describe('/library/years drill-down', () => { - test('requests the selected year as a degenerate range', async () => { + test('requests the selected year and renders its albums', () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear).mockResolvedValue({ - items: [album('a1', 'Mid Nineties')], - total: 1, - limit: 2, - offset: 0 - }); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ pages: [page([album('a1', 'Mid Nineties')], 1)] }) + ); render(YearsPage); - await waitFor(() => expect(listAlbumsByYear).toHaveBeenCalledWith(1995, 2, 0)); - expect(await screen.findByText('Mid Nineties')).toBeInTheDocument(); + expect(createAlbumsByYearInfiniteQuery).toHaveBeenCalledWith(1995); + expect(screen.getByText('Mid Nineties')).toBeInTheDocument(); + expect(screen.getByText('1 album')).toBeInTheDocument(); }); test('a non-numeric year is treated as no selection', () => { @@ -148,43 +147,57 @@ describe('/library/years drill-down', () => { render(YearsPage); // Falls back to the index rather than fetching NaN. - expect(listAlbumsByYear).not.toHaveBeenCalled(); + expect(createAlbumsByYearInfiniteQuery).not.toHaveBeenCalled(); expect(screen.getByRole('heading', { level: 1, name: 'Years' })).toBeInTheDocument(); }); - test('scrolling to the end loads the next page, then reports the end', async () => { + test('scrolling to the end loads the next page', async () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear) - .mockResolvedValueOnce({ - items: [album('a1', 'One'), album('a2', 'Two')], - total: 3, - limit: 2, - offset: 0 + const fetchNextPage = vi.fn(); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + hasNextPage: true, + fetchNextPage }) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + ); render(YearsPage); - await screen.findByText('One'); // No button: reaching the bottom of the grid loads the next page. expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument(); await waitFor(() => { io.scrollToEnd(); - expect(listAlbumsByYear).toHaveBeenLastCalledWith(1995, 2, 2); + expect(fetchNextPage).toHaveBeenCalled(); }); - - expect(await screen.findByText('Three')).toBeInTheDocument(); - expect(screen.getByText('One')).toBeInTheDocument(); - expect(await screen.findByText('End of year')).toBeInTheDocument(); }); - test('a failed drill-down offers a retry', async () => { + test('the last page says the list has ended', () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear).mockRejectedValue(new Error('nope')); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3), page([album('a3', 'Three')], 3, 2)] + }) + ); render(YearsPage); - expect(await screen.findByText(/Couldn't load albums for 1995/i)).toBeInTheDocument(); + // Pages are appended, not replaced. + expect(screen.getByText('One')).toBeInTheDocument(); + expect(screen.getByText('Three')).toBeInTheDocument(); + expect(screen.getByText('End of year')).toBeInTheDocument(); + }); + + test('a failed drill-down offers a retry rather than an empty grid', async () => { + pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); + asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); + const refetch = vi.fn(); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue(mockInfiniteQuery({ isError: true, refetch })); + render(YearsPage); + + expect(screen.getByText(/Couldn't load albums for 1995/i)).toBeInTheDocument(); + await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); + expect(refetch).toHaveBeenCalled(); }); // A failed later page keeps what is shown and offers a retry at the end, @@ -192,21 +205,23 @@ describe('/library/years drill-down', () => { test('a failed later page keeps the albums and offers Try again', async () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear) - .mockResolvedValueOnce({ items: [album('a1', 'One'), album('a2', 'Two')], total: 3, limit: 2, offset: 0 }) - .mockRejectedValueOnce(new Error('nope')) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + const fetchNextPage = vi.fn(); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + isError: true, + hasNextPage: true, + isFetchNextPageError: true, + fetchNextPage + }) + ); render(YearsPage); - await screen.findByText('One'); - await waitFor(() => { - io.scrollToEnd(); - expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); - }); + expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.queryByText(/Couldn't load albums for 1995/i)).not.toBeInTheDocument(); await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); - expect(await screen.findByText('Three')).toBeInTheDocument(); + expect(fetchNextPage).toHaveBeenCalled(); }); }); diff --git a/web/src/routes/login/+page.svelte b/web/src/routes/login/+page.svelte index 270652af..a9af457a 100644 --- a/web/src/routes/login/+page.svelte +++ b/web/src/routes/login/+page.svelte @@ -1,5 +1,5 @@ - -{pageTitle('Requests')} - - - -
    -
    -

    - Your requests -

    -

    - What you've asked Minstrel to add to the library. -

    -
    - - {#if query.isError} - - {:else if query.isPending} -

    Reading the ledger…

    - {:else if requests.length === 0} -

    Nothing requested yet.

    - {:else} -
      - {#each requests as r (r.id)} - {@const href = listenHref(r)} - - {#snippet details()} - {#if r.status === 'rejected' && r.notes} -
      - {r.notes} -
      - {/if} - {/snippet} - {#snippet actions()} - {#if r.status === 'pending'} - - {:else if r.status === 'completed' && href} - - Listen - - {/if} - {/snippet} -
      - {/each} -
    - {/if} -
    diff --git a/web/src/routes/requests/requests.test.ts b/web/src/routes/requests/requests.test.ts deleted file mode 100644 index 8dc11509..00000000 --- a/web/src/routes/requests/requests.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; -import { mockQuery } from '../../test-utils/query'; -import { apiClientMock } from '../../test-utils/mocks/client'; -import type { MusicRequest } from '#lib/api/types.js'; -import { pageUrlModule } from '../../test-utils/mocks/appState'; - -// $app/state / $app/navigation must be mocked or rendering the page -// pulls in SvelteKit's client runtime (`notifiable_store is not a -// function`) at module load. Same pattern as the other route tests. -const pageState = vi.hoisted(() => ({ - pageUrl: new URL('http://localhost/requests') -})); -vi.mock('$app/state', () => pageUrlModule(pageState)); -vi.mock('$app/navigation', () => ({ goto: vi.fn() })); - -// Capture invalidateQueries on the mocked QueryClient so the cancel test can -// assert against the same instance the page consumed. Per-file mock OVERRIDES -// the vitest.setup default so assertions see this named spy. -const invalidateQueries = vi.fn().mockResolvedValue(undefined); -vi.mock('@tanstack/svelte-query', async (orig) => { - const actual = (await orig()) as Record; - return { ...actual, useQueryClient: () => ({ invalidateQueries }) }; -}); - -vi.mock('#lib/api/requests.js', () => ({ - createMyRequestsQuery: vi.fn(), - cancelRequest: vi.fn().mockResolvedValue({ id: 'r1' }) -})); - -vi.mock('#lib/api/queries.js', () => ({ - qk: { - myRequests: () => ['myRequests'] - } -})); - -vi.mock('#lib/api/client.js', () => apiClientMock()); - -import RequestsPage from './+page.svelte'; -import { createMyRequestsQuery, cancelRequest } from '#lib/api/requests.js'; -import { qk } from '#lib/api/queries.js'; - -const mockedCreateMyRequestsQuery = createMyRequestsQuery as ReturnType; -const mockedCancelRequest = cancelRequest as ReturnType; - -function req(over: Partial = {}): MusicRequest { - return { - id: 'r1', - user_id: 'u1', - status: 'pending', - kind: 'album', - artist_mbid: 'art-mbid', - album_mbid: 'al-mbid', - track_mbid: null, - artist_name: 'Boards of Canada', - album_title: 'Music Has The Right To Children', - track_title: null, - decided_at: null, - decided_by: null, - notes: null, - completed_at: null, - matched_track_id: null, - matched_album_id: null, - matched_artist_id: null, - requested_at: '2026-04-28T12:00:00Z', - updated_at: '2026-04-28T12:00:00Z', - imported_album_count: 0, - imported_track_count: 0, - ...over - }; -} - -afterEach(() => { - vi.clearAllMocks(); -}); - -describe('Requests page', () => { - test('renders one row per request from the API', () => { - const rows: MusicRequest[] = [ - req({ id: 'r1', kind: 'artist', artist_name: 'Boards of Canada' }), - req({ id: 'r2', kind: 'album', album_title: 'Geogaddi', status: 'completed' }), - req({ id: 'r3', kind: 'track', track_title: 'Roygbiv', status: 'rejected', notes: 'Already in library' }) - ]; - mockedCreateMyRequestsQuery.mockReturnValue(mockQuery({ data: rows })); - render(RequestsPage); - expect(screen.getAllByTestId('request-row')).toHaveLength(3); - expect(screen.getByText('Boards of Canada')).toBeInTheDocument(); - expect(screen.getByText('Geogaddi')).toBeInTheDocument(); - expect(screen.getByText('Roygbiv')).toBeInTheDocument(); - }); - - test('pending row exposes Cancel; clicking calls cancelRequest and invalidates myRequests', async () => { - const rows: MusicRequest[] = [ - req({ id: 'r-pending', status: 'pending', kind: 'album', album_title: 'Geogaddi' }) - ]; - mockedCreateMyRequestsQuery.mockReturnValue(mockQuery({ data: rows })); - render(RequestsPage); - const cancelBtn = screen.getByRole('button', { name: /cancel request for geogaddi/i }); - await fireEvent.click(cancelBtn); - await waitFor(() => { - expect(mockedCancelRequest).toHaveBeenCalledWith('r-pending'); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: qk.myRequests() }); - }); - }); - - test('completed row with matched_track_id renders Listen link to /tracks/', () => { - const rows: MusicRequest[] = [ - req({ - id: 'r-track', - status: 'completed', - kind: 'track', - track_title: 'Roygbiv', - matched_track_id: 'tr-9', - matched_album_id: 'al-9', - matched_artist_id: 'art-9' - }) - ]; - mockedCreateMyRequestsQuery.mockReturnValue(mockQuery({ data: rows })); - render(RequestsPage); - const link = screen.getByRole('link', { name: /listen to roygbiv/i }); - expect(link).toHaveAttribute('href', '/tracks/tr-9'); - }); - - test('completed row with only matched_album_id renders Listen link to /albums/', () => { - const rows: MusicRequest[] = [ - req({ - id: 'r-album', - status: 'completed', - kind: 'album', - album_title: 'Geogaddi', - matched_track_id: null, - matched_album_id: 'al-7', - matched_artist_id: 'art-7' - }) - ]; - mockedCreateMyRequestsQuery.mockReturnValue(mockQuery({ data: rows })); - render(RequestsPage); - const link = screen.getByRole('link', { name: /listen to geogaddi/i }); - expect(link).toHaveAttribute('href', '/albums/al-7'); - }); - - test('rejected row renders notes and hides Cancel and Listen', () => { - const rows: MusicRequest[] = [ - req({ - id: 'r-rej', - status: 'rejected', - kind: 'album', - album_title: 'Geogaddi', - notes: 'Already kept in the library.' - }) - ]; - mockedCreateMyRequestsQuery.mockReturnValue(mockQuery({ data: rows })); - render(RequestsPage); - expect(screen.getByTestId('rejection-notes')).toHaveTextContent('Already kept in the library.'); - expect(screen.queryByRole('button', { name: /cancel request/i })).not.toBeInTheDocument(); - expect(screen.queryByRole('link', { name: /listen to/i })).not.toBeInTheDocument(); - }); - - test('empty list shows the voice-rule "Nothing requested yet." copy', () => { - mockedCreateMyRequestsQuery.mockReturnValue(mockQuery({ data: [] })); - render(RequestsPage); - expect(screen.getByText(/nothing requested yet\./i)).toBeInTheDocument(); - expect(screen.queryAllByTestId('request-row')).toHaveLength(0); - }); -}); diff --git a/web/src/routes/reset-password/[token]/+page.svelte b/web/src/routes/reset-password/[token]/+page.svelte index 20475df0..f8b1c61e 100644 --- a/web/src/routes/reset-password/[token]/+page.svelte +++ b/web/src/routes/reset-password/[token]/+page.svelte @@ -1,4 +1,6 @@ {pageTitle('Search')} @@ -107,7 +102,7 @@
    {#each tracks.items as t, i (t.id)} - + {/each}
    diff --git a/web/src/routes/search/albums/albums.test.ts b/web/src/routes/search/albums/albums.test.ts index 340db6d9..c0187f3e 100644 --- a/web/src/routes/search/albums/albums.test.ts +++ b/web/src/routes/search/albums/albums.test.ts @@ -5,9 +5,9 @@ import { installIntersectionObserverMock } from '#test-utils/intersectionObserve import { emptyLikesMock } from '../../../test-utils/mocks/likes'; import { apiClientMock } from '../../../test-utils/mocks/client'; import { pageUrlModule } from '#test-utils/mocks/appState.js'; -import type { AlbumRef, Page } from '#lib/api/types.js'; +import type { AlbumRef } from '#lib/api/types.js'; -const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/albums?q=miles') })); +const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/albums?q=marlo') })); vi.mock('$app/state', () => pageUrlModule(state)); @@ -24,19 +24,17 @@ vi.mock('#lib/api/likes.js', () => emptyLikesMock()); import AlbumsOverflow from './+page.svelte'; import { createSearchAlbumsInfiniteQuery } from '#lib/api/queries.js'; +import { page } from '#test-utils/fixtures/page.js'; -function page(items: T[], total: number, offset = 0, limit = 50): Page { - return { items, total, offset, limit }; -} const album: AlbumRef = { - id: 'al1', title: 'Kind of Blue', sort_title: 'Kind of Blue', artist_id: 'a1', artist_name: 'Miles Davis', + id: 'al1', title: 'Kind of Grey', sort_title: 'Kind of Grey', artist_id: 'a1', artist_name: 'Marlo Davies', year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover', cover_art_source: null }; afterEach(() => { vi.clearAllMocks(); - state.pageUrl = new URL('http://localhost/search/albums?q=miles'); + state.pageUrl = new URL('http://localhost/search/albums?q=marlo'); }); describe('search albums overflow', () => { @@ -45,7 +43,7 @@ describe('search albums overflow', () => { mockInfiniteQuery({ pages: [page([album], 1)] }) ); render(AlbumsOverflow); - expect(screen.getByRole('link', { name: /Kind of Blue/ })).toHaveAttribute('href', '/albums/al1'); + expect(screen.getByRole('link', { name: /Kind of Grey/ })).toHaveAttribute('href', '/albums/al1'); }); // No button; reaching the end of the list loads the next page. diff --git a/web/src/routes/search/artists/artists.test.ts b/web/src/routes/search/artists/artists.test.ts index df123bb9..8c12a00a 100644 --- a/web/src/routes/search/artists/artists.test.ts +++ b/web/src/routes/search/artists/artists.test.ts @@ -4,9 +4,9 @@ import { mockInfiniteQuery } from '../../../test-utils/query'; import { installIntersectionObserverMock } from '#test-utils/intersectionObserver.js'; import { emptyLikesMock } from '../../../test-utils/mocks/likes'; import { pageUrlModule } from '#test-utils/mocks/appState.js'; -import type { ArtistRef, Page } from '#lib/api/types.js'; +import type { ArtistRef } from '#lib/api/types.js'; -const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/artists?q=miles') })); +const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/artists?q=marlo') })); vi.mock('$app/state', () => pageUrlModule(state)); @@ -18,26 +18,24 @@ vi.mock('#lib/api/likes.js', () => emptyLikesMock()); import ArtistsOverflow from './+page.svelte'; import { createSearchArtistsInfiniteQuery } from '#lib/api/queries.js'; +import { page } from '#test-utils/fixtures/page.js'; -function page(items: T[], total: number, offset = 0, limit = 50): Page { - return { items, total, offset, limit }; -} afterEach(() => { vi.clearAllMocks(); - state.pageUrl = new URL('http://localhost/search/artists?q=miles'); + state.pageUrl = new URL('http://localhost/search/artists?q=marlo'); }); describe('search artists overflow', () => { test('renders a row per artist', () => { - const a1: ArtistRef = { id: 'a1', name: 'Miles Davis', sort_name: 'Miles Davis', album_count: 12, cover_url: '' }; - const a2: ArtistRef = { id: 'a2', name: 'Miles Mosley', sort_name: 'Miles Mosley', album_count: 1, cover_url: '' }; + const a1: ArtistRef = { id: 'a1', name: 'Marlo Davies', sort_name: 'Marlo Davies', album_count: 12, cover_url: '' }; + const a2: ArtistRef = { id: 'a2', name: 'Marlo Mosby', sort_name: 'Marlo Mosby', album_count: 1, cover_url: '' }; (createSearchArtistsInfiniteQuery as ReturnType).mockReturnValue( mockInfiniteQuery({ pages: [page([a1, a2], 2)] }) ); render(ArtistsOverflow); - expect(screen.getByRole('link', { name: /Miles Davis/ })).toBeInTheDocument(); - expect(screen.getByRole('link', { name: /Miles Mosley/ })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /Marlo Davies/ })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /Marlo Mosby/ })).toBeInTheDocument(); }); // No button; reaching the end of the list loads the next page. diff --git a/web/src/routes/search/search.test.ts b/web/src/routes/search/search.test.ts index d500ebc8..9d1fc7d8 100644 --- a/web/src/routes/search/search.test.ts +++ b/web/src/routes/search/search.test.ts @@ -40,15 +40,15 @@ function emptyResp(): SearchResponse { }; } -const artist: ArtistRef = { id: 'a1', name: 'Miles Davis', sort_name: 'Miles Davis', album_count: 12, cover_url: '' }; +const artist: ArtistRef = { id: 'a1', name: 'Marlo Davies', sort_name: 'Marlo Davies', album_count: 12, cover_url: '' }; const album: AlbumRef = { - id: 'al1', title: 'Kind of Blue', sort_title: 'Kind of Blue', artist_id: 'a1', artist_name: 'Miles Davis', + id: 'al1', title: 'Kind of Grey', sort_title: 'Kind of Grey', artist_id: 'a1', artist_name: 'Marlo Davies', year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover', cover_art_source: null }; const track = makeTrack({ - title: 'So What', - album_id: 'al1', album_title: 'Kind of Blue', - artist_id: 'a1', artist_name: 'Miles Davis', + title: 'So Then', + album_id: 'al1', album_title: 'Kind of Grey', + artist_id: 'a1', artist_name: 'Marlo Davies', duration_sec: 545 }); @@ -66,7 +66,7 @@ describe('search page', () => { }); test('all three sections render when all three facets have items', () => { - state.pageUrl = new URL('http://localhost/search?q=miles'); + state.pageUrl = new URL('http://localhost/search?q=marlo'); const resp: SearchResponse = { ...emptyResp(), artists: { items: [artist], total: 1, limit: 10, offset: 0 }, @@ -81,7 +81,7 @@ describe('search page', () => { }); test('empty facets are hidden', () => { - state.pageUrl = new URL('http://localhost/search?q=miles'); + state.pageUrl = new URL('http://localhost/search?q=marlo'); const resp: SearchResponse = { ...emptyResp(), tracks: { items: [track], total: 1, limit: 10, offset: 0 } @@ -94,7 +94,7 @@ describe('search page', () => { }); test('"See all N →" link renders when total > items.length', () => { - state.pageUrl = new URL('http://localhost/search?q=miles'); + state.pageUrl = new URL('http://localhost/search?q=marlo'); const resp: SearchResponse = { ...emptyResp(), artists: { items: [artist], total: 47, limit: 10, offset: 0 } @@ -102,11 +102,11 @@ describe('search page', () => { (createSearchQuery as ReturnType).mockReturnValue(mockQuery({ data: resp })); render(SearchPage); const link = screen.getByRole('link', { name: /see all 47/i }); - expect(link).toHaveAttribute('href', '/search/artists?q=miles'); + expect(link).toHaveAttribute('href', '/search/artists?q=marlo'); }); test('"See all" link omitted when total === items.length', () => { - state.pageUrl = new URL('http://localhost/search?q=miles'); + state.pageUrl = new URL('http://localhost/search?q=marlo'); const resp: SearchResponse = { ...emptyResp(), tracks: { items: [track], total: 1, limit: 10, offset: 0 } @@ -127,7 +127,7 @@ describe('search page', () => { }); test('error state renders ApiErrorBanner', () => { - state.pageUrl = new URL('http://localhost/search?q=miles'); + state.pageUrl = new URL('http://localhost/search?q=marlo'); (createSearchQuery as ReturnType).mockReturnValue( mockQuery({ isError: true, error: { code: 'server_error', message: 'boom' } }) ); diff --git a/web/src/routes/search/tracks/+page.svelte b/web/src/routes/search/tracks/+page.svelte index 868eff1d..8ea67765 100644 --- a/web/src/routes/search/tracks/+page.svelte +++ b/web/src/routes/search/tracks/+page.svelte @@ -10,8 +10,7 @@ import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte'; import ListContinuation from '#lib/components/ListContinuation.svelte'; import { useDelayed } from '#lib/utils/useDelayed.svelte.js'; - import { playRadio } from '#lib/player/store.svelte.js'; - import type { TrackRef } from '#lib/api/types.js'; + import { radioFromRow } from '#lib/player/radioFromRow.js'; const q = $derived((page.url.searchParams.get('q') ?? '').trim()); const queryStore = $derived(q ? createSearchTracksInfiniteQuery(q) : null); @@ -20,10 +19,6 @@ const tracks = $derived(query?.data?.pages?.flatMap((p) => p.items) ?? []); const total = $derived(query?.data?.pages?.[0]?.total ?? 0); const showSkeleton = useDelayed(() => !!query?.isPending); - - function onTrackPlay(_tracks: TrackRef[], index: number) { - playRadio(_tracks[index].id); - } {pageTitle('Search · Tracks')} @@ -50,7 +45,7 @@ {:else} {#each tracks as t, i (t.id)} - + {/each} ({ pageUrl: new URL('http://localhost/search/tracks?q=miles') })); +const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/tracks?q=marlo') })); vi.mock('$app/state', () => pageUrlModule(state)); @@ -30,16 +30,14 @@ vi.mock('#lib/api/quarantine.js', () => emptyQuarantineMock()); import TracksOverflow from './+page.svelte'; import { createSearchTracksInfiniteQuery } from '#lib/api/queries.js'; import { playRadio } from '#lib/player/store.svelte.js'; +import { page } from '#test-utils/fixtures/page.js'; -function page(items: T[], total: number, offset = 0, limit = 50): Page { - return { items, total, offset, limit }; -} -const track = makeTrack({ title: 'So What' }); +const track = makeTrack({ title: 'So Then' }); afterEach(() => { vi.clearAllMocks(); - state.pageUrl = new URL('http://localhost/search/tracks?q=miles'); + state.pageUrl = new URL('http://localhost/search/tracks?q=marlo'); }); describe('search tracks overflow', () => { @@ -48,7 +46,7 @@ describe('search tracks overflow', () => { mockInfiniteQuery({ pages: [page([track], 1)] }) ); render(TracksOverflow); - expect(screen.getByRole('button', { name: 'So What' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'So Then' })).toBeInTheDocument(); }); test('clicking a track row triggers playRadio with the track id', async () => { @@ -56,7 +54,7 @@ describe('search tracks overflow', () => { mockInfiniteQuery({ pages: [page([track], 1)] }) ); render(TracksOverflow); - await fireEvent.click(screen.getByRole('button', { name: 'So What' })); + await fireEvent.click(screen.getByRole('button', { name: 'So Then' })); expect(playRadio).toHaveBeenCalledWith('t1'); }); diff --git a/web/src/routes/settings/+layout.svelte b/web/src/routes/settings/+layout.svelte index 62b51261..289a337f 100644 --- a/web/src/routes/settings/+layout.svelte +++ b/web/src/routes/settings/+layout.svelte @@ -1,4 +1,5 @@ -
    -

    Settings

    -
    -
    -
    - -
    -
    - -
    - {@render children?.()} -
    -
    -
    + + {#snippet rail()} + + {/snippet} + {@render children?.()} + diff --git a/web/src/routes/settings/account/+page.svelte b/web/src/routes/settings/account/+page.svelte index faba9ce1..b9e7853b 100644 --- a/web/src/routes/settings/account/+page.svelte +++ b/web/src/routes/settings/account/+page.svelte @@ -1,4 +1,6 @@