Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
740088fa0f
|
No files matched your search
@@ -1,8 +0,0 @@
|
||||
.git
|
||||
.github
|
||||
.gitignore
|
||||
.golangci.yml
|
||||
*testdata*
|
||||
*_test.go
|
||||
*.db
|
||||
README.md
|
||||
@@ -1 +0,0 @@
|
||||
github: [sentriz]
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
name: bug or issue
|
||||
about: report a new bug or issue
|
||||
title: ""
|
||||
labels: ""
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
<!-- please fill these out: -->
|
||||
|
||||
gonic version:
|
||||
|
||||
if from docker, docker tag:
|
||||
if from source, git tag/branch:
|
||||
|
||||
<!-- bug or issue: -->
|
||||
@@ -1,18 +0,0 @@
|
||||
version: 2
|
||||
multi-ecosystem-groups:
|
||||
all:
|
||||
schedule:
|
||||
interval: weekly
|
||||
updates:
|
||||
- package-ecosystem: docker
|
||||
directory: /
|
||||
multi-ecosystem-group: all
|
||||
patterns: ["*"]
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
multi-ecosystem-group: all
|
||||
patterns: ["*"]
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
multi-ecosystem-group: all
|
||||
patterns: ["*"]
|
||||
|
Before Width: | Height: | Size: 237 KiB |
|
Before Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 22 KiB |
@@ -1,81 +0,0 @@
|
||||
name: Nightly Release
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
custom_tag:
|
||||
description: 'Custom tag (optional, will use "nightly" if not provided)'
|
||||
required: false
|
||||
type: string
|
||||
jobs:
|
||||
check-date:
|
||||
runs-on: ubuntu-latest
|
||||
name: Check latest commit
|
||||
outputs:
|
||||
should_run: ${{ steps.check.outputs.should_run }}
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- id: check
|
||||
run: |
|
||||
test -n "$(git rev-list --after="24 hours" ${{ github.sha }})" \
|
||||
&& echo "should_run=true" >>$GITHUB_OUTPUT \
|
||||
|| echo "should_run=false" >>$GITHUB_OUTPUT
|
||||
test:
|
||||
name: Lint and test
|
||||
needs: check-date
|
||||
if: ${{ needs.check-date.outputs.should_run == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: Lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
install-mode: goinstall
|
||||
version: v2.6.1
|
||||
- name: Test
|
||||
run: go test ./...
|
||||
build-docker:
|
||||
name: Build and release Docker image
|
||||
needs: [check-date, test]
|
||||
if: ${{ needs.check-date.outputs.should_run == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
with:
|
||||
install: true
|
||||
version: latest
|
||||
driver-opts: image=moby/buildkit:master
|
||||
- name: Login into DockerHub
|
||||
run: echo ${{ secrets.DOCKERHUB_TOKEN }} | docker login -u ${{ secrets.DOCKERHUB_USERNAME }} --password-stdin
|
||||
- name: Login into GitHub Container Registry
|
||||
run: echo ${{ secrets.CR_PAT }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin
|
||||
- name: Generate short hash and set tag
|
||||
run: |
|
||||
_short_hash=${{ github.sha }}
|
||||
echo "SHORT_HASH=${_short_hash:0:7}" >> $GITHUB_ENV
|
||||
if [ -n "${{ github.event.inputs.custom_tag }}" ]; then
|
||||
echo "TAG_NAME=${{ github.event.inputs.custom_tag }}" >> $GITHUB_ENV
|
||||
else
|
||||
echo "TAG_NAME=nightly" >> $GITHUB_ENV
|
||||
fi
|
||||
- name: Build and Push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7
|
||||
push: true
|
||||
tags: |
|
||||
ghcr.io/${{ github.repository }}:${{ env.SHORT_HASH }}
|
||||
ghcr.io/${{ github.repository }}:${{ env.TAG_NAME }}
|
||||
${{ github.repository }}:${{ env.SHORT_HASH }}
|
||||
${{ github.repository }}:${{ env.TAG_NAME }}
|
||||
@@ -1,120 +0,0 @@
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
jobs:
|
||||
test:
|
||||
name: Lint and test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: Lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
install-mode: goinstall
|
||||
version: v2.6.1
|
||||
- name: Test
|
||||
run: go test ./...
|
||||
release-please:
|
||||
name: Run Release Please
|
||||
runs-on: ubuntu-latest
|
||||
needs: [test]
|
||||
outputs:
|
||||
release_created: ${{ steps.release.outputs.release_created }}
|
||||
tag_name: ${{ steps.release.outputs.tag_name }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Setup Release Please
|
||||
uses: google-github-actions/release-please-action@v2
|
||||
id: release
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
release-type: simple
|
||||
changelog-path: CHANGELOG.md
|
||||
package-name: gonic
|
||||
build-binaries:
|
||||
name: Build binaries
|
||||
runs-on: ubuntu-latest
|
||||
needs: [release-please]
|
||||
if: ${{ needs.release-please.outputs.release_created }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [linux, windows, darwin]
|
||||
arch: [amd64, arm64, 386]
|
||||
exclude:
|
||||
- os: darwin
|
||||
arch: 386
|
||||
# https://github.com/natefinch/npipe/issues/33 (required by mpvipc)
|
||||
- os: windows
|
||||
arch: arm64
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: Build
|
||||
run: |
|
||||
set -e
|
||||
CGO_ENABLED=0 GOOS="${{ matrix.os }}" GOARCH="${{ matrix.arch }}" go build -o out/ ./cmd/...
|
||||
[[ "${{ matrix.os }}" = "windows" ]] && suff=".exe"
|
||||
cd out/
|
||||
for p in *; do
|
||||
mv "$p" "${p%.*}-${{ matrix.os }}-${{ matrix.arch }}-${{ needs.release-please.outputs.tag_name }}$suff"
|
||||
done
|
||||
cd -
|
||||
- name: Upload
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.CR_PAT }}
|
||||
file: out/*
|
||||
file_glob: true
|
||||
tag: ${{ needs.release-please.outputs.tag_name }}
|
||||
build-docker:
|
||||
name: Build, tag, and publish Docker image
|
||||
runs-on: ubuntu-latest
|
||||
needs: [release-please]
|
||||
if: ${{ needs.release-please.outputs.release_created }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
- name: Login into DockerHub
|
||||
run: echo ${{ secrets.DOCKERHUB_TOKEN }} | docker login -u ${{ secrets.DOCKERHUB_USERNAME }} --password-stdin
|
||||
- name: Login into GitHub Container Registry
|
||||
run: echo ${{ secrets.CR_PAT }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin
|
||||
- name: Build and Push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7
|
||||
push: true
|
||||
tags: |
|
||||
ghcr.io/${{ github.repository }}:${{ needs.release-please.outputs.tag_name }}
|
||||
ghcr.io/${{ github.repository }}:latest
|
||||
${{ github.repository }}:${{ needs.release-please.outputs.tag_name }}
|
||||
${{ github.repository }}:latest
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
notify-irc:
|
||||
needs: [release-please]
|
||||
name: Notify IRC
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Notify
|
||||
run: |
|
||||
set +x e
|
||||
git log -1 --pretty="push to master (@%an) %s" | curl "${{ secrets.IRC_NOTIFY_URL }}" -F target=#gonic -F message=@- >/dev/null 2>&1
|
||||
exit 0
|
||||
@@ -1,24 +0,0 @@
|
||||
name: Lint and test
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
pull_request:
|
||||
jobs:
|
||||
test:
|
||||
name: Lint and test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: Lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
install-mode: goinstall
|
||||
version: v2.6.1
|
||||
- name: Test
|
||||
run: go test ./...
|
||||
@@ -1,18 +1,41 @@
|
||||
*.db
|
||||
*.db.*.bak
|
||||
*db-wal
|
||||
*db-shm
|
||||
*.sql
|
||||
*_bytes.go
|
||||
_test*
|
||||
dist
|
||||
*.sql
|
||||
./gonic
|
||||
.devcontainer
|
||||
.vscode
|
||||
*.swp
|
||||
.tags*
|
||||
*.test
|
||||
.env
|
||||
config
|
||||
genre-tree
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
@@ -1,106 +0,0 @@
|
||||
version: "2"
|
||||
linters:
|
||||
default: none
|
||||
enable:
|
||||
- asasalint
|
||||
- asciicheck
|
||||
- bidichk
|
||||
- bodyclose
|
||||
- containedctx
|
||||
- decorder
|
||||
- dogsled
|
||||
- dupword
|
||||
- durationcheck
|
||||
- errcheck
|
||||
- errchkjson
|
||||
- errname
|
||||
- errorlint
|
||||
- forbidigo
|
||||
- ginkgolinter
|
||||
- gocheckcompilerdirectives
|
||||
- gochecknoglobals
|
||||
- gochecknoinits
|
||||
- goconst
|
||||
- gocritic
|
||||
- gocyclo
|
||||
- goheader
|
||||
- gomodguard
|
||||
- goprintffuncname
|
||||
- gosec
|
||||
- gosmopolitan
|
||||
- govet
|
||||
- grouper
|
||||
- importas
|
||||
- ineffassign
|
||||
- loggercheck
|
||||
- makezero
|
||||
- mirror
|
||||
- misspell
|
||||
- nakedret
|
||||
- nestif
|
||||
- nilerr
|
||||
- nosprintfhostport
|
||||
- paralleltest
|
||||
- predeclared
|
||||
- promlinter
|
||||
- reassign
|
||||
- rowserrcheck
|
||||
- sqlclosecheck
|
||||
- staticcheck
|
||||
- testableexamples
|
||||
- thelper
|
||||
- tparallel
|
||||
- unconvert
|
||||
- unparam
|
||||
- unused
|
||||
- wastedassign
|
||||
- whitespace
|
||||
- zerologlint
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- common-false-positives
|
||||
- legacy
|
||||
- std-error-handling
|
||||
rules:
|
||||
- linters:
|
||||
- errcheck
|
||||
- gochecknoglobals
|
||||
path: _test\.go
|
||||
- linters:
|
||||
- gosec
|
||||
text: weak cryptographic primitive
|
||||
- linters:
|
||||
- gosec
|
||||
text: weak random number generator
|
||||
- linters:
|
||||
- gosec
|
||||
text: integer overflow conversion
|
||||
- linters:
|
||||
- staticcheck
|
||||
text: at least one file in a package should have a package comment
|
||||
- linters:
|
||||
- gocritic
|
||||
text: should rewrite switch
|
||||
paths:
|
||||
- server/assets
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
settings:
|
||||
staticcheck:
|
||||
checks:
|
||||
- all
|
||||
- "-QF1001"
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- goimports
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- server/assets
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
@@ -1,486 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
### [0.20.1](https://www.github.com/sentriz/gonic/compare/v0.20.0...v0.20.1) (2026-01-30)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **playlist:** fix regression in playlist ID handling ([103a048](https://www.github.com/sentriz/gonic/commit/103a048e8497597be9b930ea9ef6d57ca755c0eb)), closes [#655](https://www.github.com/sentriz/gonic/issues/655)
|
||||
|
||||
## [0.20.0](https://www.github.com/sentriz/gonic/compare/v0.19.0...v0.20.0) (2026-01-22)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for playlist cover art on filesystem ([aad729e](https://www.github.com/sentriz/gonic/commit/aad729e3ea79a0a542496802c815851d8e0f702a)), closes [#650](https://www.github.com/sentriz/gonic/issues/650)
|
||||
* **ci:** bump golangci-lint ([79e3898](https://www.github.com/sentriz/gonic/commit/79e3898c3b47d4b3120265fa9aa6ddc22d2fbe7c))
|
||||
* **db:** add an index on albums.created_at ([816e437](https://www.github.com/sentriz/gonic/commit/816e437d44b2feb40f82e8d589e3d17c0bf87b0c)), closes [#620](https://www.github.com/sentriz/gonic/issues/620)
|
||||
* **gonic:** add log-db option to log queries ([75a0918](https://www.github.com/sentriz/gonic/commit/75a0918a7ef8bb6c9506de69dd4e6b6e8c35e567)), closes [#620](https://www.github.com/sentriz/gonic/issues/620)
|
||||
* **scanner:** read multi valued release types ([c752a22](https://www.github.com/sentriz/gonic/commit/c752a22808527a034531418263662261fe83f9d4))
|
||||
* **subsonic:** allow non admins to download podcast episodes ([c2ebe96](https://www.github.com/sentriz/gonic/commit/c2ebe9631300b54f60bf3fd12a4eae526a84d3de)), closes [#623](https://www.github.com/sentriz/gonic/issues/623)
|
||||
* **subsonic:** implement getSimilarSongs for artists and albums ([#649](https://www.github.com/sentriz/gonic/issues/649)) ([db9aa2b](https://www.github.com/sentriz/gonic/commit/db9aa2b2e37903e8cce770d76bed6e568570599e))
|
||||
* **subsonic:** return disc titles ([0377bfa](https://www.github.com/sentriz/gonic/commit/0377bfa696e7f5dc02497bd49b96cebeefd7ef2f))
|
||||
* **taglib:** add `.ape` as a supported filetype ([82642eb](https://www.github.com/sentriz/gonic/commit/82642eb1ca4b9587fe1764bf7efe8bbb2cb28e42)), closes [#615](https://www.github.com/sentriz/gonic/issues/615)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **db:** enable WAL also for Wasm driver ([b67c1c1](https://www.github.com/sentriz/gonic/commit/b67c1c14d2b883f634f7aaecc0367a15ec7dab71)), closes [#620](https://www.github.com/sentriz/gonic/issues/620)
|
||||
* **db:** use separate DSN for both drivers ([4696499](https://www.github.com/sentriz/gonic/commit/469649935e26ef279a4a805cd964d3b010aa8146))
|
||||
* **gonic:** correct typo in command line help ([#640](https://www.github.com/sentriz/gonic/issues/640)) ([99e2ccf](https://www.github.com/sentriz/gonic/commit/99e2ccfb0f7ce038669fef2f9ff281da4174fee6))
|
||||
* **podcast:** truncate filenames longer than 200 chars ([e12ab54](https://www.github.com/sentriz/gonic/commit/e12ab544c21f286ead3c84ead113be6658cef318)), closes [#624](https://www.github.com/sentriz/gonic/issues/624)
|
||||
* **podcast:** validate response status code when fetching podcast audio ([2900ce5](https://www.github.com/sentriz/gonic/commit/2900ce51024e5dafdf23ca0c5a6280bd3bd48059)), closes [#639](https://www.github.com/sentriz/gonic/issues/639)
|
||||
* **scanner:** clear metadata of albums who no longer have tracks ([ca59601](https://www.github.com/sentriz/gonic/commit/ca59601484371d41564f84e33af62642df6de3e5)), closes [#638](https://www.github.com/sentriz/gonic/issues/638)
|
||||
* **scanner:** reset embedded cover for album when toggling `scan-embedded-cover` ([ea5e625](https://www.github.com/sentriz/gonic/commit/ea5e6252a175c6dea688c2910f7cb270b60b1c27)), closes [#619](https://www.github.com/sentriz/gonic/issues/619)
|
||||
* **subsonic:** correct spec typos ([04ff7f3](https://www.github.com/sentriz/gonic/commit/04ff7f3c331445abbbcf6a64465aa523c1775386)), closes [#653](https://www.github.com/sentriz/gonic/issues/653)
|
||||
|
||||
## [0.19.0](https://www.github.com/sentriz/gonic/compare/v0.18.0...v0.19.0) (2025-10-11)
|
||||
|
||||
This release uses WebAssesmby for the [tagging](https://github.com/sentriz/go-taglib) and [database](https://github.com/ncruces/go-sqlite3) backends. This means that gonic no longer requires Cgo or external dependencies to build. As a result, static binaries will be available in the releases page, and Docker images for more architectures. Performance of scanning and tagging should also be improved.
|
||||
|
||||
### Features
|
||||
|
||||
* **build:** add Cgo free database ([505f7d8](https://www.github.com/sentriz/gonic/commit/505f7d8ae6116c5dc1cfa50a5caba6333672be20))
|
||||
* **build:** add Cgo free tagging backend ([7802e20](https://www.github.com/sentriz/gonic/commit/7802e20e7214e1912fc84bb29c877984b99913c9))
|
||||
* **ci:** merge nightly and debug workflows ([ca85eed](https://www.github.com/sentriz/gonic/commit/ca85eed4c156c5370c1e3e4c7fbc31d4c1811f57))
|
||||
* **ci:** remove Cgo dependencies, cross compile without QEMU, upload static binaries ([e3db819](https://www.github.com/sentriz/gonic/commit/e3db819d8fd5ae14332c56ab7cebc01d46a6c76b))
|
||||
* **ffprobe:** add more supported file types ([8e7820a](https://www.github.com/sentriz/gonic/commit/8e7820a72e2360e3b5808299123fd5a686c084e8))
|
||||
* **gonic:** add `scan-embedded-cover-enabled` flag ([c69cb8c](https://www.github.com/sentriz/gonic/commit/c69cb8cf35203c6db15d3c1bd68a86cb91108b40))
|
||||
* **gonic:** use wrtag/normtag for nag normalisation ([aba758f](https://www.github.com/sentriz/gonic/commit/aba758f2ba6e6d20887a36a0cba80127c2b110a9))
|
||||
* **subsonic:** also read unsynced lyrics from .txt files and tag metadata ([eb0d8fd](https://www.github.com/sentriz/gonic/commit/eb0d8fd1c710bf0367348873858662c39515b676)), closes [#593](https://www.github.com/sentriz/gonic/issues/593)
|
||||
* **subsonic:** keep original cover file format when caching ([#609](https://www.github.com/sentriz/gonic/issues/609)) ([1af4ce3](https://www.github.com/sentriz/gonic/commit/1af4ce35873ff17dc6331e0d7c0e0385213b53b3)), closes [#11](https://www.github.com/sentriz/gonic/issues/11)
|
||||
* **subsonic:** return genres for getAlbumListTwo2 ([3909e9b](https://www.github.com/sentriz/gonic/commit/3909e9b5bdbc3deb1b5f48ff6f04b3d865a1b1bc)), closes [#605](https://www.github.com/sentriz/gonic/issues/605)
|
||||
* **subsonic:** support embedded cover art ([ec7cffd](https://www.github.com/sentriz/gonic/commit/ec7cffdd57f235adce93b7faf1998fdc9a164c52)), closes [#11](https://www.github.com/sentriz/gonic/issues/11) [#556](https://www.github.com/sentriz/gonic/issues/556)
|
||||
* **subsonic:** support embedded track level cover art ([d66814b](https://www.github.com/sentriz/gonic/commit/d66814bfd1d39ba92c6c368c0006052451675454)), closes [#11](https://www.github.com/sentriz/gonic/issues/11)
|
||||
* **tags:** add ffprobe reader ([3a9c03a](https://www.github.com/sentriz/gonic/commit/3a9c03ac88b6e6476206a87e3703e247c965e7c9))
|
||||
* **tags:** add Properties.HasCover ([bc0b6c0](https://www.github.com/sentriz/gonic/commit/bc0b6c0da4738c3ee8f40525e2ed1d85c51f927a))
|
||||
* **tags:** add ReadCover interface method ([e413bc3](https://www.github.com/sentriz/gonic/commit/e413bc35ded9463b245ff913fb2d90ee80ea3184))
|
||||
|
||||
### ⚠ Note to package maintainers
|
||||
|
||||
- The `sqlite-dev` and `libtag-dev` (or your distro's equivalents) packages are **no longer required**; please remove them from package dependencies.
|
||||
- Build with `CGO_ENABLED=0` to produce static binaries.
|
||||
|
||||
gonic now vendors reproducible WebAssembly backends for TagLib and SQLite, eliminating Cgo and external system libraries. Builds are fully static, cross-compiling is straightforward, and supply-chain verification is easier.
|
||||
|
||||
Verify the vendored WASM artifacts using Artifact Attestations:
|
||||
- <https://github.com/sentriz/go-taglib/raw/refs/tags/v0.10.4/taglib.wasm> ([Attestations](https://github.com/sentriz/go-taglib/attestations/11402786))
|
||||
- <https://github.com/ncruces/go-sqlite3/raw/refs/tags/v0.29.1/embed/sqlite3.wasm> ([Attestations](https://github.com/ncruces/go-sqlite3/attestations/11344814))
|
||||
|
||||
Example build pipeline:
|
||||
```console
|
||||
$ git clone https://github.com/sentriz/gonic
|
||||
$ cd gonic
|
||||
|
||||
$ sha256sum "$(go list -m -f '{{.Dir}}' go.senan.xyz/taglib)/taglib.wasm"
|
||||
# expected ca5ce04b35f1e6cad8b8d9f00906a4c108ccd004b56e713db5ce69aa69b3805d (https://github.com/sentriz/go-taglib/attestations/11402786)
|
||||
|
||||
$ sha256sum "$(go list -m -f '{{.Dir}}' github.com/ncruces/go-sqlite3)/embed/sqlite3.wasm"
|
||||
# expected 117262b6241d8de78ba564a44383fa1562e52f1a978de269e20a02b3c06c02e3 (https://github.com/ncruces/go-sqlite3/attestations/11344814)
|
||||
|
||||
$ CGO_ENABLED=0 go build ./cmd/gonic/.
|
||||
```
|
||||
|
||||
Opting out of WebAssembly:
|
||||
|
||||
- If you prefer not to use the WebAssembly binaries, you can build with `nowasm`:
|
||||
|
||||
```console
|
||||
$ go build -tags nowasm ./cmd/gonic/.
|
||||
```
|
||||
|
||||
- This mode is not supported, and tagging/scan performance will degrade.
|
||||
- Cgo will be used for sqlite, so sqlite-dev is still required.
|
||||
- `ffprobe` will be used for tagging, so that must be available in `$PATH`. `libtag-dev` is still not used in this mode.
|
||||
|
||||
## [0.18.0](https://www.github.com/sentriz/gonic/compare/v0.17.0...v0.18.0) (2025-09-18)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **deps:** bump to go1.25
|
||||
|
||||
### Features
|
||||
|
||||
* **docker:** use alpine native taglib ([c9f4181](https://www.github.com/sentriz/gonic/commit/c9f41810af76d6a49c40af274b001f2b5b1d155d))
|
||||
* **readme:** document comma escaping in readme ([eaa82b0](https://www.github.com/sentriz/gonic/commit/eaa82b00e55dc56dd5f1b7683769c2f30dadcc63)), closes [#596](https://www.github.com/sentriz/gonic/issues/596)
|
||||
* **subsonic:** add support for lyrics ([#519](https://www.github.com/sentriz/gonic/issues/519)) ([db97bc7](https://www.github.com/sentriz/gonic/commit/db97bc753e1070de12b3907b2b996511140a3259))
|
||||
* **subsonic:** better support for internet radio and podcast episodes in jukebox ([3db183b](https://www.github.com/sentriz/gonic/commit/3db183bda4b9feda1adf7f4f67218d36eff61a49)), closes [#572](https://www.github.com/sentriz/gonic/issues/572)
|
||||
* **subsonic:** replace html2text with bluemonday ([5916a7f](https://www.github.com/sentriz/gonic/commit/5916a7fe7bc7ac39ca1975665433da627d214769)), closes [#591](https://www.github.com/sentriz/gonic/issues/591)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **subsonic:** restore disc/track ordering in getMusicDirectory ([8ac8779](https://www.github.com/sentriz/gonic/commit/8ac8779b92ec9c969bf6a26b26454a1c9e49748a)), closes [#597](https://www.github.com/sentriz/gonic/issues/597)
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* **deps:** bump to go1.25 ([1bf4a5b](https://www.github.com/sentriz/gonic/commit/1bf4a5b0c1e209770b060c8b4a08910afb72078f)), closes [#594](https://www.github.com/sentriz/gonic/issues/594)
|
||||
|
||||
## [0.17.0](https://www.github.com/sentriz/gonic/compare/v0.16.4...v0.17.0) (2025-08-21)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **db:** add a covering index on tracks (album_id, length) ([018343d](https://www.github.com/sentriz/gonic/commit/018343dc32fd89685ca3eb80ceb3116615a6cbec)), closes [#508](https://www.github.com/sentriz/gonic/issues/508)
|
||||
* **lastfm:** paginate loved tracks ([5c7d065](https://www.github.com/sentriz/gonic/commit/5c7d065fd7513f66604d78409859c4028ca9ad70))
|
||||
* **playlist:** assume playlists in the root dir without a user dir belong to admin ([#499](https://www.github.com/sentriz/gonic/issues/499)) ([f5893ea](https://www.github.com/sentriz/gonic/commit/f5893ea5ea4d47a82212b47e85a15d9defdc5eff))
|
||||
* **podcast:** download most recent episode when switching to download recent mode ([c222ecb](https://www.github.com/sentriz/gonic/commit/c222ecb45cec5282e0ef892db21eb32632a0145d)), closes [#557](https://www.github.com/sentriz/gonic/issues/557)
|
||||
* **podcast:** use podcast author if episode author is not defined ([#574](https://www.github.com/sentriz/gonic/issues/574)) ([19b707c](https://www.github.com/sentriz/gonic/commit/19b707c5d4081242825704eed764c257e6161865))
|
||||
* **scanner:** cleanup bookmarks on scan ([#583](https://www.github.com/sentriz/gonic/issues/583)) ([b8dfe14](https://www.github.com/sentriz/gonic/commit/b8dfe1449e1f9ee93193b32b1e9d3e233e23706d))
|
||||
* **scanner:** support full scan cleanups in watcher ([#496](https://www.github.com/sentriz/gonic/issues/496)) ([93ce039](https://www.github.com/sentriz/gonic/commit/93ce039963821dbfa0acec6ee9c92134ff479fcc))
|
||||
* **scanner:** use wrtag/coverparse for cover selection ([453639e](https://www.github.com/sentriz/gonic/commit/453639ee34da28dc47f64865d490445968c23ce8)), closes [#338](https://www.github.com/sentriz/gonic/issues/338) [#516](https://www.github.com/sentriz/gonic/issues/516)
|
||||
* **subsonic:** allow search albums with MBID ([7b19101](https://www.github.com/sentriz/gonic/commit/7b19101a34702bdeaeacf57dbc3db9226f0169f3))
|
||||
* **subsonic:** allow search with MBID ([#579](https://www.github.com/sentriz/gonic/issues/579)) ([2d4111d](https://www.github.com/sentriz/gonic/commit/2d4111dfc5226e99fe9fee23e415806960ea7a5c))
|
||||
* **subsonic:** bump image cache expiration ([bbe16b7](https://www.github.com/sentriz/gonic/commit/bbe16b7555f1d7300f829171f73c8308ae506fd3))
|
||||
* **subsonic:** expose album `isCompilation` and `releaseTypes` ([29b7549](https://www.github.com/sentriz/gonic/commit/29b754973db9106bf1061a7aadb2b9b93b1fbf17))
|
||||
* **subsonic:** expose replaygain tags ([0e45f5e](https://www.github.com/sentriz/gonic/commit/0e45f5e84cd650211351179edf3eed89a54c6c75))
|
||||
* **subsonic:** fallback to filename when title is missing tags ([58d54c2](https://www.github.com/sentriz/gonic/commit/58d54c287cb6711959707b50207ea700df25d1cf)), closes [#541](https://www.github.com/sentriz/gonic/issues/541)
|
||||
* **subsonic:** support more podcast metadata and podcast bookmarks ([#569](https://www.github.com/sentriz/gonic/issues/569)) ([63a420d](https://www.github.com/sentriz/gonic/commit/63a420d2d32b006a92b3aa5d97bc39ad49fc8155))
|
||||
* **transcode:** add cache pruning and config options ([bcb613c](https://www.github.com/sentriz/gonic/commit/bcb613c79c6a822adeafc802f19b7626bfb64009))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **admin:** better handing of resolve proxy path escaping ([7b21e82](https://www.github.com/sentriz/gonic/commit/7b21e82aaf511d36300fd9cf2dae32a1196a4f77)), closes [#493](https://www.github.com/sentriz/gonic/issues/493)
|
||||
* **adminui:** resolve reverse proxy paths for fonts ([718686a](https://www.github.com/sentriz/gonic/commit/718686a93a4341c5b5ccb113a0ed7ae95c0524b4)), closes [#543](https://www.github.com/sentriz/gonic/issues/543)
|
||||
* **ci:** bump golangci-lint ([640d872](https://www.github.com/sentriz/gonic/commit/640d872f4c66d21b760590ae9413cc5b63b53cb6))
|
||||
* **ci:** ignore gosec integer overflow conversion ([120fd79](https://www.github.com/sentriz/gonic/commit/120fd7959a8e360fdccc6bd1a47e8cc7ebdbb0d4))
|
||||
* **ci:** update .golangci.yml exclude config ([e5f7ef3](https://www.github.com/sentriz/gonic/commit/e5f7ef3c86d6a52709336f2dd2d428203e7d9472))
|
||||
* **ci:** use new sqlite package name ([1c23771](https://www.github.com/sentriz/gonic/commit/1c2377189da75c78831955953f25dd09b3cb7bb2))
|
||||
* **dockerfile:** install abuild key ([#526](https://www.github.com/sentriz/gonic/issues/526)) ([fb36dbf](https://www.github.com/sentriz/gonic/commit/fb36dbf71991424879be85950ab508bcdf653902))
|
||||
* **playlist:** fix non-admin users not being able to create playlists ([#524](https://www.github.com/sentriz/gonic/issues/524)) ([ac798ac](https://www.github.com/sentriz/gonic/commit/ac798ac2d2cdf936b653577d9acd4b7d1e22ecaf))
|
||||
* **podcast:** gracefully handle no podcast cover URL ([#547](https://www.github.com/sentriz/gonic/issues/547)) ([aef5f92](https://www.github.com/sentriz/gonic/commit/aef5f920d24c57bc5b652891409926ff98458aa0))
|
||||
* **subsonic:** gracefully handle missing playqueue items ([3fc9d5d](https://www.github.com/sentriz/gonic/commit/3fc9d5dcb5af0db8286d7be7c895726cf9b437cc))
|
||||
* **subsonic:** order some browse-by-tag responses ([39df00e](https://www.github.com/sentriz/gonic/commit/39df00ef8f683a846efd0da7480c3db6d928d2c4)), closes [#512](https://www.github.com/sentriz/gonic/issues/512)
|
||||
* **subsonic:** populate ArtistID and AlbumID for playlists ([#567](https://www.github.com/sentriz/gonic/issues/567)) ([c6d8751](https://www.github.com/sentriz/gonic/commit/c6d87515c6702c3ca22fef6ba1420ffc00eeaa77))
|
||||
* **subsonic:** skip bookmarks for missing items instead of failing ([#580](https://www.github.com/sentriz/gonic/issues/580)) ([e3dc188](https://www.github.com/sentriz/gonic/commit/e3dc1887730cb019a91e74ad8a133a31839dbf56))
|
||||
* **taglib:** support lower case filenames again ([8a0fa05](https://www.github.com/sentriz/gonic/commit/8a0fa05c7cdcb98066c263fea72af0715864bea5)), closes [#491](https://www.github.com/sentriz/gonic/issues/491)
|
||||
|
||||
### [0.16.4](https://www.github.com/sentriz/gonic/compare/v0.16.3...v0.16.4) (2024-03-20)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* support internet radio stations for jukebox ([62d49a3](https://www.github.com/sentriz/gonic/commit/62d49a33d1c7cb93ed7bd44478b44b4bc5145889)), closes [#481](https://www.github.com/sentriz/gonic/issues/481)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **subsonic:** allow unlimited bitrate with no transcode setting configured ([81f8a7e](https://www.github.com/sentriz/gonic/commit/81f8a7ec49cc1fe66fdad2b1b80ff646ca2a1040)), closes [#485](https://www.github.com/sentriz/gonic/issues/485)
|
||||
|
||||
### [0.16.3](https://www.github.com/sentriz/gonic/compare/v0.16.2...v0.16.3) (2024-03-09)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* bump audiotags fork to support taglib v2 ([29c5397](https://www.github.com/sentriz/gonic/commit/29c5397dae82017e24347afe65e9bbf9be10a494))
|
||||
* **lastfm:** autocorrect artist and album name misspellings when fetching info ([2878b88](https://www.github.com/sentriz/gonic/commit/2878b88aeee8bdf7a2e45520298422b883d8ab24)), closes [#472](https://www.github.com/sentriz/gonic/issues/472)
|
||||
* **lastfm:** strip copyright text from albumInfo/artistInfo responses ([aa82b94](https://www.github.com/sentriz/gonic/commit/aa82b944b794ac07b41a34aeb2b4cc365a2666ef))
|
||||
* **listenbrainz:** submit release MBID ([#443](https://www.github.com/sentriz/gonic/issues/443)) ([552aa3a](https://www.github.com/sentriz/gonic/commit/552aa3afb138a125f15ab161a1a06cbe6c68a762))
|
||||
* replace ff with with flagconf ([3ada74c](https://www.github.com/sentriz/gonic/commit/3ada74c4db61c90ba428a071282fdacfd038cfc0))
|
||||
* **subsonic:** expose track musicbrainz id ([f98b232](https://www.github.com/sentriz/gonic/commit/f98b2326da31c15192f1c3b4bb17dcbfa59a058a))
|
||||
* **subsonic:** prefer tagged musicbrainz ID over lastfm in getAlbumInfo ([422c684](https://www.github.com/sentriz/gonic/commit/422c684f44369a0c85cb1a825e3d480ee157ca0b)), closes [#444](https://www.github.com/sentriz/gonic/issues/444)
|
||||
* **subsonic:** return `changed` field in playlist response ([8b4fc04](https://www.github.com/sentriz/gonic/commit/8b4fc04d3e7a22ba5beb3d682ea13b541c99d2bb)), closes [#455](https://www.github.com/sentriz/gonic/issues/455)
|
||||
* **subsonic:** return `playCount` in album responses ([ec55f3b](https://www.github.com/sentriz/gonic/commit/ec55f3b22a8c689cbd2305965b3c538f5c2bf25f)), closes [#458](https://www.github.com/sentriz/gonic/issues/458)
|
||||
* **subsonic:** return an error if maxBitRate requested with no user transcode preferences set ([88e58c0](https://www.github.com/sentriz/gonic/commit/88e58c055a2b1259d0c68618b943b4a319855b15))
|
||||
* **subsonic:** return http form post opensubsonic extension key ([e8ae1c1](https://www.github.com/sentriz/gonic/commit/e8ae1c1d406c7013b2a739dd13bac3076bde641f))
|
||||
* upgrade to ff v4 ([4600ee1](https://www.github.com/sentriz/gonic/commit/4600ee1cbb380bb7a9d255cbd51bd746e021eb63)), closes [#473](https://www.github.com/sentriz/gonic/issues/473)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **ci:** manually add taglib v2 APKBUILD ([51fa0ba](https://www.github.com/sentriz/gonic/commit/51fa0baac39577b335a3f5c064be81cf9293e9f0))
|
||||
* **db:** add double index for right side of unique compound indexes ([d640a9f](https://www.github.com/sentriz/gonic/commit/d640a9fc065bd3908968abacbd5ac080331c3e25)), closes [#426](https://www.github.com/sentriz/gonic/issues/426)
|
||||
* **docker:** fix sqlite3 musl build ([433829d](https://www.github.com/sentriz/gonic/commit/433829dc4f43f3be83a99cb54099be4f781dcf7d))
|
||||
* **listenbrainz:** set track length submission and include submission client details ([#424](https://www.github.com/sentriz/gonic/issues/424)) ([b27c02f](https://www.github.com/sentriz/gonic/commit/b27c02fc894510b714c129e898fd0e6792d017b4))
|
||||
* **playlist:** return new playlist id for createPlaylist ([314e963](https://www.github.com/sentriz/gonic/commit/314e9632d72dd7cd68044f9d69295123fff78f80)), closes [#464](https://www.github.com/sentriz/gonic/issues/464)
|
||||
* **podcast:** collect all episode errors when adding new podcast ([2f109f1](https://www.github.com/sentriz/gonic/commit/2f109f1982dea78dbdfe786cafa3c6718138b66e)), closes [#430](https://www.github.com/sentriz/gonic/issues/430)
|
||||
* **podcast:** slightly more robust downloading and concurrency ([#433](https://www.github.com/sentriz/gonic/issues/433)) ([f34cd2e](https://www.github.com/sentriz/gonic/commit/f34cd2e213f9be93ae3db4ad32e7e927fd15c618))
|
||||
* **scanner:** clean up orphaned album genres when dir still exists without tracks ([19ebd45](https://www.github.com/sentriz/gonic/commit/19ebd4540f9e47c521cc70587457a770110495a5)), closes [#466](https://www.github.com/sentriz/gonic/issues/466)
|
||||
* **scanner:** gracefully handle multi value tag delim splits with adjacent delimiters ([eb79cec](https://www.github.com/sentriz/gonic/commit/eb79cecc44628d3e24b2196e1d680f2b1ba15f97)), closes [#448](https://www.github.com/sentriz/gonic/issues/448)
|
||||
* **specid:** match music dirs with trailing slash ([#439](https://www.github.com/sentriz/gonic/issues/439)) ([e63ee96](https://www.github.com/sentriz/gonic/commit/e63ee9687e1cb4b76faa9ffe10bf99b4640ddd43))
|
||||
* **subsonic:** always return playlist duration ([87943ea](https://www.github.com/sentriz/gonic/commit/87943ea863f5e882ff4acfe329d6dde674ac630b)), closes [#457](https://www.github.com/sentriz/gonic/issues/457)
|
||||
* **subsonic:** fix getAvatar user request comparison ([#469](https://www.github.com/sentriz/gonic/issues/469)) ([2949b4c](https://www.github.com/sentriz/gonic/commit/2949b4c86715d9eebfe5bf116c8df7f0a5875eb3))
|
||||
* **subsonic:** return error code 70 for not found errors in more places ([42dbfa7](https://www.github.com/sentriz/gonic/commit/42dbfa7a85a25fcb80f2936ac7949d50ed1bfbf8)), closes [#454](https://www.github.com/sentriz/gonic/issues/454)
|
||||
|
||||
### [0.16.2](https://www.github.com/sentriz/gonic/compare/v0.16.1...v0.16.2) (2023-11-30)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* set global http timeouts except for streaming endpoints ([2edb1b8](https://www.github.com/sentriz/gonic/commit/2edb1b8eda649671aa4b0534ec8065bde65803e3)), closes [#411](https://www.github.com/sentriz/gonic/issues/411)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **admin:** don't start with empty session key ([dd0f6b3](https://www.github.com/sentriz/gonic/commit/dd0f6b3650426a06218bff875301471b92c6f03e)), closes [#414](https://www.github.com/sentriz/gonic/issues/414)
|
||||
* **jukebox:** make sure we clean up "seekable" event listener ([b199bc1](https://www.github.com/sentriz/gonic/commit/b199bc104e90eaf760563b6efca409ccd9618788)), closes [#411](https://www.github.com/sentriz/gonic/issues/411)
|
||||
* **jukebox:** restore play index only when incoming new track has index >0 ([82c3c5b](https://www.github.com/sentriz/gonic/commit/82c3c5baef5a5145902cd96e1a14d6d3fd50320f)), closes [#411](https://www.github.com/sentriz/gonic/issues/411)
|
||||
* **subsonic:** return empty opensubsonic fields ([5022500](https://www.github.com/sentriz/gonic/commit/5022500b307e746f2ff0426b07c4e776873c880a))
|
||||
|
||||
### [0.16.1](https://www.github.com/sentriz/gonic/compare/v0.16.0...v0.16.1) (2023-11-08)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add more and unify stats ([2fdc1f4](https://www.github.com/sentriz/gonic/commit/2fdc1f41a25435f2c543ea114dd366c3c3d8394f))
|
||||
* store and expose individual track artists ([c1a34dc](https://www.github.com/sentriz/gonic/commit/c1a34dc0219b83300b427e66ef388f27a6186c9f))
|
||||
* **subsonic:** add getAlbumInfo with cache ([cc1a99f](https://www.github.com/sentriz/gonic/commit/cc1a99f03381a5afcebdbe95aaa42fb969f98b9f))
|
||||
* **subsonic:** expose all of album "name"/"title"/"album" for browse by tag and browse by folder ([2df9052](https://www.github.com/sentriz/gonic/commit/2df9052bf9862258c81a69e362c23fa35e653831)), closes [#404](https://www.github.com/sentriz/gonic/issues/404)
|
||||
* **subsonic:** expose track/album displayArtist/displayAlbumArtist ([0718aab](https://www.github.com/sentriz/gonic/commit/0718aabbacd52b7737dea606238ba64f65f2c2c6)), closes [#406](https://www.github.com/sentriz/gonic/issues/406)
|
||||
* **subsonic:** support getAlbumList/getAlbumList2 `type=highest` ([a30ee3d](https://www.github.com/sentriz/gonic/commit/a30ee3d7f91ebf24f427e7f36b6b2830299935f9)), closes [#404](https://www.github.com/sentriz/gonic/issues/404)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add track count to /debug/vars metrics endpoint ([69c02e8](https://www.github.com/sentriz/gonic/commit/69c02e8352c10276697184d3c24d0f3253ec8c4d)), closes [#392](https://www.github.com/sentriz/gonic/issues/392)
|
||||
* **contrib:** update config example ([d03d2dc](https://www.github.com/sentriz/gonic/commit/d03d2dc760c6c14b6f79efeca8b0111ead8912af))
|
||||
* don't panic when scan on start fails ([37e826e](https://www.github.com/sentriz/gonic/commit/37e826e02b2cdcfc2d60bc860767f7dbd89a1dcd)), closes [#399](https://www.github.com/sentriz/gonic/issues/399)
|
||||
* **metrics:** have a distinction between folders and albums ([cae3725](https://www.github.com/sentriz/gonic/commit/cae37255d68cbf493aba0bbb35dae38ca18fc4b6)), closes [#396](https://www.github.com/sentriz/gonic/issues/396)
|
||||
* **scanner:** make sure we roll back invalid parents ([ddb686b](https://www.github.com/sentriz/gonic/commit/ddb686bddc5d040912812777829e6283d15c5343)), closes [#402](https://www.github.com/sentriz/gonic/issues/402)
|
||||
* store and scrobble with real album artist info string ([fe0567a](https://www.github.com/sentriz/gonic/commit/fe0567a995dc40daeffa0460f0272b6e3af783a8))
|
||||
* **subsonic:** don't return concatenated genres strings for song/trackchilds ([f18151b](https://www.github.com/sentriz/gonic/commit/f18151b75573e6f024529ec4a134ef213dd86a78))
|
||||
* **subsonic:** songCount and albumCount in genre objects is required ([#390](https://www.github.com/sentriz/gonic/issues/390)) ([b17e76e](https://www.github.com/sentriz/gonic/commit/b17e76ea730e213d99a164c8ddff2c4b951f7f1f))
|
||||
* use conf cache-path instead of XDG_CACHE_HOME for jukebox socket ([9818523](https://www.github.com/sentriz/gonic/commit/981852317572a8c6ab357e9ce81523780801d3fe)), closes [#391](https://www.github.com/sentriz/gonic/issues/391)
|
||||
|
||||
## [0.16.0](https://www.github.com/sentriz/gonic/compare/v0.15.2...v0.16.0) (2023-10-09)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **build:** bump to go 1.21
|
||||
* **subsonic:** drop support for guessed artist covers in filesystem
|
||||
|
||||
### Features
|
||||
|
||||
* add .wav to list of supported audio types ([#322](https://www.github.com/sentriz/gonic/issues/322)) ([ab07b87](https://www.github.com/sentriz/gonic/commit/ab07b876b8686d2e2c792f2d422dd227d6f9d94b))
|
||||
* add option for /debug/vars endpoint to expose database and media stats ([2a7a455](https://www.github.com/sentriz/gonic/commit/2a7a455ce27c3f8007a6114f815ae8ae94648533)), closes [#372](https://www.github.com/sentriz/gonic/issues/372) [#150](https://www.github.com/sentriz/gonic/issues/150)
|
||||
* add support for wavpack ([#380](https://www.github.com/sentriz/gonic/issues/380)) ([827baf2](https://www.github.com/sentriz/gonic/commit/827baf2036dfe581bfddba1c5b88510c13b8bba6))
|
||||
* **admin:** sort transcode profile names ([ae5bc2e](https://www.github.com/sentriz/gonic/commit/ae5bc2e1494f983993be7a053c953ca2f8555fae)), closes [#288](https://www.github.com/sentriz/gonic/issues/288)
|
||||
* **admin:** support application/x-mpegurl playlist uploads ([6aa4c42](https://www.github.com/sentriz/gonic/commit/6aa4c42ce556f5a503bd9d5a4d1ee957c167dafa)), closes [#282](https://www.github.com/sentriz/gonic/issues/282)
|
||||
* **admin:** update stylesheet ([222256c](https://www.github.com/sentriz/gonic/commit/222256cccbeb791168070ba5fe04a3bc1632cb94))
|
||||
* allow multi valued tag modes to be configurable ([8f6610f](https://www.github.com/sentriz/gonic/commit/8f6610ff860ad18d56545b903d9edb6a1254ddec))
|
||||
* **ci:** add a bunch more linters ([e3dd812](https://www.github.com/sentriz/gonic/commit/e3dd812b6c13c5f74690a868d0a5c37f30e33053))
|
||||
* **ci:** update checkout and setup-go actions ([#326](https://www.github.com/sentriz/gonic/issues/326)) ([6144ac7](https://www.github.com/sentriz/gonic/commit/6144ac7979e03d704f8f721ba378eb612538d284))
|
||||
* **ci:** update golangci-lint and action ([#325](https://www.github.com/sentriz/gonic/issues/325)) ([85eeb86](https://www.github.com/sentriz/gonic/commit/85eeb860bf1f97091fbd101b3bc827ff6502ccdb))
|
||||
* **contrib:** improve system related contrib files ([ac74b35](https://www.github.com/sentriz/gonic/commit/ac74b354653b7353466eda3d81ca519bfa9f816e))
|
||||
* enable profile-guided optimization ([e842b89](https://www.github.com/sentriz/gonic/commit/e842b896ec5acde6acdefbf3ec66610bd6cf7e22))
|
||||
* **lastfm:** add user get loved tracks method ([9026c9e](https://www.github.com/sentriz/gonic/commit/9026c9e2c0463c467958b7032e4e6f7a889c3c76))
|
||||
* **podcast:** parse podcast episode descriptions from HTML to plain text ([#351](https://www.github.com/sentriz/gonic/issues/351)) ([7d2c4fb](https://www.github.com/sentriz/gonic/commit/7d2c4fbb5c4cec3e7bcb4852214c17999bf320bb))
|
||||
* **scanner:** add a new option for excluding paths based on a regexp ([1d38776](https://www.github.com/sentriz/gonic/commit/1d3877668f9bf925cae7c548b5d8e683d9676af2))
|
||||
* **scanner:** support more cover types ([906164a](https://www.github.com/sentriz/gonic/commit/906164a5de34047444efe75b52b014737c111bc4))
|
||||
* **scanner:** support non lowercase extensions like .Mp3 ([d83fe56](https://www.github.com/sentriz/gonic/commit/d83fe560d3df980c0bf99d03e026af9bce30e0c7))
|
||||
* store and use m3u files on filesystem for playlists ([7dc9575](https://www.github.com/sentriz/gonic/commit/7dc9575e52538cf4fd39715193b5c760e1cc477b)), closes [#306](https://www.github.com/sentriz/gonic/issues/306) [#307](https://www.github.com/sentriz/gonic/issues/307) [#66](https://www.github.com/sentriz/gonic/issues/66)
|
||||
* **subsonic:** add getOpenSubsonicExtensions endpoint and openSubsonic response key ([2caee44](https://www.github.com/sentriz/gonic/commit/2caee441ca49e7b2ca148f5b698365085db0cfc8))
|
||||
* **subsonic:** add support for multi-valued album artist tags ([3ac7782](https://www.github.com/sentriz/gonic/commit/3ac77823c3bdc2e2be543f18e7b78295a7eb2fb8))
|
||||
* **subsonic:** add support for podcast episodes in both playlists and play queues ([aecee3d](https://www.github.com/sentriz/gonic/commit/aecee3d2d859ca9e754db9f65bf031290d0ce4a5))
|
||||
* **subsonic:** cache and use lastfm responses for covers, bios, top songs ([c374577](https://www.github.com/sentriz/gonic/commit/c374577328c17b6c3c7b6edbf901585e1f6644ee))
|
||||
* **subsonic:** change frequent album list to use total time played per album instead of play count. ([#331](https://www.github.com/sentriz/gonic/issues/331)) ([7982ffc](https://www.github.com/sentriz/gonic/commit/7982ffc0b46bc3e14eb753cfb3791e183a75834b))
|
||||
* **subsonic:** drop support for guessed artist covers in filesystem ([657fb22](https://www.github.com/sentriz/gonic/commit/657fb221db002ffebbf2a8d603566191acb40d17))
|
||||
* **subsonic:** expose all album genres in a list of subsonic api ([749233d](https://www.github.com/sentriz/gonic/commit/749233db4effbdc7c3288f7cb8052784379be44f))
|
||||
* **subsonic:** fetch artist images from lastfm opengraph ([4757495](https://www.github.com/sentriz/gonic/commit/475749534f784eb803eec9cb83c72d49f30d1994)), closes [#295](https://www.github.com/sentriz/gonic/issues/295)
|
||||
* **subsonic:** gracefully handle missing podcast episode paths when returning playlists ([d5f8e23](https://www.github.com/sentriz/gonic/commit/d5f8e23a89cf1677e6ced124df4c0e07cdb7d114))
|
||||
* **subsonic:** improve search2 and search3 when there are multiple words searched on. ([#335](https://www.github.com/sentriz/gonic/issues/335)) ([cbab68b](https://www.github.com/sentriz/gonic/commit/cbab68b05700aeb8b1fc2192ae5263ead248baf4))
|
||||
* **subsonic:** make it easier to add more tag reading backends ([8382f61](https://www.github.com/sentriz/gonic/commit/8382f6123c2ac39d12b266730d76301faaf168f4))
|
||||
* **subsonic:** order results from getStarred reverse chronologically based on star date ([b3c863c](https://www.github.com/sentriz/gonic/commit/b3c863c386adb830cdb45f45644f4779a4b73e86))
|
||||
* **subsonic:** return artist cover ids for similar artists response ([c15349f](https://www.github.com/sentriz/gonic/commit/c15349f79667e71138c6088f52f8efbd9966c33a))
|
||||
* **subsonic:** scrobble to different scrobble backends in parallel ([1ea2402](https://www.github.com/sentriz/gonic/commit/1ea240255927986b90a39c9ea67736f1b6808441))
|
||||
* **subsonic:** support timeOffset in stream.view ([#384](https://www.github.com/sentriz/gonic/issues/384)) ([7eaf602](https://www.github.com/sentriz/gonic/commit/7eaf602e6990d6840f2fc5792599abb09bbef24b))
|
||||
* **subsonic:** update track play stats on scrobble instead of stream ([e0b1603](https://www.github.com/sentriz/gonic/commit/e0b1603c00f7c24ce9b57085f5447bc0d7b016d7))
|
||||
* **sunsonic:** expose type serverVersion in subsonic responses ([b8fceae](https://www.github.com/sentriz/gonic/commit/b8fceae3834d29f447fbb23eeb77f6216018e55a))
|
||||
* **tags:** support multi valued tags like albumartists ([623d5c3](https://www.github.com/sentriz/gonic/commit/623d5c370906784b3ba8b21b89e435eafd41771e))
|
||||
* **transcode:** add MP3 320 transcoding profile ([#363](https://www.github.com/sentriz/gonic/issues/363)) ([a644f0f](https://www.github.com/sentriz/gonic/commit/a644f0ff5c47c0f196c937dd76189de1e6099594))
|
||||
* **transcode:** add opus 192 profile ([5dcc8c1](https://www.github.com/sentriz/gonic/commit/5dcc8c18a1f0cedf1ce6772aafe6dbdec1ded03c))
|
||||
* **transcode:** lock the destination transcode cache path ([c9a2d2f](https://www.github.com/sentriz/gonic/commit/c9a2d2f9ce3fd7b9c724d8d2079abf43c2aa339b))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **admin:** continue on track match error ([16e6046](https://www.github.com/sentriz/gonic/commit/16e6046e85b99ebadc08f07b75404d7e67f6b77f))
|
||||
* **podcasts:** make sure we use safeFilename for podcast episodes too ([#339](https://www.github.com/sentriz/gonic/issues/339)) ([5fb9c49](https://www.github.com/sentriz/gonic/commit/5fb9c49ed2810a1b63fce8930320eb7de0356c33))
|
||||
* **podcasts:** remove query parameters from URL when getting the extension ([19be6f0](https://www.github.com/sentriz/gonic/commit/19be6f0881ed6c0c3311793c55dbbbe0a5571f51))
|
||||
* **scanner:** fix watcher panic ([78d0c52](https://www.github.com/sentriz/gonic/commit/78d0c52d2240671a1e529339727bd013b7feb5c6))
|
||||
* **scanner:** remove redundant mod time look up ([e0a8c18](https://www.github.com/sentriz/gonic/commit/e0a8c18b8df9b148053ed5dbe535f76c245e7df8)), closes [#293](https://www.github.com/sentriz/gonic/issues/293)
|
||||
* **subsonic:** only return one bookmark entry per row in getBookmarks ([efe72fc](https://www.github.com/sentriz/gonic/commit/efe72fc447a23f48f0a49d92a7b3ed3c68d03722)), closes [#310](https://www.github.com/sentriz/gonic/issues/310)
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* **build:** bump to go 1.21 ([658bae2](https://www.github.com/sentriz/gonic/commit/658bae2b43d170fa249ef2a0e953a494e0b2061a))
|
||||
|
||||
### [0.15.2](https://www.github.com/sentriz/gonic/compare/v0.15.1...v0.15.2) (2022-12-27)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **subsonic:** send valid content-type with http.ServeStream ([8dc58c7](https://www.github.com/sentriz/gonic/commit/8dc58c71a45b4bd8ec4224392a4d2ed3c36c24fa))
|
||||
|
||||
### [0.15.1](https://www.github.com/sentriz/gonic/compare/v0.15.0...v0.15.1) (2022-12-26)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* allow for custom music folder path alias ([7e097c9](https://www.github.com/sentriz/gonic/commit/7e097c9bdffa6f6cff57e5af6d9dea6965553c19)), closes [#259](https://www.github.com/sentriz/gonic/issues/259)
|
||||
* **scrobble:** only send musicbrainz id if it's a valid uuid ([2bc3f31](https://www.github.com/sentriz/gonic/commit/2bc3f31554c9b6be9a9beef72b76e437d13131be))
|
||||
* **server:** recover from panics ([df93286](https://www.github.com/sentriz/gonic/commit/df932864d812b6a83d1049c7a4820172c859ab22))
|
||||
* **subsonic:** add stub lyrics.view ([0407a15](https://www.github.com/sentriz/gonic/commit/0407a1581f5d80dc66e849906518cb73a4dc3311)), closes [#274](https://www.github.com/sentriz/gonic/issues/274)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **jukebox:** gracefully handle case of no audio in feed item ([b47c880](https://www.github.com/sentriz/gonic/commit/b47c880ea5ffd357878b7617c3493d7b1f48f4cf)), closes [#269](https://www.github.com/sentriz/gonic/issues/269)
|
||||
* **jukebox:** use a tmp dir instead of file for mpv sock ([4280700](https://www.github.com/sentriz/gonic/commit/42807006213871432b7ddfbb623ed6f82f4122c6)), closes [#266](https://www.github.com/sentriz/gonic/issues/266) [#265](https://www.github.com/sentriz/gonic/issues/265)
|
||||
* **subsonic:** update music folder id in bounds check ([c6ddee8](https://www.github.com/sentriz/gonic/commit/c6ddee8f7e7f246c4384b05384057c24231937a1)), closes [#271](https://www.github.com/sentriz/gonic/issues/271)
|
||||
* **transcode:** don't leave half transcode cache files lying around ([ce31310](https://www.github.com/sentriz/gonic/commit/ce31310571a1b1c3007202d507bec5ef1a9fad99)), closes [#270](https://www.github.com/sentriz/gonic/issues/270)
|
||||
|
||||
## [0.15.0](https://www.github.com/sentriz/gonic/compare/v0.14.0...v0.15.0) (2022-11-17)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* upgrade deps and require go 1.19
|
||||
* **podcast:** make podcasts global not per user, to match spec
|
||||
|
||||
### Features
|
||||
|
||||
* add a ping endpoint that doesn't create a session ([731a696](https://www.github.com/sentriz/gonic/commit/731a696bd795bbec668e4685ed1cb2271044c8aa))
|
||||
* add CreatedAt to albums ([#159](https://www.github.com/sentriz/gonic/issues/159)) ([848d85d](https://www.github.com/sentriz/gonic/commit/848d85d26a4c2a6e83cd01c21e63080fdbb27cd8))
|
||||
* add multi folder support ([40cd031](https://www.github.com/sentriz/gonic/commit/40cd031b05c71d930b5d92ed6ebbbf676f5e219e)), closes [#50](https://www.github.com/sentriz/gonic/issues/50)
|
||||
* **countrw:** add countrw package ([5155dee](https://www.github.com/sentriz/gonic/commit/5155dee2e82972ef50adfdbe2298b1126dcd994d))
|
||||
* **jukebox:** allow users to pass custom arguments to mpv ([428fdda](https://www.github.com/sentriz/gonic/commit/428fddad1bad0dc7091528794622fc2d2dc7c1dc)), closes [#125](https://www.github.com/sentriz/gonic/issues/125) [#164](https://www.github.com/sentriz/gonic/issues/164)
|
||||
* **jukebox:** use mpv over ipc as a player backend ([e1488b0](https://www.github.com/sentriz/gonic/commit/e1488b0d183a3244eba89220ad960865b94087e5))
|
||||
* **lastfm:** scrobble with duration ([7d0d036](https://www.github.com/sentriz/gonic/commit/7d0d036f0bc0f5bd4429f510ca636daa3934766b))
|
||||
* log all folders while scanning ([b2388e6](https://www.github.com/sentriz/gonic/commit/b2388e6d851c2192bda14eb7771c83ce75f493f9))
|
||||
* **mockfs:** add DumpDB method ([b0d5861](https://www.github.com/sentriz/gonic/commit/b0d5861d10a5472d4ac07a5e27331ec492be69b6))
|
||||
* **podcasts:** add an option to purge old episodes ([85cb0fe](https://www.github.com/sentriz/gonic/commit/85cb0feb5a11b753bc7936e040e00e95e6601b47))
|
||||
* render local artist images for getArtistInfo2 ([cb6b33a](https://www.github.com/sentriz/gonic/commit/cb6b33a9fb69589bf73e33773c6f16bf073ce865))
|
||||
* render local artist images with no foreign key ([a74b5a2](https://www.github.com/sentriz/gonic/commit/a74b5a261c5d47c1a24942ecd4ddd98666755ad4))
|
||||
* **scanner:** add fuzzing test ([f7f4b8b](https://www.github.com/sentriz/gonic/commit/f7f4b8b2cc3fffaa85a63fceba1bdc7cd79c9044))
|
||||
* **scanner:** add option to use fsnotify based scan watcher ([#232](https://www.github.com/sentriz/gonic/issues/232)) ([ea28ff1](https://www.github.com/sentriz/gonic/commit/ea28ff1df3f0ea30c53bc79c2e9980ea7ad7206b))
|
||||
* **scanner:** added option to scan at startup ([f6c9550](https://www.github.com/sentriz/gonic/commit/f6c95503c714dce11bddc4db632028ab09992093)), closes [#251](https://www.github.com/sentriz/gonic/issues/251)
|
||||
* **server:** support TLS ([59c4047](https://www.github.com/sentriz/gonic/commit/59c404749fa71416e29facac4ec523acd65a0f01))
|
||||
* **subsonic:** add avatar support ([5e66261](https://www.github.com/sentriz/gonic/commit/5e66261f0ccd63e6ceda46dc908661a748c16325)), closes [#228](https://www.github.com/sentriz/gonic/issues/228)
|
||||
* **subsonic:** add detailed logging about requested audio ([dc4d9e4](https://www.github.com/sentriz/gonic/commit/dc4d9e4e96c905f6edcfcdddae0a16214b3b054d)), closes [#212](https://www.github.com/sentriz/gonic/issues/212)
|
||||
* **subsonic:** add getNewestPodcasts ([f6687df](https://www.github.com/sentriz/gonic/commit/f6687df3f3f0d94a2db661b9d4b276175d951d68))
|
||||
* **subsonic:** add internet radio support ([7ab378a](https://www.github.com/sentriz/gonic/commit/7ab378accbadf2f25478ae37e231aacca881f7b7))
|
||||
* **subsonic:** add support for track/album/artist ratings/stars ([e8759cb](https://www.github.com/sentriz/gonic/commit/e8759cb6c11cd61a2a8ca3892fc905c4a9c4b167))
|
||||
* **subsonic:** add year and genre fields to track-by-folder response ([53a4247](https://www.github.com/sentriz/gonic/commit/53a4247dfd18d0783316d6a38126eca3f9df8af9)), closes [#223](https://www.github.com/sentriz/gonic/issues/223)
|
||||
* **subsonic:** implement getSimilarSongs.view ([e1cfed7](https://www.github.com/sentriz/gonic/commit/e1cfed7965ed43c91689fd5949dab55fa77a983d)), closes [#195](https://www.github.com/sentriz/gonic/issues/195)
|
||||
* **subsonic:** implement getSimilarSongs2.view ([92febcf](https://www.github.com/sentriz/gonic/commit/92febcffe6bbaff487b6869fbd3467003c987bed)), closes [#195](https://www.github.com/sentriz/gonic/issues/195)
|
||||
* **subsonic:** implement getTopSongs.view ([39b3ae5](https://www.github.com/sentriz/gonic/commit/39b3ae5ecb2ddb8c733beb99c80b68356d203be2)), closes [#195](https://www.github.com/sentriz/gonic/issues/195)
|
||||
* **subsonic:** improve getArtistInfo2.view similar artist results ([#203](https://www.github.com/sentriz/gonic/issues/203)) ([55c0920](https://www.github.com/sentriz/gonic/commit/55c09209b6ebdc0ecd7ca17d5b173a8db0cb23b1))
|
||||
* **subsonic:** log error responses ([2440e69](https://www.github.com/sentriz/gonic/commit/2440e696892b38d2cc255373f700c2449a98fef2))
|
||||
* **subsonic:** make the v param optional ([50e2818](https://www.github.com/sentriz/gonic/commit/50e2818cc78aad1c5ecdb388dd0ebb5e16f0ae26))
|
||||
* **subsonic:** return transcoded mime and transcoded suffix in subsonic responses ([6e6404a](https://www.github.com/sentriz/gonic/commit/6e6404af73357b4abcf0d45d2e8114f4404d1b5c))
|
||||
* **subsonic:** skip transcoding if request bitrate is the same as track bitrate ([f41dd08](https://www.github.com/sentriz/gonic/commit/f41dd0818ba95e27fbad376438585a1057f60382)), closes [#241](https://www.github.com/sentriz/gonic/issues/241)
|
||||
* **subsonic:** sort artist album list ([e56f64a](https://www.github.com/sentriz/gonic/commit/e56f64a75877efe15f96414c5dc58a33b03cb9ce)), closes [#197](https://www.github.com/sentriz/gonic/issues/197)
|
||||
* **subsonic:** support dsub edgecase for queries by decade ([03df207](https://www.github.com/sentriz/gonic/commit/03df207e638122446a9b24facfd0b893ddd9e0e8))
|
||||
* **subsonic:** support public playlists ([1647eaa](https://www.github.com/sentriz/gonic/commit/1647eaac4585cca7a244036f9c242a5602706b83))
|
||||
* **subsonic:** update play stats when scrobbling ([1ab47d6](https://www.github.com/sentriz/gonic/commit/1ab47d6fbee83f2dd00256bf5cd9ad33c2448202)), closes [#207](https://www.github.com/sentriz/gonic/issues/207)
|
||||
* **transcode:** add a generic transcoding package for encoding/decoding/caching ([165904c](https://www.github.com/sentriz/gonic/commit/165904c2bb2857aacc9053759ff707d64389a3bb))
|
||||
* **transcode:** add opus 128 kbps profiles ([bb83426](https://www.github.com/sentriz/gonic/commit/bb83426816a3f5fd45f14a5114e6843923598b21)), closes [#241](https://www.github.com/sentriz/gonic/issues/241)
|
||||
* **ui:** add a link to wiki in transcode profile section ([3348ca6](https://www.github.com/sentriz/gonic/commit/3348ca6b5bf0d054c8be38e860acdecc6e040b1c)), closes [#254](https://www.github.com/sentriz/gonic/issues/254)
|
||||
* **ui:** show when a scan is in progress ([7fbe7c0](https://www.github.com/sentriz/gonic/commit/7fbe7c0994356e5adaaa160e51ac4ae051ea027b))
|
||||
* use album create time for home ui and album listings ([14a2668](https://www.github.com/sentriz/gonic/commit/14a266842600fae27a134590d69542dc5d0d2cfc)), closes [#182](https://www.github.com/sentriz/gonic/issues/182) [#135](https://www.github.com/sentriz/gonic/issues/135)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add stub getStarred views to shut up refix ([27ac8e1](https://www.github.com/sentriz/gonic/commit/27ac8e1d25d9b58a8c71b9f7318a6b398f4a5865))
|
||||
* **ci:** set golangci-lint timeout ([48c34fd](https://www.github.com/sentriz/gonic/commit/48c34fdffc1c9bc47ce57d26b433dbbd775831a6))
|
||||
* **docs:** add GONIC_HTTP_LOG to setting table ([a11d6ab](https://www.github.com/sentriz/gonic/commit/a11d6ab92d3661d2311a1567bf8fffa07dd1eee6))
|
||||
* don't send listenbrainz playing_now and submitted_at at the same time ([b07b9a8](https://www.github.com/sentriz/gonic/commit/b07b9a8be610a932d6c66839f020456ff136d2f6)), closes [#168](https://www.github.com/sentriz/gonic/issues/168)
|
||||
* **lastfm:** make a better guess at callback protocol when incoming connection is TLS ([4658d07](https://www.github.com/sentriz/gonic/commit/4658d0727323fdf8107f94c7b0a61c419e6504f6)), closes [#213](https://www.github.com/sentriz/gonic/issues/213)
|
||||
* **listenbrainz:** set json header ([e883de8](https://www.github.com/sentriz/gonic/commit/e883de8c957a23d14103e547c7ddbbab161a43db))
|
||||
* **listenbrainz:** submit track recording ID instead of track ID ([8ee357b](https://www.github.com/sentriz/gonic/commit/8ee357b0217eeeebbee954111e17e4d29ac09c91)), closes [#240](https://www.github.com/sentriz/gonic/issues/240)
|
||||
* make sure open cover and audio files are closed after use ([1d1ab11](https://www.github.com/sentriz/gonic/commit/1d1ab116cd331fb5dbce50051f61be42e771ff80))
|
||||
* **podcast:** add error case for when DownloadEpisode is called via API and podcast is already downloaded ([611bc96](https://www.github.com/sentriz/gonic/commit/611bc96e29abd69e322b0a33705c164b1577dd99)), closes [#213](https://www.github.com/sentriz/gonic/issues/213)
|
||||
* **podcast:** add user agent to avoid 403s with some remotes ([0f80ae2](https://www.github.com/sentriz/gonic/commit/0f80ae2655509ddcc044c4e113f5ec1eaed77050))
|
||||
* render artistId in track types ([7ec6440](https://www.github.com/sentriz/gonic/commit/7ec6440ed2c95b0f38b8089c17dcd23a2d26bf23)), closes [#170](https://www.github.com/sentriz/gonic/issues/170)
|
||||
* **scanner:** better detect years given extraneous year tags ([a9d3933](https://www.github.com/sentriz/gonic/commit/a9d393350a0286d77d8eb1c68d46e5eb4c2e5cc8))
|
||||
* **scanner:** fix linting Ctim.Sec/Ctim.Nsec on 32 bit systems ([b280e8d](https://www.github.com/sentriz/gonic/commit/b280e8d256d28cfff6d135d8bf5eadc576e34d45))
|
||||
* **scanner:** fix records with album name same as artist ([fdbb282](https://www.github.com/sentriz/gonic/commit/fdbb28209b3e155825fa5380774102e2f119e22e)), closes [#230](https://www.github.com/sentriz/gonic/issues/230)
|
||||
* **scanner:** make sure we have an album artist before populating track ([01747c8](https://www.github.com/sentriz/gonic/commit/01747c89400decedaaa0f801bb9aeb8a7f6e75f5)), closes [#209](https://www.github.com/sentriz/gonic/issues/209)
|
||||
* **scanner:** respect "is full" setting ([f2143e3](https://www.github.com/sentriz/gonic/commit/f2143e32ef42ae25875db62a2337a4770e095798))
|
||||
* set ON DELETE SET NULL to artists.guessed_folder_id removing folders ([24d64e2](https://www.github.com/sentriz/gonic/commit/24d64e2125995bbe446fcadc449cc0914a70202c))
|
||||
* show artist album count when searching by tags ([0c79044](https://www.github.com/sentriz/gonic/commit/0c790442f4fc0c53dd0c71c05b66c600db883b9a))
|
||||
* show artist covers (raw url in artist info, cover id elsewhere) via scanned guessed artist folder ([c0ebd26](https://www.github.com/sentriz/gonic/commit/c0ebd2642206f7dba81f136cd9d576ded75bb14e)), closes [#180](https://www.github.com/sentriz/gonic/issues/180) [#179](https://www.github.com/sentriz/gonic/issues/179)
|
||||
* **subsonic:** change order of fromYear toYear query ([d7655cb](https://www.github.com/sentriz/gonic/commit/d7655cb9d167222446c32a21eb4951b75e12857d)), closes [#208](https://www.github.com/sentriz/gonic/issues/208)
|
||||
* **subsonic:** correct album orderding in getAlbumList, add starred request type in getAlbumList ([692ec68](https://www.github.com/sentriz/gonic/commit/692ec68282805e2dc3cf4a74ac7a44a249fe3695))
|
||||
* **subsonic:** return an error when no tracks provided in savePlayQueue ([d47d5e1](https://www.github.com/sentriz/gonic/commit/d47d5e17e91d1775e3c6f16d900ba3b565401393))
|
||||
* **subsonic:** return song artist ID, album and song genres from search3 ([1a1f39f](https://www.github.com/sentriz/gonic/commit/1a1f39f4e8e5553f32499b1461d227a93820e70f)), closes [#229](https://www.github.com/sentriz/gonic/issues/229)
|
||||
* **subsonic:** route settings.view -> admin home ([f9133aa](https://www.github.com/sentriz/gonic/commit/f9133aac91e5f18473dc461a6f2ffd0417967465))
|
||||
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* **podcast:** make podcasts global not per user, to match spec ([182c96e](https://www.github.com/sentriz/gonic/commit/182c96e9669369d862787f46b541b5090cd64887))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* upgrade deps and require go 1.19 ([385a980](https://www.github.com/sentriz/gonic/commit/385a980b715e7259f896198b4ad4624c40e1e9dd))
|
||||
|
||||
## [0.14.0](https://www.github.com/sentriz/gonic/compare/v0.13.1...v0.14.0) (2021-10-03)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **ci:** add debug build workflow ([2780dba](https://www.github.com/sentriz/gonic/commit/2780dba534b673b1a496d44c9fcc3007fd0f2e62))
|
||||
* **ci:** pin golangci-lint version ([8f7131e](https://www.github.com/sentriz/gonic/commit/8f7131e25b9ea4207cdb9091ccbae26b5118cdac))
|
||||
* **ci:** test before release please, and only run extra tests on develop and pull request ([cd5771f](https://www.github.com/sentriz/gonic/commit/cd5771f88635b95955c7d2aea72379411142b777))
|
||||
* **ci:** use GITHUB_TOKEN for release please ([608504b](https://www.github.com/sentriz/gonic/commit/608504bedc88ec02cef34849cb42fb476dd63e1c))
|
||||
* create cache directory on startup ([f3bc3ae](https://www.github.com/sentriz/gonic/commit/f3bc3ae78990948e75d0b9757c399aad4e5c3b6b)), closes [#127](https://www.github.com/sentriz/gonic/issues/127)
|
||||
* **encode:** add hi-gain RG and upsampling support ([616b152](https://www.github.com/sentriz/gonic/commit/616b152fede7d56b77b8ea96bc2b86226d690f93))
|
||||
* **encode:** add mime-type headers to cache handlers ([4109b5b](https://www.github.com/sentriz/gonic/commit/4109b5b66cbb53e9255fcd216195f8e1a773e48d))
|
||||
* **encode:** use "true" (unconstrained) VBR for Opus profiles ([b9f8ea7](https://www.github.com/sentriz/gonic/commit/b9f8ea704876eb033986e7e586f16c93e2864df2))
|
||||
* **jukebox:** reduce complexity and update dependencies ([#154](https://www.github.com/sentriz/gonic/issues/154)) ([3938136](https://www.github.com/sentriz/gonic/commit/393813665abb614fa2e2f57cdd575c4dd083b4b5))
|
||||
* support filter by genre in browse by folder mode ([b56f00e](https://www.github.com/sentriz/gonic/commit/b56f00e9ace62fc3d60b21eef7e638b1ec5007d7))
|
||||
* support filter by year in browse by folder mode ([6e2d4f7](https://www.github.com/sentriz/gonic/commit/6e2d4f73c53ab908b5933cfbbc1ffc97584e0a08))
|
||||
* Support WMA files, including those with embedded album art ([#143](https://www.github.com/sentriz/gonic/issues/143)) ([7100b2b](https://www.github.com/sentriz/gonic/commit/7100b2b241ab5c199aaa17b2631b85b065b383e1))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **build:** add zlib ([ccc0e3c](https://www.github.com/sentriz/gonic/commit/ccc0e3c58d9fb1975bc0bdcf4f87829e9f705b74))
|
||||
* **ci:** remove deprecated linters ([3382af7](https://www.github.com/sentriz/gonic/commit/3382af72f19eead97b601eee847fd60b6c50ca34))
|
||||
* **ci:** trim short hash ([6f26974](https://www.github.com/sentriz/gonic/commit/6f269745a5f678b256b4a715ba236a2b847e4de9))
|
||||
* **docs:** update ubuntu / systemd service instructions ([ef6dd6c](https://www.github.com/sentriz/gonic/commit/ef6dd6c82a638dcd8aa3254839e2f53580a4ef46)), closes [#126](https://www.github.com/sentriz/gonic/issues/126)
|
||||
* **encode:** Strip EBU R128 gain tags when using forced-RG transcoding ([#145](https://www.github.com/sentriz/gonic/issues/145)) ([5444d40](https://www.github.com/sentriz/gonic/commit/5444d40018c6f8051fc8d03ef46bd66737dfe1f4))
|
||||
* return early before type switch in ServeStream ([212a133](https://www.github.com/sentriz/gonic/commit/212a13395d288486f9baa57c2da9bef2d9b6324d)), closes [#152](https://www.github.com/sentriz/gonic/issues/152)
|
||||
* **scanner:** refactor a bit and fix the issue of repeatedly adding and removing tracks 😎 ([93608d0](https://www.github.com/sentriz/gonic/commit/93608d04b49ebfde3020752802fd665ccfe807bb)), closes [#26](https://www.github.com/sentriz/gonic/issues/26) [#63](https://www.github.com/sentriz/gonic/issues/63)
|
||||
* **scanner:** spawn interval scans in a goroutine ([c0ca6aa](https://www.github.com/sentriz/gonic/commit/c0ca6aaf0337a23b3f1d2a867884afe89fd4a281)), closes [#63](https://www.github.com/sentriz/gonic/issues/63)
|
||||
* **scanner:** update changed cover files when scanning ([f50817a](https://www.github.com/sentriz/gonic/commit/f50817a3dcdaf752ac4c9a20c078428846dc2bde)), closes [#158](https://www.github.com/sentriz/gonic/issues/158)
|
||||
* show "gonic" not version in --help ([3cf3bda](https://www.github.com/sentriz/gonic/commit/3cf3bdafd890ea25247f2bf9af14e775d8d1d148))
|
||||
* trim newlines when rendering flag values ([4637cf7](https://www.github.com/sentriz/gonic/commit/4637cf70c16d9c4ea30c9604ca79704ec0e3f0c4))
|
||||
|
||||
### [0.13.1](https://www.github.com/sentriz/gonic/compare/v0.13.0...v0.13.1) (2021-05-08)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **docker:** bump alpine / go ([1f941b2](https://www.github.com/sentriz/gonic/commit/1f941b2085815d8aa0bf7ad7f3e44efba20295e8))
|
||||
|
||||
## [0.13.0](https://www.github.com/sentriz/gonic/compare/v0.12.3...v0.13.0) (2021-05-08)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **subsonic:** don't return gonic version from responses
|
||||
* bump to go1.16 and embed version
|
||||
|
||||
### Features
|
||||
|
||||
* bump to go1.16 and embed version ([6f15589](https://www.github.com/sentriz/gonic/commit/6f15589c0889893b7beda85a81d49878401566f0))
|
||||
* **ci:** arm builds, push multiple registries ([0622672](https://www.github.com/sentriz/gonic/commit/06226724b718883cff9e9150e60e2eeacc2e0a1c))
|
||||
* **ci:** use ghcr and auto release ([c2c7eb2](https://www.github.com/sentriz/gonic/commit/c2c7eb249f77eebabc910c70357249a3017523ef))
|
||||
* **subsonic:** don't return gonic version from responses ([58624f0](https://www.github.com/sentriz/gonic/commit/58624f07dc81c36fda79827cc41ac57e89e18b37))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **ci:** only test on go1.16 ([e9743f0](https://www.github.com/sentriz/gonic/commit/e9743f0cb0e96e9b4b434141e890a0fa16ce3f18))
|
||||
* don't clutter db close in main ([e6b7691](https://www.github.com/sentriz/gonic/commit/e6b76915daa2bbd6f259f2b019cde9130c62e326))
|
||||
* trim newline from version ([a565008](https://www.github.com/sentriz/gonic/commit/a5650084d7969a37765d291a6554984e4ae4e2d9))
|
||||
@@ -1,35 +0,0 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM --platform=$BUILDPLATFORM golang:1.26-alpine3.23 AS builder
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
WORKDIR /src
|
||||
COPY go.mod .
|
||||
COPY go.sum .
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN \
|
||||
--mount=type=cache,target=/go/pkg/mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build \
|
||||
CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o /out/ ./cmd/...
|
||||
|
||||
FROM alpine:3.23
|
||||
LABEL org.opencontainers.image.source=https://github.com/sentriz/gonic
|
||||
RUN apk add -U --no-cache \
|
||||
ffmpeg \
|
||||
mpv \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
tini \
|
||||
shared-mime-info
|
||||
COPY --from=builder /out/* /usr/local/bin/
|
||||
VOLUME ["/cache", "/data", "/music", "/podcasts"]
|
||||
EXPOSE 80
|
||||
ENV TZ=
|
||||
ENV GONIC_DB_PATH=/data/gonic.db
|
||||
ENV GONIC_LISTEN_ADDR=:80
|
||||
ENV GONIC_MUSIC_PATH=/music
|
||||
ENV GONIC_PODCAST_PATH=/podcasts
|
||||
ENV GONIC_CACHE_PATH=/cache
|
||||
ENV GONIC_PLAYLISTS_PATH=/playlists
|
||||
ENTRYPOINT ["/sbin/tini", "--"]
|
||||
CMD ["gonic"]
|
||||
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is 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. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
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.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
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 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. Use with the GNU Affero General Public License.
|
||||
|
||||
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 Affero 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 special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU 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 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 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 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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
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 GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,181 +1,36 @@
|
||||
<p align="center"><img width="500" src="https://github.com/sentriz/gonic/blob/master/.github/logo.png?raw=true"></p>
|
||||
<h4 align="center">free-software <a href="http://www.subsonic.org/">subsonic</a> server API implementation, supporting its <a href="https://github.com/sentriz/gonic?tab=readme-ov-file#features">many clients</a></h4>
|
||||
<p align="center">
|
||||
<a href="http://hub.docker.com/r/sentriz/gonic"><img src="https://img.shields.io/docker/pulls/sentriz/gonic.svg"></a>
|
||||
<a href="https://repology.org/project/gonic/"><img src="https://repology.org/badge/tiny-repos/gonic.svg"></a>
|
||||
<a href="https://github.com/sentriz/gonic/releases"><img src="https://img.shields.io/github/v/release/sentriz/gonic.svg"></a>
|
||||
<a href="https://web.libera.chat/#gonic"><img src="https://img.shields.io/badge/libera.chat-%23gonic-blue.svg"></a>
|
||||
</p>
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## features
|
||||
## Getting Started
|
||||
|
||||
- browsing by folder (keeping your full tree intact) [see here](#directory-structure)
|
||||
- browsing by tags (using [taglib](https://taglib.org/) - supports mp3, opus, flac, ape, m4a, wav, etc.)
|
||||
- on-the-fly audio transcoding and caching (requires [ffmpeg](https://ffmpeg.org/)) (thank you [spijet](https://github.com/spijet/))
|
||||
- subsonic jukebox mode, for gapless server-side audio playback instead of streaming (thank you [lxea](https://github.com/lxea/))
|
||||
- support for podcasts (thank you [lxea](https://github.com/lxea/))
|
||||
- pretty fast scanning (with my library of ~50k tracks, initial scan takes about 10m, and about 6s after incrementally)
|
||||
- multiple users, each with their own transcoding preferences, playlists, top tracks, top artists, etc.
|
||||
- [last.fm](https://www.last.fm/) scrobbling
|
||||
- [listenbrainz](https://listenbrainz.org/) scrobbling (thank you [spezifisch](https://github.com/spezifisch), [lxea](https://github.com/lxea))
|
||||
- artist similarities and biographies from the last.fm api
|
||||
- support for multi valued tags like albumartists and genres ([see more](#multi-valued-tags-v016))
|
||||
- a web interface for configuration (set up last.fm, manage users, start scans, etc.)
|
||||
- support for the [album-artist](https://mkoby.com/2007/02/18/artist-versus-album-artist/) tag, to not clutter your artist list with compilation album appearances
|
||||
- written in [go](https://golang.org/), so lightweight and suitable for a raspberry pi, etc. (see ARM images below)
|
||||
- newer salt and token auth
|
||||
- tested on [airsonic-refix](https://github.com/tamland/airsonic-refix), [amperfy](https://github.com/BLeeEZ/amperfy), [symfonium](https://symfonium.app), [dsub](https://f-droid.org/en/packages/github.daneren2005.dsub/), [jamstash](https://github.com/sqrlmstr5000/Jamstash), [music-assistant](https://www.music-assistant.io/), [subsonic.el](https://git.sr.ht/~amk/subsonic.el), [sublime music](https://github.com/sublime-music/sublime-music), [soundwaves](https://apps.apple.com/us/app/soundwaves/id736139596), [stmp](https://github.com/wildeyedskies/stmp), [termsonic](https://git.sixfoisneuf.fr/termsonic/), [tempus](https://github.com/eddyizm/tempus/), [strawberry](https://www.strawberrymusicplayer.org/), and [ultrasonic](https://gitlab.com/ultrasonic/ultrasonic)
|
||||
First, run the development server:
|
||||
|
||||
## installation
|
||||
|
||||
the default login is **admin**/**admin**.
|
||||
password can then be changed from the web interface
|
||||
|
||||
### ...from source
|
||||
|
||||
<https://github.com/sentriz/gonic/wiki/installation#from-source>
|
||||
|
||||
### ...with docker
|
||||
|
||||
<https://github.com/sentriz/gonic/wiki/installation#with-docker>
|
||||
|
||||
### ...with systemd
|
||||
|
||||
<https://github.com/sentriz/gonic/wiki/installation#with-systemd>
|
||||
|
||||
### ...elsewhere
|
||||
|
||||
[](https://repology.org/project/gonic/versions)
|
||||
|
||||
## configuration options
|
||||
|
||||
| env var | command line arg | description |
|
||||
| ----------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `GONIC_MUSIC_PATH` | `-music-path` | path to your music collection (see also multi-folder support below) |
|
||||
| `GONIC_DEFAULT_MUSIC_PATH` | `-default-music-path` | default music path for when no folder is selected in client (useful for when client does not support choosing a folder) |
|
||||
| `GONIC_PODCAST_PATH` | `-podcast-path` | path to a podcasts directory |
|
||||
| `GONIC_PLAYLISTS_PATH` | `-playlists-path` | path to new or existing directory with m3u files for subsonic playlists. items in the directory should be in the format `<userid>/<name>.m3u`. for example the admin user could have `1/my-playlist.m3u`. gonic create and make changes to these playlists over the subsonic api. |
|
||||
| `GONIC_CACHE_PATH` | `-cache-path` | path to store audio transcodes, covers, etc |
|
||||
| `GONIC_DB_PATH` | `-db-path` | **optional** path to database file |
|
||||
| `GONIC_HTTP_LOG` | `-http-log` | **optional** http request logging, enabled by default |
|
||||
| `GONIC_LISTEN_ADDR` | `-listen-addr` | **optional** host and port to listen on (eg. `0.0.0.0:4747`, `127.0.0.1:4747`) (_default_ `0.0.0.0:4747`) |
|
||||
| `GONIC_TLS_CERT` | `-tls-cert` | **optional** path to a TLS cert (enables HTTPS listening) |
|
||||
| `GONIC_TLS_KEY` | `-tls-key` | **optional** path to a TLS key (enables HTTPS listening) |
|
||||
| `GONIC_PROXY_PREFIX` | `-proxy-prefix` | **optional** url path prefix to use if behind reverse proxy. eg `/gonic` (see example configs below) |
|
||||
| `GONIC_SCAN_INTERVAL` | `-scan-interval` | **optional** interval (in minutes) to check for new music (automatic scanning disabled if omitted) |
|
||||
| `GONIC_SCAN_AT_START_ENABLED` | `-scan-at-start-enabled` | **optional** whether to perform an initial scan at startup |
|
||||
| `GONIC_SCAN_WATCHER_ENABLED` | `-scan-watcher-enabled` | **optional** whether to watch file system for new music and rescan |
|
||||
| `GONIC_SCAN_EMBEDDED_COVER_ENABLED` | `-scan-embedded-cover-enabled` | **optional** whether to scan for embedded covers in audio files (_default_ `true`) |
|
||||
| `GONIC_JUKEBOX_ENABLED` | `-jukebox-enabled` | **optional** whether the subsonic [jukebox api](https://airsonic.github.io/docs/jukebox/) should be enabled |
|
||||
| `GONIC_JUKEBOX_MPV_EXTRA_ARGS` | `-jukebox-mpv-extra-args` | **optional** extra command line arguments to pass to the jukebox mpv daemon |
|
||||
| `GONIC_PODCAST_PURGE_AGE` | `-podcast-purge-age` | **optional** age (in days) to purge podcast episodes if not accessed |
|
||||
| `GONIC_EXCLUDE_PATTERN` | `-exclude-pattern` | **optional** files matching this regex pattern will not be imported. eg <code>@eaDir\|[aA]rtwork\|[cC]overs\|[sS]cans\|[sS]pectrals</code> |
|
||||
| `GONIC_MULTI_VALUE_GENRE` | `-multi-value-genre` | **optional** setting for multi-valued genre tags when scanning ([see more](#multi-valued-tags-v016)) |
|
||||
| `GONIC_MULTI_VALUE_ARTIST` | `-multi-value-artist` | **optional** setting for multi-valued artist tags when scanning ([see more](#multi-valued-tags-v016)) |
|
||||
| `GONIC_MULTI_VALUE_ALBUM_ARTIST` | `-multi-value-album-artist` | **optional** setting for multi-valued album artist tags when scanning ([see more](#multi-valued-tags-v016)) |
|
||||
| `GONIC_TRANSCODE_CACHE_SIZE` | `-transcode-cache-size` | **optional** size of the transcode cache in MB (0 = no limit) |
|
||||
| `GONIC_TRANSCODE_EJECT_INTERVAL` | `-transcode-eject-interval` | **optional** interval (in minutes) to eject transcode cache (0 = never) |
|
||||
| `GONIC_EXPVAR` | `-expvar` | **optional** enable the /debug/vars endpoint (exposes useful debugging attributes as well as database stats) |
|
||||
| `GONIC_LDAP_FQDN` | `-ldap-fqdn` | **optional** the name of the server to connect to (required for LDAP) |
|
||||
| `GONIC_LDAP_PORT` | `-ldap-port` | **optional** what port the LDAP server is hosted on (_default_ `389`) |
|
||||
| `GONIC_LDAP_TLS` | `-ldap-tls` | **optional** whether gonic will connect to the LDAP server using TLS (_default_ `false`) |
|
||||
| `GONIC_LDAP_BASE_DN` | `-ldap-base-dn` | **optional** the base DN for LDAP objects (required for LDAP, escaping the commas might be necessary if using environmental variable) |
|
||||
| `GONIC_LDAP_USERNAME_ATTR` | `-ldap-username-attr` | **optional** attribute used by the LDAP server for usernames, gets prepended to BaseDN (_default_ `uid`) |
|
||||
| `GONIC_LDAP_BIND_USER` | `-ldap-bind-user` | **optional** the bind user to bind to LDAP with (required for LDAP) |
|
||||
| `GONIC_LDAP_BIND_PASS` | `-ldap-bind-pass` | **optional** the password of the LDAP bind user (required for LDAP) |
|
||||
| `GONIC_LDAP_FILTER` | `-ldap-filter` | **optional** the filter to select LDAP objects with (escaping the commas might be necessary if using environmental variable) |
|
||||
| `GONIC_LDAP_ADMIN_FILTER` | `-ldap-admin-filter` | **optional** the filter to select LDAP admin objects with (escaping the commas might be necessary if using environmental variable) (_default_ `(memberof=cn=admin)`) |
|
||||
|
||||
## multi valued tags (v0.16+)
|
||||
|
||||
gonic can support potentially multi valued tags like `genres`, `artists`, and `albumartists`. in both cases gonic will individual entries in its database for each.
|
||||
|
||||
this means being able to click find album "X" under both "techno" and "house" for example. or finding the album "My Life in the Bush of Ghosts" under either "David Byrne" or "Brian Eno". it also means not cluttering up your artists list with "A & X", "A and Y", "A ft. Z", etc. you will only have A, X, Y, and Z.
|
||||
|
||||
the available modes are:
|
||||
|
||||
| value | desc |
|
||||
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `multi` | gonic will explictly look for multi value fields in your audio metadata such as "genres" or "album_artists". software like [musicbrainz picard](https://picard.musicbrainz.org/), [beets](https://beets.io/) (v1.6.1+ / master), [wrtag](https://github.com/sentriz/wrtag/), or [betanin](https://github.com/sentriz/betanin/) can set set these |
|
||||
| `delim <delim>` | gonic will look at your normal audio metadata fields like "genre" or "album_artist", but split them on a delimiter. for example you could set `-multi-value-genre "delim ;"` to split the single genre field on ";". note this mode is not recommended unless you use an uncommon delimiter such as ";" or "\|". using a delimiter like "&" will likely lead to many [false positives](https://musicbrainz.org/artist/ccd4879c-5e88-4385-b131-bf65296bf245) |
|
||||
| `none` (default) | gonic will not attempt to do any multi value processing |
|
||||
|
||||
note: `,` is a special character in the environment variable parser. if you wish to use `,` for example for splitting genres, the `,` must be escaped with `\`. for example `"delim \,"`.
|
||||
|
||||
## screenshots
|
||||
|
||||
| | | | | |
|
||||
| :-----------------------------------------------------------------------------: | :-----------------------------------------------------------------------------: | :-----------------------------------------------------------------------------: | :-----------------------------------------------------------------------------: | :-----------------------------------------------------------------------------: |
|
||||
|  |  |  |  |  |
|
||||
|
||||
## multiple folders support (v0.15+)
|
||||
|
||||
gonic supports multiple music folders. this can be handy if you have your music separated by albums, compilations, singles. or maybe 70s, 80s, 90s. whatever.
|
||||
|
||||
on top of that - if you don't decide your folder names, or simply do not want the same name in your subsonic client,
|
||||
gonic can parse aliases for the folder names with the optional `ALIAS->PATH` syntax
|
||||
|
||||
if you're running gonic with the command line, stack the `-music-path` arg
|
||||
|
||||
```shell
|
||||
$ gonic -music-path "/path/to/albums" -music-path "/path/to/compilations" # without aliases
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
$ gonic -music-path "my albums->/path/to/albums" -music-path "my compilations->/path/to/compilations" # with aliases
|
||||
```
|
||||
|
||||
if you're running gonic with ENV_VARS, or docker, try separate with a comma
|
||||
|
||||
```shell
|
||||
export GONIC_MUSIC_PATH="/path/to/albums,/path/to/compilations" # without aliases
|
||||
yarn dev
|
||||
# or
|
||||
export GONIC_MUSIC_PATH="my albums->/path/to/albums,my compilations->/path/to/compilations" # with aliases
|
||||
```
|
||||
|
||||
if you're running gonic with the config file, you can repeat the `music-path` option
|
||||
|
||||
```
|
||||
# without aliases
|
||||
music-path /path/to/albums
|
||||
music-path /path/to/compilations
|
||||
|
||||
pnpm dev
|
||||
# or
|
||||
|
||||
# with aliases
|
||||
music-path my albums->/path/to/albums
|
||||
music-path my compilations->/path/to/compilations
|
||||
bun dev
|
||||
```
|
||||
|
||||
after that, most subsonic clients should allow you to select which music folder to use.
|
||||
queries like show me "recently played compilations" or "recently added albums" are possible for example.
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
## directory structure
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
when browsing by folder, any arbitrary and nested folder layout is supported, with the following caveats:
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
- files from the same album must all be in the same folder
|
||||
- all files in a folder must be from the same album
|
||||
## Learn More
|
||||
|
||||
please see [here](https://github.com/sentriz/gonic/issues/89) for more context
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
```
|
||||
music
|
||||
├── drum and bass
|
||||
│ └── Photek
|
||||
│ └── (1997) Modus Operandi
|
||||
│ ├── 01.10 The Hidden Camera.flac
|
||||
│ ├── 02.10 Smoke Rings.flac
|
||||
│ ├── 03.10 Minotaur.flac
|
||||
│ └── folder.jpg
|
||||
└── experimental
|
||||
└── Alan Vega
|
||||
├── (1980) Alan Vega
|
||||
│ ├── 01.08 Jukebox Babe.flac
|
||||
│ ├── 02.08 Fireball.flac
|
||||
│ ├── 03.08 Kung Foo Cowboy.flac
|
||||
│ └── folder.jpg
|
||||
└── (1990) Deuce Avenue
|
||||
├── 01.13 Body Bop Jive.flac
|
||||
├── 02.13 Sneaker Gun Fire.flac
|
||||
├── 03.13 Jab Gee.flac
|
||||
└── folder.jpg
|
||||
```
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,21 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import Image from "next/image";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
|
||||
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={180}
|
||||
height={38}
|
||||
priority
|
||||
/>
|
||||
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
|
||||
<li className="mb-2">
|
||||
Get started by editing{" "}
|
||||
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
|
||||
app/page.tsx
|
||||
</code>
|
||||
.
|
||||
</li>
|
||||
<li>Save and see your changes instantly.</li>
|
||||
</ol>
|
||||
|
||||
<div className="flex gap-4 items-center flex-col sm:flex-row">
|
||||
<a
|
||||
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Deploy now
|
||||
</a>
|
||||
<a
|
||||
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Read our docs
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src="/file.svg"
|
||||
alt="File icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Learn
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src="/window.svg"
|
||||
alt="Window icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Examples
|
||||
</a>
|
||||
<a
|
||||
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
|
||||
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
aria-hidden
|
||||
src="/globe.svg"
|
||||
alt="Globe icon"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Go to nextjs.org →
|
||||
</a>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,586 +0,0 @@
|
||||
//nolint:lll,gocyclo,forbidigo,nilerr,errcheck
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"expvar"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/pprof"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
// avatar encode/decode
|
||||
_ "image/gif"
|
||||
_ "image/png"
|
||||
|
||||
"github.com/google/shlex"
|
||||
"github.com/gorilla/securecookie"
|
||||
"github.com/sentriz/gormstore"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"go.senan.xyz/flagconf"
|
||||
|
||||
"go.senan.xyz/gonic"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/deps"
|
||||
"go.senan.xyz/gonic/handlerutil"
|
||||
"go.senan.xyz/gonic/infocache/albuminfocache"
|
||||
"go.senan.xyz/gonic/infocache/artistinfocache"
|
||||
"go.senan.xyz/gonic/jukebox"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
"go.senan.xyz/gonic/ldap"
|
||||
"go.senan.xyz/gonic/listenbrainz"
|
||||
"go.senan.xyz/gonic/playlist"
|
||||
"go.senan.xyz/gonic/podcast"
|
||||
"go.senan.xyz/gonic/scanner"
|
||||
"go.senan.xyz/gonic/scrobble"
|
||||
"go.senan.xyz/gonic/server/ctrladmin"
|
||||
"go.senan.xyz/gonic/server/ctrlsubsonic"
|
||||
"go.senan.xyz/gonic/transcode"
|
||||
)
|
||||
|
||||
func main() {
|
||||
confListenAddr := flag.String("listen-addr", "0.0.0.0:4747", "listen address (optional)")
|
||||
|
||||
confTLSCert := flag.String("tls-cert", "", "path to TLS certificate (optional)")
|
||||
confTLSKey := flag.String("tls-key", "", "path to TLS private key (optional)")
|
||||
|
||||
confPodcastPurgeAgeDays := flag.Uint("podcast-purge-age", 0, "age (in days) to purge podcast episodes if not accessed (optional)")
|
||||
confPodcastPath := flag.String("podcast-path", "", "path to podcasts")
|
||||
|
||||
confCachePath := flag.String("cache-path", "", "path to cache")
|
||||
|
||||
var confMusicPaths pathAliases
|
||||
flag.Var(&confMusicPaths, "music-path", "path to music")
|
||||
defaultMusicPath := flag.String("default-music-path", "", "interval (in minutes) to automatically scan music (optional)")
|
||||
|
||||
confPlaylistsPath := flag.String("playlists-path", "", "path to your list of new or existing m3u playlists that gonic can manage")
|
||||
|
||||
confDBPath := flag.String("db-path", "gonic.db", "path to database (optional)")
|
||||
|
||||
confScanIntervalMins := flag.Uint("scan-interval", 0, "interval (in minutes) to automatically scan music (optional)")
|
||||
confScanAtStart := flag.Bool("scan-at-start-enabled", false, "whether to perform an initial scan at startup (optional)")
|
||||
confScanWatcher := flag.Bool("scan-watcher-enabled", false, "whether to watch file system for new music and rescan (optional)")
|
||||
confScanEmbeddedCover := flag.Bool("scan-embedded-cover-enabled", true, "whether to scan for embedded covers in audio files (optional)")
|
||||
|
||||
confJukeboxEnabled := flag.Bool("jukebox-enabled", false, "whether the subsonic jukebox api should be enabled (optional)")
|
||||
confJukeboxMPVExtraArgs := flag.String("jukebox-mpv-extra-args", "", "extra command line arguments to pass to the jukebox mpv daemon (optional)")
|
||||
|
||||
confProxyPrefix := flag.String("proxy-prefix", "", "url path prefix to use if behind proxy. eg '/gonic' (optional)")
|
||||
confHTTPLog := flag.Bool("http-log", true, "http request logging (optional)")
|
||||
|
||||
confShowVersion := flag.Bool("version", false, "show gonic version")
|
||||
confConfigPath := flag.String("config-path", "", "path to config (optional)")
|
||||
|
||||
confExcludePattern := flag.String("exclude-pattern", "", "regex pattern to exclude files from scan (optional)")
|
||||
|
||||
var ldapConfig ldap.Config
|
||||
var ldapStore = make(ldap.LDAPStore)
|
||||
flag.StringVar(&ldapConfig.BindUser, "ldap-bind-user", "", "the bind user to bind to LDAP with (required for LDAP)")
|
||||
flag.StringVar(&ldapConfig.BindPass, "ldap-bind-pass", "", "the password of the LDAP bind user (required for LDAP)")
|
||||
flag.StringVar(&ldapConfig.BaseDN, "ldap-base-dn", "", "the base DN for LDAP objects (required for LDAP)")
|
||||
flag.StringVar(&ldapConfig.UsernameAttr, "ldap-username-attr", "uid", "attribute used by the LDAP server for usernames, gets prepended to BaseDN (optional)")
|
||||
|
||||
flag.StringVar(&ldapConfig.Filter, "ldap-filter", "", "the filter to select LDAP objects with (optional)")
|
||||
flag.StringVar(&ldapConfig.AdminFilter, "ldap-admin-filter", "(memberof=cn=admin)", "the filter to select LDAP objects with (optional)")
|
||||
|
||||
flag.StringVar(&ldapConfig.FQDN, "ldap-fqdn", "", "the name of the server to connect to (required for LDAP)")
|
||||
flag.UintVar(&ldapConfig.Port, "ldap-port", 389, "what port the LDAP server is hosted on (optional)")
|
||||
flag.BoolVar(&ldapConfig.TLS, "ldap-tls", false, "whether gonic will connect to the LDAP server using TLS (optional)")
|
||||
|
||||
if ldapConfig.FQDN != "" {
|
||||
if ldapConfig.BindUser == "" || ldapConfig.BindPass == "" || ldapConfig.BaseDN == "" {
|
||||
log.Fatal("a server was provided for an LDAP connection, but configuration is incomplete")
|
||||
}
|
||||
}
|
||||
|
||||
var confMultiValueGenre, confMultiValueArtist, confMultiValueAlbumArtist multiValueSetting
|
||||
flag.Var(&confMultiValueGenre, "multi-value-genre", "setting for multi-valued genre scanning (optional)")
|
||||
flag.Var(&confMultiValueArtist, "multi-value-artist", "setting for multi-valued track artist scanning (optional)")
|
||||
flag.Var(&confMultiValueAlbumArtist, "multi-value-album-artist", "setting for multi-valued album artist scanning (optional)")
|
||||
|
||||
confPprof := flag.Bool("pprof", false, "enable the /debug/pprof endpoint (optional)")
|
||||
confExpvar := flag.Bool("expvar", false, "enable the /debug/vars endpoint (optional)")
|
||||
confLogDB := flag.Bool("log-db", false, "enable database query logging (optional)")
|
||||
|
||||
deprecatedConfGenreSplit := flag.String("genre-split", "", "(deprecated, see multi-value settings)")
|
||||
|
||||
confTranscodeCacheSize := flag.Int("transcode-cache-size", 0, "size of the transcode cache in MB (0 = no limit) (optional)")
|
||||
confTranscodeEjectInterval := flag.Int("transcode-eject-interval", 0, "interval (in minutes) to eject transcode cache (0 = never) (optional)")
|
||||
|
||||
flag.Parse()
|
||||
flagconf.ParseEnv()
|
||||
flagconf.ParseConfig(*confConfigPath)
|
||||
|
||||
if *confShowVersion {
|
||||
fmt.Printf("v%s\n", gonic.Version)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
if _, err := regexp.Compile(*confExcludePattern); err != nil {
|
||||
log.Fatalf("invalid exclude pattern: %v\n", err)
|
||||
}
|
||||
|
||||
if len(confMusicPaths) == 0 {
|
||||
log.Fatalf("please provide a music directory")
|
||||
}
|
||||
|
||||
var err error
|
||||
for i, confMusicPath := range confMusicPaths {
|
||||
if confMusicPaths[i].path, err = validatePath(confMusicPath.path); err != nil {
|
||||
log.Fatalf("checking music dir %q: %v", confMusicPath.path, err)
|
||||
}
|
||||
}
|
||||
|
||||
if *confPodcastPath, err = validatePath(*confPodcastPath); err != nil {
|
||||
log.Fatalf("checking podcast directory: %v", err)
|
||||
}
|
||||
if *confCachePath, err = validatePath(*confCachePath); err != nil {
|
||||
log.Fatalf("checking cache directory: %v", err)
|
||||
}
|
||||
if *confPlaylistsPath, err = validatePath(*confPlaylistsPath); err != nil {
|
||||
log.Fatalf("checking playlist directory: %v", err)
|
||||
}
|
||||
|
||||
cacheDirAudio := path.Join(*confCachePath, "audio")
|
||||
cacheDirCovers := path.Join(*confCachePath, "covers")
|
||||
if err := os.MkdirAll(cacheDirAudio, os.ModePerm); err != nil {
|
||||
log.Fatalf("couldn't create audio cache path: %v\n", err)
|
||||
}
|
||||
if err := os.MkdirAll(cacheDirCovers, os.ModePerm); err != nil {
|
||||
log.Fatalf("couldn't create covers cache path: %v\n", err)
|
||||
}
|
||||
|
||||
dbc, err := db.New(*confDBPath, deps.DBDriverOptions(), *confLogDB)
|
||||
if err != nil {
|
||||
log.Fatalf("error opening database: %v\n", err)
|
||||
}
|
||||
defer dbc.Close()
|
||||
|
||||
err = dbc.Migrate(db.MigrationContext{
|
||||
Production: true,
|
||||
DBPath: *confDBPath,
|
||||
OriginalMusicPath: confMusicPaths[0].path,
|
||||
PlaylistsPath: *confPlaylistsPath,
|
||||
PodcastsPath: *confPodcastPath,
|
||||
})
|
||||
if err != nil {
|
||||
log.Panicf("error migrating database: %v\n", err)
|
||||
}
|
||||
|
||||
var musicPaths []ctrlsubsonic.MusicPath
|
||||
for _, pa := range confMusicPaths {
|
||||
musicPaths = append(musicPaths, ctrlsubsonic.MusicPath{Alias: pa.alias, Path: pa.path})
|
||||
}
|
||||
|
||||
proxyPrefixExpr := regexp.MustCompile(`^\/*(.*?)\/*$`)
|
||||
*confProxyPrefix = proxyPrefixExpr.ReplaceAllString(*confProxyPrefix, `/$1`)
|
||||
|
||||
if *deprecatedConfGenreSplit != "" && *deprecatedConfGenreSplit != "\n" {
|
||||
confMultiValueGenre = multiValueSetting{Mode: scanner.Delim, Delim: *deprecatedConfGenreSplit}
|
||||
*deprecatedConfGenreSplit = "<deprecated>"
|
||||
}
|
||||
if confMultiValueArtist.Mode == scanner.None && confMultiValueAlbumArtist.Mode > scanner.None {
|
||||
confMultiValueArtist.Mode = confMultiValueAlbumArtist.Mode
|
||||
confMultiValueArtist.Delim = confMultiValueAlbumArtist.Delim
|
||||
}
|
||||
if confMultiValueArtist.Mode != confMultiValueAlbumArtist.Mode {
|
||||
log.Panic("differing multi artist and album artist modes have been tested yet. please set them to be the same")
|
||||
}
|
||||
|
||||
log.Printf("starting gonic v%s\n", gonic.Version)
|
||||
log.Printf("provided config\n")
|
||||
flag.VisitAll(func(f *flag.Flag) {
|
||||
value := strings.ReplaceAll(f.Value.String(), "\n", "")
|
||||
log.Printf(" %-30s %s\n", f.Name, value)
|
||||
})
|
||||
|
||||
tagReader := deps.TagReader
|
||||
|
||||
scannr := scanner.New(
|
||||
ctrlsubsonic.MusicPaths(musicPaths),
|
||||
dbc,
|
||||
map[scanner.Tag]scanner.MultiValueSetting{
|
||||
scanner.Genre: scanner.MultiValueSetting(confMultiValueGenre),
|
||||
scanner.Artist: scanner.MultiValueSetting(confMultiValueArtist),
|
||||
scanner.AlbumArtist: scanner.MultiValueSetting(confMultiValueAlbumArtist),
|
||||
},
|
||||
tagReader,
|
||||
*confExcludePattern,
|
||||
*confScanEmbeddedCover,
|
||||
)
|
||||
podcast := podcast.New(dbc, *confPodcastPath, tagReader)
|
||||
transcoder := transcode.NewCachingTranscoder(
|
||||
transcode.NewFFmpegTranscoder(),
|
||||
cacheDirAudio,
|
||||
*confTranscodeCacheSize,
|
||||
)
|
||||
|
||||
lastfmClientKeySecretFunc := func() (string, string, error) {
|
||||
apiKey, _ := dbc.GetSetting(db.LastFMAPIKey)
|
||||
secret, _ := dbc.GetSetting(db.LastFMSecret)
|
||||
if apiKey == "" || secret == "" {
|
||||
return "", "", fmt.Errorf("not configured")
|
||||
}
|
||||
return apiKey, secret, nil
|
||||
}
|
||||
|
||||
listenbrainzClient := listenbrainz.NewClient()
|
||||
lastfmClient := lastfm.NewClient(lastfmClientKeySecretFunc)
|
||||
|
||||
playlistStore, err := playlist.NewStore(*confPlaylistsPath)
|
||||
if err != nil {
|
||||
log.Panicf("error creating playlists store: %v", err)
|
||||
}
|
||||
|
||||
var jukebx *jukebox.Jukebox
|
||||
if *confJukeboxEnabled {
|
||||
jukebx = jukebox.New()
|
||||
}
|
||||
|
||||
sessKey, err := dbc.GetSetting("session_key")
|
||||
if err != nil {
|
||||
log.Panicf("error getting session key: %v\n", err)
|
||||
}
|
||||
if sessKey == "" {
|
||||
sessKey = string(securecookie.GenerateRandomKey(32))
|
||||
if err := dbc.SetSetting("session_key", sessKey); err != nil {
|
||||
log.Panicf("error setting session key: %v\n", err)
|
||||
}
|
||||
}
|
||||
sessDB := gormstore.New(dbc.DB, []byte(sessKey))
|
||||
sessDB.SessionOpts.HttpOnly = true
|
||||
sessDB.SessionOpts.SameSite = http.SameSiteLaxMode
|
||||
|
||||
artistInfoCache := artistinfocache.New(dbc, lastfmClient)
|
||||
albumInfoCache := albuminfocache.New(dbc, lastfmClient)
|
||||
|
||||
scrobblers := []scrobble.Scrobbler{lastfmClient, listenbrainzClient}
|
||||
|
||||
resolveProxyPath := func(in string) string {
|
||||
url, _ := url.Parse(in)
|
||||
url.Path = path.Join(*confProxyPrefix, url.Path)
|
||||
return url.String()
|
||||
}
|
||||
|
||||
ctrlAdmin, err := ctrladmin.New(dbc, sessDB, scannr, podcast, lastfmClient, resolveProxyPath, ldapConfig, ldapStore)
|
||||
if err != nil {
|
||||
log.Panicf("error creating admin controller: %v\n", err)
|
||||
}
|
||||
ctrlSubsonic, err := ctrlsubsonic.New(dbc, scannr, musicPaths, *defaultMusicPath, *confPodcastPath, cacheDirAudio, cacheDirCovers, jukebx, playlistStore, scrobblers, podcast, transcoder, lastfmClient, artistInfoCache, albumInfoCache, tagReader, resolveProxyPath, ldapConfig, ldapStore)
|
||||
if err != nil {
|
||||
log.Panicf("error creating subsonic controller: %v\n", err)
|
||||
}
|
||||
|
||||
chain := handlerutil.Chain()
|
||||
if *confHTTPLog {
|
||||
chain = handlerutil.Chain(handlerutil.Log)
|
||||
}
|
||||
chain = handlerutil.Chain(
|
||||
chain,
|
||||
handlerutil.BasicCORS,
|
||||
)
|
||||
trim := handlerutil.TrimPathSuffix(".view") // /x.view and /x should match the same
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/admin/", http.StripPrefix("/admin", chain(ctrlAdmin)))
|
||||
mux.Handle("/rest/", http.StripPrefix("/rest", chain(trim(ctrlSubsonic))))
|
||||
mux.Handle("/ping", chain(handlerutil.Message("ok")))
|
||||
mux.Handle("/", chain(http.RedirectHandler(resolveProxyPath("/admin/home"), http.StatusSeeOther)))
|
||||
|
||||
if *confExpvar {
|
||||
mux.Handle("/debug/vars", expvar.Handler())
|
||||
expvar.Publish("stats", expvar.Func(func() any {
|
||||
stats, _ := dbc.Stats()
|
||||
return stats
|
||||
}))
|
||||
}
|
||||
|
||||
var (
|
||||
readTimeout = 5 * time.Second
|
||||
writeTimeout = 5 * time.Second
|
||||
idleTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
if *confPprof {
|
||||
// overwrite global WriteTimeout. in future we should set this only for these handlers
|
||||
// https://github.com/golang/go/issues/62358
|
||||
writeTimeout = 0
|
||||
|
||||
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
||||
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
||||
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
||||
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
||||
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
||||
}
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
errgrp, ctx := errgroup.WithContext(ctx)
|
||||
|
||||
errgrp.Go(func() error {
|
||||
defer logJob("http")()
|
||||
|
||||
server := &http.Server{
|
||||
Addr: *confListenAddr,
|
||||
ReadTimeout: readTimeout, WriteTimeout: writeTimeout, IdleTimeout: idleTimeout,
|
||||
Handler: mux,
|
||||
}
|
||||
errgrp.Go(func() error {
|
||||
<-ctx.Done()
|
||||
return server.Shutdown(context.Background())
|
||||
})
|
||||
if *confTLSCert != "" && *confTLSKey != "" {
|
||||
return server.ListenAndServeTLS(*confTLSCert, *confTLSKey)
|
||||
}
|
||||
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
if !*confScanWatcher {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer logJob("scan watcher")()
|
||||
|
||||
return scannr.ExecuteWatch(ctx)
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
if jukebx == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer logJob("jukebox")()
|
||||
|
||||
extraArgs, _ := shlex.Split(*confJukeboxMPVExtraArgs)
|
||||
jukeboxTempDir := filepath.Join(*confCachePath, "gonic-jukebox")
|
||||
if err := os.RemoveAll(jukeboxTempDir); err != nil {
|
||||
return fmt.Errorf("remove jubebox tmp dir: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(jukeboxTempDir, os.ModePerm); err != nil {
|
||||
return fmt.Errorf("create tmp sock file: %w", err)
|
||||
}
|
||||
sockPath := filepath.Join(jukeboxTempDir, "sock")
|
||||
if err := jukebx.Start(ctx, sockPath, extraArgs); err != nil {
|
||||
return fmt.Errorf("start jukebox: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
defer logJob("session clean")()
|
||||
|
||||
ctxTick(ctx, 10*time.Minute, func() {
|
||||
sessDB.Cleanup()
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
defer logJob("podcast refresh")()
|
||||
|
||||
ctxTick(ctx, 1*time.Hour, func() {
|
||||
if err := podcast.RefreshPodcasts(); err != nil {
|
||||
log.Printf("failed to refresh some feeds: %s", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
defer logJob("podcast download")()
|
||||
|
||||
ctxTick(ctx, 5*time.Second, func() {
|
||||
if err := podcast.DownloadTick(); err != nil {
|
||||
log.Printf("failed to download podcast: %s", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
if *confPodcastPurgeAgeDays == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer logJob("podcast purge")()
|
||||
|
||||
ctxTick(ctx, 24*time.Hour, func() {
|
||||
if err := podcast.PurgeOldPodcasts(time.Duration(*confPodcastPurgeAgeDays) * 24 * time.Hour); err != nil {
|
||||
log.Printf("error purging old podcasts: %v", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
if *confTranscodeEjectInterval == 0 || *confTranscodeCacheSize == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer logJob("transcode cache eject")()
|
||||
|
||||
ctxTick(ctx, time.Duration(*confTranscodeEjectInterval)*time.Minute, func() {
|
||||
if err := transcoder.CacheEject(); err != nil {
|
||||
log.Printf("error ejecting transcode cache: %v", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
if *confScanIntervalMins == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer logJob("scan timer")()
|
||||
|
||||
ctxTick(ctx, time.Duration(*confScanIntervalMins)*time.Minute, func() {
|
||||
if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
|
||||
log.Printf("error scanning: %v", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
if _, _, err := lastfmClientKeySecretFunc(); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer logJob("refresh artist info")()
|
||||
|
||||
ctxTick(ctx, 8*time.Second, func() {
|
||||
if err := artistInfoCache.Refresh(); err != nil {
|
||||
log.Printf("error in artist info cache: %v", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
errgrp.Go(func() error {
|
||||
if !*confScanAtStart {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer logJob("scan at start")()
|
||||
|
||||
if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
|
||||
log.Printf("error scanning on start: %v", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err := errgrp.Wait(); err != nil {
|
||||
log.Panic(err)
|
||||
}
|
||||
|
||||
fmt.Println("shutdown complete")
|
||||
}
|
||||
|
||||
const pathAliasSep = "->"
|
||||
|
||||
type (
|
||||
pathAliases []pathAlias
|
||||
pathAlias struct{ alias, path string }
|
||||
)
|
||||
|
||||
func (pa pathAliases) String() string {
|
||||
var strs []string
|
||||
for _, p := range pa {
|
||||
if p.alias != "" {
|
||||
strs = append(strs, fmt.Sprintf("%s %s %s", p.alias, pathAliasSep, p.path))
|
||||
continue
|
||||
}
|
||||
strs = append(strs, p.path)
|
||||
}
|
||||
return strings.Join(strs, ", ")
|
||||
}
|
||||
|
||||
func (pa *pathAliases) Set(value string) error {
|
||||
if name, path, ok := strings.Cut(value, pathAliasSep); ok {
|
||||
*pa = append(*pa, pathAlias{alias: name, path: path})
|
||||
return nil
|
||||
}
|
||||
*pa = append(*pa, pathAlias{path: value})
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePath(p string) (string, error) {
|
||||
if p == "" {
|
||||
return "", errors.New("path can't be empty")
|
||||
}
|
||||
if _, err := os.Stat(p); os.IsNotExist(err) {
|
||||
return "", errors.New("path does not exist, please provide one")
|
||||
}
|
||||
p, err := filepath.Abs(p)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("make absolute: %w", err)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
type multiValueSetting scanner.MultiValueSetting
|
||||
|
||||
func (mvs multiValueSetting) String() string {
|
||||
switch mvs.Mode {
|
||||
case scanner.Delim:
|
||||
return fmt.Sprintf("delim(%s)", mvs.Delim)
|
||||
case scanner.Multi:
|
||||
return "multi"
|
||||
default:
|
||||
return "none"
|
||||
}
|
||||
}
|
||||
|
||||
func (mvs *multiValueSetting) Set(value string) error {
|
||||
mode, delim, _ := strings.Cut(value, " ")
|
||||
switch mode {
|
||||
case "delim":
|
||||
if delim == "" {
|
||||
return fmt.Errorf("no delimiter provided for delimiter mode")
|
||||
}
|
||||
mvs.Mode = scanner.Delim
|
||||
mvs.Delim = delim
|
||||
case "multi":
|
||||
mvs.Mode = scanner.Multi
|
||||
case "none":
|
||||
default:
|
||||
return fmt.Errorf(`unknown multi value mode %q. should be "none" | "multi" | "delim <delim>"`, mode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func logJob(jobName string) func() {
|
||||
log.Printf("starting job %q", jobName)
|
||||
return func() { log.Printf("stopped job %q", jobName) }
|
||||
}
|
||||
|
||||
func ctxTick(ctx context.Context, interval time.Duration, f func()) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
f()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
# This is the gonic server system-wide configuration file. For other
|
||||
# administrative and per user settings go to the web UI.
|
||||
#
|
||||
# The strategy used for options in the default config shipped with gonic is to
|
||||
# specify options with their default value where possible, and leave optional
|
||||
# ones commented. Uncommented options override the default value. Options that
|
||||
# are mandatory and need setting before first run have a placeholder for their
|
||||
# values in <angle brackets>.
|
||||
|
||||
# Interface and port to listen on. Defaults to 0.0.0.0:4747
|
||||
listen-addr 127.0.0.1:4747
|
||||
|
||||
# HTTP(S) request logging
|
||||
#http-log true
|
||||
# URL path prefix to use if behind reverse proxy
|
||||
#proxy-prefix <prefix>
|
||||
|
||||
# Secure connection settings. Recommended to set up unless gonic sits behind an
|
||||
# SSL enabled reverse proxy server. Disabled by default.
|
||||
#tls-cert <path to TLS certificate>
|
||||
#tls-key <path to TLS private key>
|
||||
|
||||
# gonic's internal state database location
|
||||
db-path /var/lib/gonic/gonic.db
|
||||
|
||||
# Path to music files. Must be specified at least once, but can be specified
|
||||
# multiple times if the collection is split into different
|
||||
# directories. E.g.:
|
||||
# music-path /srv/audio/music
|
||||
music-path <path to your music dir>
|
||||
|
||||
# Path to downloaded podcast files. Must be specified. E.g.:
|
||||
# podcast-path /var/cache/podcast
|
||||
podcast-path <path to your podcasts dir>
|
||||
|
||||
# gonic manages playlists as m3u files. This way users can also edit these
|
||||
# playlists themselves or add custom ones via other tools. Items in the
|
||||
# directory should be placed in subdirectories matching user IDs in the
|
||||
# database, in the format `<userid>/<name>.m3u`. For example the admin user could
|
||||
# have 1/my-playlist.m3u. E.g.:
|
||||
# playlists-path /srv/audio/playlists
|
||||
playlists-path <path to your m3u playlist dir>
|
||||
|
||||
# Age (in days) to purge podcast episodes if not accessed. Disabled by default.
|
||||
#podcast-purge-age 0
|
||||
|
||||
# Directory where transcoded audio files and covers are stored. It's safe to
|
||||
# delete contents periodically (see tmpfilesd configuration), as it will be
|
||||
# regenerated.
|
||||
cache-path /var/cache/gonic
|
||||
|
||||
# Option to eject least recently used items from transcode cache.
|
||||
#transcode-cache-size 5000 # in Mb (0 = no limit)
|
||||
#transcode-eject-interval 1440 # in minutes (0 = never eject)
|
||||
|
||||
# Interval (in minutes) to check for new music. Default: don't scan
|
||||
#scan-interval 0
|
||||
#scan-at-start-enabled false
|
||||
#scan-watcher-enabled false
|
||||
#jukebox-enabled false
|
||||
#jukebox-mpv-extra-args <extra command line arguments to pass to the jukebox mpv daemon>
|
||||
|
||||
# Metadata multi-value handling
|
||||
# gonic supports parsing mult-valued tags in the metadata thus assigning a song
|
||||
# to several genres or album artists. This improves search and reduces clutter
|
||||
# in the artist/genre listing. Accepted options are:
|
||||
# multi: gonic will explicitly look for multi value fields the audio metadata
|
||||
# delim <delimiter character>: gonic will look at the regular audio metadata
|
||||
# fields like "genre" or "album_artist", but split
|
||||
# them on a delimiter. For example to split on
|
||||
# semicolon set the option value to be "delim ;"
|
||||
# none: default setting, gonic won't attempt to do any multi value parsing
|
||||
#multi-value-genre none
|
||||
#multi-value-album-artist none
|
||||
@@ -1,19 +0,0 @@
|
||||
[Unit]
|
||||
Description=gonic service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=gonic
|
||||
Group=gonic
|
||||
|
||||
StateDirectory=gonic
|
||||
CacheDirectory=gonic
|
||||
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
ExecStart=/usr/local/bin/gonic -config-path /etc/gonic/config
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -1 +0,0 @@
|
||||
u gonic - "user for gonic daemon"
|
||||
@@ -1 +0,0 @@
|
||||
d /var/cache/gonic 0775 gonic gonic 7d
|
||||
@@ -1,662 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"mime"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
|
||||
// TODO: remove this dep
|
||||
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
|
||||
)
|
||||
|
||||
type DB struct {
|
||||
*gorm.DB
|
||||
}
|
||||
|
||||
func New(path string, opts url.Values, logQueries bool) (*DB, error) {
|
||||
u := url.URL{
|
||||
Scheme: "file",
|
||||
Opaque: path,
|
||||
RawQuery: opts.Encode(),
|
||||
}
|
||||
|
||||
db, err := gorm.Open("sqlite3", u.String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("with gorm: %w", err)
|
||||
}
|
||||
|
||||
db.SetLogger(log.New(os.Stdout, "gorm ", 0))
|
||||
if logQueries {
|
||||
db.LogMode(true)
|
||||
}
|
||||
|
||||
db.DB().SetMaxOpenConns(4)
|
||||
|
||||
return &DB{DB: db}, nil
|
||||
}
|
||||
|
||||
func NewMock(opts url.Values) (*DB, error) {
|
||||
d, err := New(":memory:", opts, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// in-memory databases can't be shared across multiple connections
|
||||
d.DB.DB().SetMaxOpenConns(1)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (db *DB) InsertBulkLeftMany(table string, head []string, left int, col []int) error {
|
||||
rows := make([][]any, len(col))
|
||||
for i, c := range col {
|
||||
rows[i] = []any{c}
|
||||
}
|
||||
return db.InsertBulkLeftManyRows(table, head, left, rows)
|
||||
}
|
||||
|
||||
func (db *DB) InsertBulkLeftManyRows(table string, head []string, left int, rows [][]any) error {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
tail := len(head) - 1
|
||||
placeholder := "(?" + strings.Repeat(", ?", tail) + ")"
|
||||
|
||||
placeholders := make([]string, len(rows))
|
||||
values := make([]any, 0, len(rows)*len(head))
|
||||
for i, r := range rows {
|
||||
if len(r) != tail {
|
||||
return fmt.Errorf("row %d has %d values, expected %d", i, len(r), tail)
|
||||
}
|
||||
placeholders[i] = placeholder
|
||||
values = append(values, left)
|
||||
values = append(values, r...)
|
||||
}
|
||||
q := fmt.Sprintf("INSERT OR IGNORE INTO %q (%s) VALUES %s",
|
||||
table,
|
||||
strings.Join(head, ", "),
|
||||
strings.Join(placeholders, ", "),
|
||||
)
|
||||
return db.Exec(q, values...).Error
|
||||
}
|
||||
|
||||
type Stats struct {
|
||||
Folders, Albums, Artists, AlbumArtists, Tracks, InternetRadioStations, Podcasts uint
|
||||
}
|
||||
|
||||
func (db *DB) Stats() (Stats, error) {
|
||||
var stats Stats
|
||||
db.Model(Album{}).Count(&stats.Folders)
|
||||
db.Model(AlbumArtist{}).Group("album_id").Count(&stats.Albums)
|
||||
db.Model(TrackArtist{}).Group("artist_id").Count(&stats.Artists)
|
||||
db.Model(AlbumArtist{}).Group("artist_id").Count(&stats.AlbumArtists)
|
||||
db.Model(Track{}).Count(&stats.Tracks)
|
||||
db.Model(InternetRadioStation{}).Count(&stats.InternetRadioStations)
|
||||
db.Model(Podcast{}).Count(&stats.Podcasts)
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (db *DB) GetUserByID(id int) *User {
|
||||
var user User
|
||||
err := db.
|
||||
Where("id=?", id).
|
||||
First(&user).
|
||||
Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return &user
|
||||
}
|
||||
|
||||
func (db *DB) GetUserByName(name string) *User {
|
||||
var user User
|
||||
err := db.
|
||||
Where("name=?", name).
|
||||
First(&user).
|
||||
Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return &user
|
||||
}
|
||||
|
||||
func (db *DB) Begin() *DB {
|
||||
return &DB{DB: db.DB.Begin()}
|
||||
}
|
||||
|
||||
func (db *DB) Transaction(cb func(*DB) error) error {
|
||||
return db.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return cb(&DB{DB: tx})
|
||||
})
|
||||
}
|
||||
|
||||
func (db *DB) TransactionChunked(data []int64, cb func(*DB, []int64) error) error {
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
// https://sqlite.org/limits.html
|
||||
const size = 999
|
||||
for i := 0; i < len(data); i += size {
|
||||
end := min(i+size, len(data))
|
||||
if err := db.Transaction(func(tx *DB) error {
|
||||
return cb(tx, data[i:end])
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type SettingKey string
|
||||
|
||||
const (
|
||||
LastFMAPIKey SettingKey = "lastfm_api_key" //nolint:gosec
|
||||
LastFMSecret SettingKey = "lastfm_secret"
|
||||
LastScanTime SettingKey = "last_scan_time"
|
||||
)
|
||||
|
||||
func (db *DB) GetSetting(key SettingKey) (string, error) {
|
||||
var setting Setting
|
||||
if err := db.Where("key=?", key).First(&setting).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", err
|
||||
}
|
||||
return setting.Value, nil
|
||||
}
|
||||
|
||||
func (db *DB) SetSetting(key SettingKey, value string) error {
|
||||
return db.
|
||||
Where("key=?", key).
|
||||
Assign(Setting{Key: key, Value: value}).
|
||||
FirstOrCreate(&Setting{}).
|
||||
Error
|
||||
}
|
||||
|
||||
type Artist struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
Name string `gorm:"not null; unique_index"`
|
||||
NameUDec string `sql:"default: null"`
|
||||
Albums []*Album `gorm:"many2many:album_artists"`
|
||||
AlbumCount int `sql:"-"`
|
||||
Appearances []*Album `gorm:"many2many:artist_appearances"`
|
||||
AppearanceCount int `sql:"-"`
|
||||
ArtistStar *ArtistStar
|
||||
ArtistRating *ArtistRating
|
||||
AverageRating float64 `sql:"default: null"`
|
||||
Info *ArtistInfo `gorm:"foreignkey:id"`
|
||||
}
|
||||
|
||||
func (a *Artist) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Artist, Value: a.ID}
|
||||
}
|
||||
|
||||
func (a *Artist) IndexName() string {
|
||||
if len(a.NameUDec) > 0 {
|
||||
return a.NameUDec
|
||||
}
|
||||
return a.Name
|
||||
}
|
||||
|
||||
type Genre struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
Name string `gorm:"not null; unique_index"`
|
||||
AlbumCount int `sql:"-"`
|
||||
TrackCount int `sql:"-"`
|
||||
}
|
||||
|
||||
// AudioFile is used to avoid some duplication in handlers_raw.go
|
||||
// between Track and Podcast
|
||||
type AudioFile interface {
|
||||
Ext() string
|
||||
MIME() string
|
||||
AudioFilename() string
|
||||
AudioBitrate() int
|
||||
AudioLength() int
|
||||
}
|
||||
|
||||
type Track struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Filename string `gorm:"not null; unique_index:idx_folder_filename" sql:"default: null"`
|
||||
FilenameUDec string `sql:"default: null"`
|
||||
Album *Album
|
||||
AlbumID int `gorm:"not null; unique_index:idx_folder_filename" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
Artists []*Artist `gorm:"many2many:track_artists"`
|
||||
Contributors []*TrackContributor `gorm:"foreignkey:track_id"`
|
||||
Genres []*Genre `gorm:"many2many:track_genres"`
|
||||
Size int `sql:"default: null"`
|
||||
Length int `sql:"default: null"`
|
||||
Bitrate int `sql:"default: null"`
|
||||
TagTitle string `sql:"default: null"`
|
||||
TagTitleUDec string `sql:"default: null"`
|
||||
TagTrackArtist string `sql:"default: null"`
|
||||
TagTrackNumber int `sql:"default: null"`
|
||||
TagDiscNumber int `sql:"default: null"`
|
||||
TagBrainzID string `sql:"default: null"`
|
||||
TagLyrics string `sql:"default: null"`
|
||||
TagYear int `sql:"default: null"`
|
||||
|
||||
ReplayGainTrackGain float32
|
||||
ReplayGainTrackPeak float32
|
||||
ReplayGainAlbumGain float32
|
||||
ReplayGainAlbumPeak float32
|
||||
|
||||
HasEmbeddedCover bool
|
||||
|
||||
TrackStar *TrackStar
|
||||
TrackRating *TrackRating
|
||||
AverageRating float64 `sql:"default: null"`
|
||||
}
|
||||
|
||||
func (t *Track) AudioLength() int { return t.Length }
|
||||
func (t *Track) AudioBitrate() int { return t.Bitrate }
|
||||
|
||||
func (t *Track) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Track, Value: t.ID}
|
||||
}
|
||||
|
||||
func (t *Track) AlbumSID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Album, Value: t.AlbumID}
|
||||
}
|
||||
|
||||
func (t *Track) Ext() string {
|
||||
return filepath.Ext(t.Filename)
|
||||
}
|
||||
|
||||
func (t *Track) AudioFilename() string {
|
||||
return t.Filename
|
||||
}
|
||||
|
||||
func (t *Track) MIME() string {
|
||||
return mime.TypeByExtension(filepath.Ext(t.Filename))
|
||||
}
|
||||
|
||||
func (t *Track) AbsPath() string {
|
||||
if t.Album == nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(
|
||||
t.Album.RootDir,
|
||||
t.Album.LeftPath,
|
||||
t.Album.RightPath,
|
||||
t.Filename,
|
||||
)
|
||||
}
|
||||
|
||||
func (t *Track) RelPath() string {
|
||||
if t.Album == nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(
|
||||
t.Album.LeftPath,
|
||||
t.Album.RightPath,
|
||||
t.Filename,
|
||||
)
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
Name string `gorm:"not null; unique_index" sql:"default: null"`
|
||||
Password string `sql:"default: null"`
|
||||
LastFMSession string `sql:"default: null"`
|
||||
ListenBrainzURL string `sql:"default: null"`
|
||||
ListenBrainzToken string `sql:"default: null"`
|
||||
IsAdmin bool `sql:"default: null"`
|
||||
Avatar []byte `sql:"default: null"`
|
||||
}
|
||||
|
||||
type Setting struct {
|
||||
Key SettingKey `gorm:"not null; primary_key; auto_increment:false" sql:"default: null"`
|
||||
Value string `sql:"default: null"`
|
||||
}
|
||||
|
||||
type Play struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
User *User
|
||||
UserID int `gorm:"not null; index" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
Album *Album
|
||||
AlbumID int `gorm:"not null; index" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
Time time.Time `sql:"default: null"`
|
||||
Count int
|
||||
Length int
|
||||
}
|
||||
|
||||
type Album struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
ModifiedAt time.Time
|
||||
LeftPath string `gorm:"unique_index:idx_album_abs_path"`
|
||||
RightPath string `gorm:"not null; unique_index:idx_album_abs_path" sql:"default: null"`
|
||||
RightPathUDec string `sql:"default: null"`
|
||||
Parent *Album
|
||||
ParentID int `sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
RootDir string `gorm:"unique_index:idx_album_abs_path" sql:"default: null"`
|
||||
Genres []*Genre `gorm:"many2many:album_genres"`
|
||||
Cover string `sql:"default: null"`
|
||||
EmbeddedCoverTrackID *int `sql:"default: null; type:int REFERENCES tracks(id) ON DELETE SET NULL"`
|
||||
Artists []*Artist `gorm:"many2many:album_artists"`
|
||||
TagTitle string `sql:"default: null"`
|
||||
TagAlbumArtist string // display purposes only
|
||||
TagTitleUDec string `sql:"default: null"`
|
||||
TagBrainzID string `sql:"default: null"`
|
||||
TagYear int `sql:"default: null"`
|
||||
TagCompilation bool `sql:"default: null"`
|
||||
TagReleaseType string `sql:"default: null"`
|
||||
Tracks []*Track
|
||||
ChildCount int `sql:"-"`
|
||||
Duration int `sql:"-"`
|
||||
AlbumStar *AlbumStar
|
||||
AlbumRating *AlbumRating
|
||||
AverageRating float64 `sql:"default: null"`
|
||||
Play *Play
|
||||
DiscTitles []*AlbumDiscTitle
|
||||
}
|
||||
|
||||
func (a *Album) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Album, Value: a.ID}
|
||||
}
|
||||
|
||||
func (a *Album) ParentSID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Album, Value: a.ParentID}
|
||||
}
|
||||
|
||||
func (a *Album) EmbeddedCoverTrackSID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Track, Value: *a.EmbeddedCoverTrackID}
|
||||
}
|
||||
|
||||
func (a *Album) IndexRightPath() string {
|
||||
if len(a.RightPathUDec) > 0 {
|
||||
return a.RightPathUDec
|
||||
}
|
||||
return a.RightPath
|
||||
}
|
||||
|
||||
type PlayQueue struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
User *User
|
||||
UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
Current string
|
||||
Position int
|
||||
ChangedBy string
|
||||
Items string
|
||||
}
|
||||
|
||||
func (p *PlayQueue) CurrentSID() *specid.ID {
|
||||
id, _ := specid.New(p.Current)
|
||||
return &id
|
||||
}
|
||||
|
||||
func (p *PlayQueue) GetItems() []specid.ID {
|
||||
return splitIDs(p.Items, ",")
|
||||
}
|
||||
|
||||
func (p *PlayQueue) SetItems(items []specid.ID) {
|
||||
p.Items = join(items, ",")
|
||||
}
|
||||
|
||||
type TranscodePreference struct {
|
||||
UserID int `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
Client string `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null"`
|
||||
Profile string `gorm:"not null" sql:"default: null"`
|
||||
}
|
||||
|
||||
type AlbumArtist struct {
|
||||
AlbumID int `gorm:"not null; unique_index:idx_album_id_artist_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
ArtistID int `gorm:"not null; unique_index:idx_album_id_artist_id" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
|
||||
}
|
||||
|
||||
type TrackArtist struct {
|
||||
TrackID int `gorm:"not null; unique_index:idx_track_id_artist_id" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
|
||||
ArtistID int `gorm:"not null; unique_index:idx_track_id_artist_id" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
|
||||
}
|
||||
|
||||
type ContributorRole string
|
||||
|
||||
const (
|
||||
ContributorRoleComposer ContributorRole = "composer"
|
||||
ContributorRoleLyricist ContributorRole = "lyricist"
|
||||
ContributorRoleRemixer ContributorRole = "remixer"
|
||||
ContributorRoleConductor ContributorRole = "conductor"
|
||||
ContributorRoleProducer ContributorRole = "producer"
|
||||
ContributorRoleArranger ContributorRole = "arranger"
|
||||
)
|
||||
|
||||
type TrackContributor struct {
|
||||
TrackID int `gorm:"not null; unique_index:idx_track_contributor" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
|
||||
ArtistID int `gorm:"not null; unique_index:idx_track_contributor" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
|
||||
Role ContributorRole `gorm:"not null; unique_index:idx_track_contributor" sql:"default: null"`
|
||||
Artist *Artist
|
||||
}
|
||||
|
||||
type ArtistAppearances struct {
|
||||
ArtistID int `gorm:"not null; unique_index:idx_artist_id_album_id" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
|
||||
AlbumID int `gorm:"not null; unique_index:idx_artist_id_album_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
}
|
||||
|
||||
type TrackGenre struct {
|
||||
TrackID int `gorm:"not null; unique_index:idx_track_id_genre_id" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
|
||||
GenreID int `gorm:"not null; unique_index:idx_track_id_genre_id" sql:"default: null; type:int REFERENCES genres(id) ON DELETE CASCADE"`
|
||||
}
|
||||
|
||||
type AlbumGenre struct {
|
||||
AlbumID int `gorm:"not null; unique_index:idx_album_id_genre_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
GenreID int `gorm:"not null; unique_index:idx_album_id_genre_id" sql:"default: null; type:int REFERENCES genres(id) ON DELETE CASCADE"`
|
||||
}
|
||||
|
||||
type AlbumDiscTitle struct {
|
||||
AlbumID int `gorm:"not null; unique_index:idx_album_disc" sql:"type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
DiscNumber int `gorm:"not null; unique_index:idx_album_disc"`
|
||||
Title string `gorm:"not null"`
|
||||
}
|
||||
|
||||
type AlbumStar struct {
|
||||
UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
AlbumID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
StarDate time.Time
|
||||
}
|
||||
|
||||
type AlbumRating struct {
|
||||
UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
AlbumID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
|
||||
}
|
||||
|
||||
type ArtistStar struct {
|
||||
UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
ArtistID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
|
||||
StarDate time.Time
|
||||
}
|
||||
|
||||
type ArtistRating struct {
|
||||
UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
ArtistID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
|
||||
Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
|
||||
}
|
||||
|
||||
type TrackStar struct {
|
||||
UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
TrackID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
|
||||
StarDate time.Time
|
||||
}
|
||||
|
||||
type TrackRating struct {
|
||||
UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
TrackID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
|
||||
Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
|
||||
}
|
||||
|
||||
type PodcastAutoDownload string
|
||||
|
||||
const (
|
||||
PodcastAutoDownloadLatest PodcastAutoDownload = "latest"
|
||||
PodcastAutoDownloadNone PodcastAutoDownload = "none"
|
||||
)
|
||||
|
||||
type Podcast struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
UpdatedAt time.Time
|
||||
ModifiedAt time.Time
|
||||
URL string
|
||||
Title string
|
||||
Description string
|
||||
ImageURL string
|
||||
Image string
|
||||
Error string
|
||||
Episodes []*PodcastEpisode
|
||||
AutoDownload PodcastAutoDownload
|
||||
RootDir string
|
||||
Author string
|
||||
}
|
||||
|
||||
func (p *Podcast) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Podcast, Value: p.ID}
|
||||
}
|
||||
|
||||
type PodcastEpisodeStatus string
|
||||
|
||||
const (
|
||||
PodcastEpisodeStatusDownloading PodcastEpisodeStatus = "downloading"
|
||||
PodcastEpisodeStatusSkipped PodcastEpisodeStatus = "skipped"
|
||||
PodcastEpisodeStatusDeleted PodcastEpisodeStatus = "deleted"
|
||||
PodcastEpisodeStatusCompleted PodcastEpisodeStatus = "completed"
|
||||
PodcastEpisodeStatusError PodcastEpisodeStatus = "error"
|
||||
)
|
||||
|
||||
type PodcastEpisode struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
ModifiedAt time.Time
|
||||
PodcastID int `gorm:"not null" sql:"default: null; type:int REFERENCES podcasts(id) ON DELETE CASCADE"`
|
||||
Title string
|
||||
Description string
|
||||
PublishDate *time.Time
|
||||
AudioURL string
|
||||
Bitrate int
|
||||
Length int
|
||||
Size int
|
||||
Filename string
|
||||
Status PodcastEpisodeStatus
|
||||
Error string
|
||||
Podcast *Podcast
|
||||
Artist string
|
||||
Album string
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) AudioLength() int { return pe.Length }
|
||||
func (pe *PodcastEpisode) AudioBitrate() int { return pe.Bitrate }
|
||||
|
||||
func (pe *PodcastEpisode) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.PodcastEpisode, Value: pe.ID}
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) PodcastSID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Podcast, Value: pe.PodcastID}
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) AudioFilename() string {
|
||||
return pe.Filename
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) Ext() string {
|
||||
return filepath.Ext(pe.Filename)
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) MIME() string {
|
||||
return mime.TypeByExtension(filepath.Ext(pe.Filename))
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) AbsPath() string {
|
||||
if pe.Podcast == nil || pe.Podcast.RootDir == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(pe.Podcast.RootDir, pe.Filename)
|
||||
}
|
||||
|
||||
type Bookmark struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
User *User
|
||||
UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
Position int
|
||||
Comment string
|
||||
EntryIDType string
|
||||
EntryID int
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type InternetRadioStation struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
StreamURL string
|
||||
Name string
|
||||
HomepageURL string
|
||||
}
|
||||
|
||||
func (ir *InternetRadioStation) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.InternetRadioStation, Value: ir.ID}
|
||||
}
|
||||
|
||||
func (ir *InternetRadioStation) AbsPath() string {
|
||||
return ir.StreamURL
|
||||
}
|
||||
|
||||
type ArtistInfo struct {
|
||||
ID int `gorm:"primary_key" sql:"type:int REFERENCES artists(id) ON DELETE CASCADE"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time `gorm:"index"`
|
||||
Biography string
|
||||
MusicBrainzID string
|
||||
LastFMURL string
|
||||
ImageURL string
|
||||
SimilarArtists string
|
||||
TopTracks string
|
||||
}
|
||||
|
||||
func (p *ArtistInfo) GetSimilarArtists() []string { return strings.Split(p.SimilarArtists, ";") }
|
||||
func (p *ArtistInfo) SetSimilarArtists(items []string) { p.SimilarArtists = strings.Join(items, ";") }
|
||||
|
||||
func (p *ArtistInfo) GetTopTracks() []string { return strings.Split(p.TopTracks, ";") }
|
||||
func (p *ArtistInfo) SetTopTracks(items []string) { p.TopTracks = strings.Join(items, ";") }
|
||||
|
||||
type AlbumInfo struct {
|
||||
ID int `gorm:"primary_key" sql:"type:int REFERENCES albums(id) ON DELETE CASCADE"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time `gorm:"index"`
|
||||
Notes string
|
||||
MusicBrainzID string
|
||||
LastFMURL string
|
||||
}
|
||||
|
||||
func splitIDs(in, sep string) []specid.ID {
|
||||
if in == "" {
|
||||
return []specid.ID{}
|
||||
}
|
||||
parts := strings.Split(in, sep)
|
||||
ret := make([]specid.ID, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
id, _ := specid.New(p)
|
||||
ret = append(ret, id)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func join[T fmt.Stringer](in []T, sep string) string {
|
||||
if in == nil {
|
||||
return ""
|
||||
}
|
||||
strs := make([]string, 0, len(in))
|
||||
for _, id := range in {
|
||||
strs = append(strs, id.String())
|
||||
}
|
||||
return strings.Join(strs, sep)
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"go.senan.xyz/gonic/deps"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
log.SetOutput(io.Discard)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestGetSetting(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key := SettingKey(randKey())
|
||||
value := "howdy"
|
||||
|
||||
testDB, err := NewMock(deps.DBDriverOptions())
|
||||
if err != nil {
|
||||
t.Fatalf("error creating db: %v", err)
|
||||
}
|
||||
if err := testDB.Migrate(MigrationContext{}); err != nil {
|
||||
t.Fatalf("error migrating db: %v", err)
|
||||
}
|
||||
|
||||
require.NoError(t, testDB.SetSetting(key, value))
|
||||
|
||||
actual, err := testDB.GetSetting(key)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, value, actual)
|
||||
|
||||
require.NoError(t, testDB.SetSetting(key, value))
|
||||
actual, err = testDB.GetSetting(key)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, value, actual)
|
||||
}
|
||||
|
||||
func randKey() string {
|
||||
letters := []rune("abcdef0123456789")
|
||||
b := make([]rune, 16)
|
||||
for i := range b {
|
||||
b[i] = letters[rand.Intn(len(letters))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -1,906 +0,0 @@
|
||||
//nolint:goerr113
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"go.senan.xyz/gonic/fileutil"
|
||||
"go.senan.xyz/gonic/playlist"
|
||||
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
|
||||
"gopkg.in/gormigrate.v1"
|
||||
)
|
||||
|
||||
type MigrationContext struct {
|
||||
Production bool
|
||||
DBPath string
|
||||
OriginalMusicPath string
|
||||
PlaylistsPath string
|
||||
PodcastsPath string
|
||||
}
|
||||
|
||||
func (db *DB) Migrate(ctx MigrationContext) error {
|
||||
options := &gormigrate.Options{
|
||||
TableName: "migrations",
|
||||
IDColumnName: "id",
|
||||
IDColumnSize: 255,
|
||||
UseTransaction: false,
|
||||
}
|
||||
|
||||
// $ date '+%Y%m%d%H%M'
|
||||
migrations := []*gormigrate.Migration{
|
||||
construct(ctx, "202002192100", migrateInitSchema),
|
||||
construct(ctx, "202002192019", migrateCreateInitUser),
|
||||
construct(ctx, "202002192222", migrateMergePlaylist),
|
||||
construct(ctx, "202003111222", migrateCreateTranscode),
|
||||
construct(ctx, "202003121330", migrateAddGenre),
|
||||
construct(ctx, "202003241509", migrateUpdateTranscodePrefIDX),
|
||||
construct(ctx, "202004302006", migrateAddAlbumIDX),
|
||||
construct(ctx, "202012151806", migrateMultiGenre),
|
||||
construct(ctx, "202101081149", migrateListenBrainz),
|
||||
construct(ctx, "202101111537", migratePodcast),
|
||||
construct(ctx, "202102032210", migrateBookmarks),
|
||||
construct(ctx, "202102191448", migratePodcastAutoDownload),
|
||||
construct(ctx, "202110041330", migrateAlbumCreatedAt),
|
||||
construct(ctx, "202111021951", migrateAlbumRootDir),
|
||||
construct(ctx, "202201042236", migrateArtistGuessedFolder),
|
||||
construct(ctx, "202202092013", migrateArtistCover),
|
||||
construct(ctx, "202202121809", migrateAlbumRootDirAgain),
|
||||
construct(ctx, "202202241218", migratePublicPlaylist),
|
||||
construct(ctx, "202204270903", migratePodcastDropUserID),
|
||||
construct(ctx, "202206011628", migrateInternetRadioStations),
|
||||
construct(ctx, "202206101425", migrateUser),
|
||||
construct(ctx, "202207251148", migrateStarRating),
|
||||
construct(ctx, "202211111057", migratePlaylistsQueuesToFullID),
|
||||
construct(ctx, "202304221528", migratePlaylistsToM3U),
|
||||
construct(ctx, "202305301718", migratePlayCountToLength),
|
||||
construct(ctx, "202307281628", migrateAlbumArtistsMany2Many),
|
||||
construct(ctx, "202309070009", migrateDeleteArtistCoverField),
|
||||
construct(ctx, "202309131743", migrateArtistInfo),
|
||||
construct(ctx, "202309161411", migratePlaylistsPaths),
|
||||
construct(ctx, "202310252205", migrateAlbumTagArtistString),
|
||||
construct(ctx, "202310281803", migrateTrackArtists),
|
||||
construct(ctx, "202311062259", migrateArtistAppearances),
|
||||
construct(ctx, "202311072309", migrateAlbumInfo),
|
||||
construct(ctx, "202311082304", migrateTemporaryDisplayAlbumArtist),
|
||||
construct(ctx, "202312110003", migrateAddExtraIndexes),
|
||||
construct(ctx, "202405301140", migrateAddReplayGainFields),
|
||||
construct(ctx, "202501152035", migrateTrackAddIndexOnAlbumID),
|
||||
construct(ctx, "202501152036", migrateAlbumAddIndexOnParentID),
|
||||
construct(ctx, "202502012036", migratePodcastEpisode),
|
||||
construct(ctx, "202504132036", migratePodcast),
|
||||
construct(ctx, "202505211202", migrateTrackAddIndexOnBrainzID),
|
||||
construct(ctx, "202505262025", migrateAlbumAddIndexOnBrainzID),
|
||||
construct(ctx, "202507062103", migrateAlbumCompilationReleaseType),
|
||||
construct(ctx, "202508261102", migrateAddLyrics),
|
||||
construct(ctx, "202509291741", migrateAddAlbumEmbeddedCoverTrackID),
|
||||
construct(ctx, "202509301448", migrateAddTrackEmbeddedCover),
|
||||
construct(ctx, "202512021147", migrateAlbumAddIndexOnCreatedAt),
|
||||
construct(ctx, "202601201000", migrateAddAlbumDiscTitles),
|
||||
construct(ctx, "202602061800", migrateAddTrackYear),
|
||||
construct(ctx, "202604231200", migrateAddTrackContributors),
|
||||
}
|
||||
|
||||
return gormigrate.
|
||||
New(db.DB, options, migrations).
|
||||
Migrate()
|
||||
}
|
||||
|
||||
func construct(ctx MigrationContext, id string, f func(*gorm.DB, MigrationContext) error) *gormigrate.Migration {
|
||||
return constructNoTx(ctx, id, func(db *gorm.DB, ctx MigrationContext) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
return f(tx, ctx)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func constructNoTx(ctx MigrationContext, id string, f func(*gorm.DB, MigrationContext) error) *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: id,
|
||||
Migrate: func(db *gorm.DB) error {
|
||||
if err := f(db, ctx); err != nil {
|
||||
return fmt.Errorf("%q: %w", id, err)
|
||||
}
|
||||
log.Printf("migration '%s' finished", id)
|
||||
return nil
|
||||
},
|
||||
Rollback: func(*gorm.DB) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func migrateInitSchema(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Genre{},
|
||||
TrackGenre{},
|
||||
AlbumGenre{},
|
||||
Track{},
|
||||
Artist{},
|
||||
User{},
|
||||
Setting{},
|
||||
Play{},
|
||||
Album{},
|
||||
PlayQueue{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateCreateInitUser(tx *gorm.DB, _ MigrationContext) error {
|
||||
const (
|
||||
initUsername = "admin"
|
||||
initPassword = "admin"
|
||||
)
|
||||
err := tx.
|
||||
Where("name=?", initUsername).
|
||||
First(&User{}).
|
||||
Error
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return tx.Create(&User{
|
||||
Name: initUsername,
|
||||
Password: initPassword,
|
||||
IsAdmin: true,
|
||||
}).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateMergePlaylist(tx *gorm.DB, _ MigrationContext) error {
|
||||
if !tx.HasTable("playlists") {
|
||||
return nil
|
||||
}
|
||||
if !tx.HasTable("playlist_items") {
|
||||
return nil
|
||||
}
|
||||
|
||||
return tx.Exec(`
|
||||
UPDATE playlists
|
||||
SET items=( SELECT group_concat(track_id) FROM (
|
||||
SELECT track_id
|
||||
FROM playlist_items
|
||||
WHERE playlist_items.playlist_id=playlists.id
|
||||
ORDER BY created_at
|
||||
) );
|
||||
DROP TABLE playlist_items;`,
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateCreateTranscode(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
TranscodePreference{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateAddGenre(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Genre{},
|
||||
Album{},
|
||||
Track{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateUpdateTranscodePrefIDX(tx *gorm.DB, _ MigrationContext) error {
|
||||
var hasIDX int
|
||||
tx.
|
||||
Select("1").
|
||||
Table("sqlite_master").
|
||||
Where("type = ?", "index").
|
||||
Where("name = ?", "idx_user_id_client").
|
||||
Count(&hasIDX)
|
||||
if hasIDX == 1 {
|
||||
// index already exists
|
||||
return nil
|
||||
}
|
||||
|
||||
step := tx.Exec(`
|
||||
ALTER TABLE transcode_preferences RENAME TO transcode_preferences_orig;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step rename: %w", err)
|
||||
}
|
||||
|
||||
step = tx.AutoMigrate(
|
||||
TranscodePreference{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step create: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
INSERT INTO transcode_preferences (user_id, client, profile)
|
||||
SELECT user_id, client, profile
|
||||
FROM transcode_preferences_orig;
|
||||
DROP TABLE transcode_preferences_orig;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step copy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateAddAlbumIDX(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Album{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateMultiGenre(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(
|
||||
Genre{},
|
||||
TrackGenre{},
|
||||
AlbumGenre{},
|
||||
Track{},
|
||||
Album{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
var genreCount int
|
||||
tx.
|
||||
Model(Genre{}).
|
||||
Count(&genreCount)
|
||||
if genreCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
INSERT INTO track_genres (track_id, genre_id)
|
||||
SELECT id, tag_genre_id
|
||||
FROM tracks
|
||||
WHERE tag_genre_id IS NOT NULL;
|
||||
UPDATE tracks SET tag_genre_id=NULL;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate track genres: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
INSERT INTO album_genres (album_id, genre_id)
|
||||
SELECT id, tag_genre_id
|
||||
FROM albums
|
||||
WHERE tag_genre_id IS NOT NULL;
|
||||
UPDATE albums SET tag_genre_id=NULL;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate album genres: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateListenBrainz(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(
|
||||
User{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migratePodcast(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Podcast{},
|
||||
PodcastEpisode{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateBookmarks(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Bookmark{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migratePodcastAutoDownload(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Podcast{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateAlbumCreatedAt(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(
|
||||
Album{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
UPDATE albums SET created_at=modified_at;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate album created_at: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateAlbumRootDir(tx *gorm.DB, ctx MigrationContext) error {
|
||||
step := tx.AutoMigrate(
|
||||
Album{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
DROP INDEX IF EXISTS idx_left_path_right_path;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop idx: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
UPDATE albums SET root_dir=? WHERE root_dir IS NULL
|
||||
`, ctx.OriginalMusicPath)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop idx: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateArtistGuessedFolder(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(Artist{}).Error
|
||||
}
|
||||
|
||||
func migrateArtistCover(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(
|
||||
Artist{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
if !tx.Dialect().HasColumn("artists", "guessed_folder_id") {
|
||||
return nil
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
ALTER TABLE artists DROP COLUMN guessed_folder_id
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop column: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// there was an issue with that migration, try it again since it's updated
|
||||
func migrateAlbumRootDirAgain(tx *gorm.DB, ctx MigrationContext) error {
|
||||
return migrateAlbumRootDir(tx, ctx)
|
||||
}
|
||||
|
||||
func migratePublicPlaylist(tx *gorm.DB, _ MigrationContext) error {
|
||||
if !tx.HasTable("playlists") {
|
||||
return nil
|
||||
}
|
||||
return tx.AutoMigrate(__OldPlaylist{}).Error
|
||||
}
|
||||
|
||||
func migratePodcastDropUserID(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(
|
||||
Podcast{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
if !tx.Dialect().HasColumn("podcasts", "user_id") {
|
||||
return nil
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
ALTER TABLE podcasts DROP COLUMN user_id;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate podcasts drop user_id: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateInternetRadioStations(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
InternetRadioStation{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateUser(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
User{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateStarRating(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Album{},
|
||||
AlbumStar{},
|
||||
AlbumRating{},
|
||||
Artist{},
|
||||
ArtistStar{},
|
||||
ArtistRating{},
|
||||
Track{},
|
||||
TrackStar{},
|
||||
TrackRating{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migratePlaylistsQueuesToFullID(tx *gorm.DB, _ MigrationContext) error {
|
||||
if !tx.HasTable("playlists") {
|
||||
return nil
|
||||
}
|
||||
|
||||
step := tx.Exec(`
|
||||
UPDATE playlists SET items=('tr-' || items) WHERE items IS NOT NULL;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate playlists to full id: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
UPDATE playlists SET items=REPLACE(items,',',',tr-') WHERE items IS NOT NULL;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate playlists to full id: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
UPDATE play_queues SET items=('tr-' || items) WHERE items IS NOT NULL;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate play_queues to full id: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
UPDATE play_queues SET items=REPLACE(items,',',',tr-') WHERE items IS NOT NULL;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate play_queues to full id: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
ALTER TABLE play_queues ADD COLUMN newcurrent varchar[255];
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate play_queues to full id: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
UPDATE play_queues SET newcurrent=('tr-' || CAST(current AS varchar(10)));
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate play_queues to full id: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
ALTER TABLE play_queues DROP COLUMN current;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate play_queues to full id: %w", err)
|
||||
}
|
||||
step = tx.Exec(`
|
||||
ALTER TABLE play_queues RENAME COLUMN newcurrent TO "current";
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step migrate play_queues to full id: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func migratePlaylistsToM3U(tx *gorm.DB, ctx MigrationContext) error {
|
||||
if ctx.PlaylistsPath == "" || !tx.HasTable("playlists") {
|
||||
return nil
|
||||
}
|
||||
|
||||
// local copy of specidpaths.Locate to avoid circular dep
|
||||
locate := func(id specid.ID) string {
|
||||
switch id.Type {
|
||||
case specid.Track:
|
||||
var track Track
|
||||
tx.Preload("Album").Where("id=?", id.Value).Find(&track)
|
||||
return track.AbsPath()
|
||||
case specid.PodcastEpisode:
|
||||
var pe PodcastEpisode
|
||||
tx.Where("id=?", id.Value).Preload("Podcast").Find(&pe)
|
||||
if pe.Filename == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(ctx.PodcastsPath, fileutil.Safe(pe.Podcast.Title), pe.Filename)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
store, err := playlist.NewStore(ctx.PlaylistsPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create playlists store: %w", err)
|
||||
}
|
||||
|
||||
var prevs []*__OldPlaylist
|
||||
if err := tx.Find(&prevs).Error; err != nil {
|
||||
return fmt.Errorf("fetch old playlists: %w", err)
|
||||
}
|
||||
|
||||
for _, prev := range prevs {
|
||||
var pl playlist.Playlist
|
||||
pl.UpdatedAt = time.Now()
|
||||
pl.UserID = prev.UserID
|
||||
pl.Name = prev.Name
|
||||
pl.Comment = prev.Comment
|
||||
pl.IsPublic = prev.IsPublic
|
||||
|
||||
for _, id := range splitIDs(prev.Items, ",") {
|
||||
path := locate(id)
|
||||
if path == "" {
|
||||
log.Printf("migrating: can't find item %s from playlist %q on filesystem", id, prev.Name)
|
||||
continue
|
||||
}
|
||||
pl.Items = append(pl.Items, path)
|
||||
}
|
||||
|
||||
if err := store.Write(playlist.NewPath(prev.UserID, prev.Name), &pl); err != nil {
|
||||
return fmt.Errorf("write playlist: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func migratePlayCountToLength(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(
|
||||
Play{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
// As a best guess, we set length played so far as length of album * current count / number of tracks in album
|
||||
step = tx.Exec(`
|
||||
UPDATE plays SET length=
|
||||
((SELECT SUM(length) FROM tracks WHERE tracks.album_id=plays.album_id)*plays.count/
|
||||
(SELECT COUNT(*) FROM tracks WHERE tracks.album_id=plays.album_id));
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("calculate length: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateAlbumArtistsMany2Many(tx *gorm.DB, _ MigrationContext) error {
|
||||
// gorms seems to want to create the table automatically without ON DELETE rules
|
||||
step := tx.DropTableIfExists(AlbumArtist{})
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop prev: %w", err)
|
||||
}
|
||||
|
||||
step = tx.AutoMigrate(
|
||||
AlbumArtist{},
|
||||
Album{},
|
||||
Artist{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
if tx.Dialect().HasColumn("albums", "tag_artist_id") {
|
||||
tx = tx.LogMode(false)
|
||||
step = tx.Exec(`
|
||||
INSERT INTO album_artists (album_id, artist_id)
|
||||
SELECT id album_id, tag_artist_id artist_id
|
||||
FROM albums
|
||||
WHERE tag_artist_id IS NOT NULL;
|
||||
`)
|
||||
if err := step.Error; err != nil && !strings.Contains(err.Error(), "no such column") {
|
||||
return fmt.Errorf("step insert from albums: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`DROP INDEX idx_albums_tag_artist_id`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop index: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`ALTER TABLE albums DROP COLUMN tag_artist_id;`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop albums tag artist id: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if tx.Dialect().HasColumn("tracks", "artist_id") {
|
||||
step = tx.Exec(`ALTER TABLE tracks DROP COLUMN artist_id;`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop track tag artist: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateDeleteArtistCoverField(tx *gorm.DB, _ MigrationContext) error {
|
||||
if !tx.Dialect().HasColumn("artists", "cover") {
|
||||
return nil
|
||||
}
|
||||
|
||||
step := tx.Exec(`
|
||||
ALTER TABLE artists DROP COLUMN cover;
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateArtistInfo(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
ArtistInfo{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migratePlaylistsPaths(tx *gorm.DB, ctx MigrationContext) error {
|
||||
if !tx.Dialect().HasColumn("podcast_episodes", "path") {
|
||||
return nil
|
||||
}
|
||||
if !tx.Dialect().HasColumn("podcasts", "image_path") {
|
||||
return nil
|
||||
}
|
||||
|
||||
step := tx.Exec(`
|
||||
ALTER TABLE podcasts RENAME COLUMN image_path TO image
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop podcast_episodes path: %w", err)
|
||||
}
|
||||
|
||||
step = tx.AutoMigrate(
|
||||
Podcast{},
|
||||
PodcastEpisode{},
|
||||
)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
var podcasts []*Podcast
|
||||
if err := tx.Find(&podcasts).Error; err != nil {
|
||||
return fmt.Errorf("step load: %w", err)
|
||||
}
|
||||
|
||||
for _, p := range podcasts {
|
||||
p.Image = filepath.Base(p.Image)
|
||||
if err := tx.Save(p).Error; err != nil {
|
||||
return fmt.Errorf("saving podcast for cover %d: %w", p.ID, err)
|
||||
}
|
||||
|
||||
oldPath, err := fileutil.First(
|
||||
filepath.Join(ctx.PodcastsPath, fileutil.Safe(p.Title)),
|
||||
filepath.Join(ctx.PodcastsPath, strings.ReplaceAll(p.Title, string(filepath.Separator), "_")), // old safe func
|
||||
filepath.Join(ctx.PodcastsPath, p.Title),
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("error finding old podcast path: %v. ignoring", err)
|
||||
continue
|
||||
}
|
||||
newPath := filepath.Join(ctx.PodcastsPath, fileutil.Safe(p.Title))
|
||||
p.RootDir = newPath
|
||||
if err := tx.Save(p).Error; err != nil {
|
||||
return fmt.Errorf("saving podcast %d: %w", p.ID, err)
|
||||
}
|
||||
if oldPath == newPath {
|
||||
continue
|
||||
}
|
||||
if err := os.Rename(oldPath, newPath); err != nil {
|
||||
return fmt.Errorf("rename podcast path: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
var podcastEpisodes []*PodcastEpisode
|
||||
if err := tx.Preload("Podcast").Find(&podcastEpisodes, "status=? OR status=?", PodcastEpisodeStatusCompleted, PodcastEpisodeStatusDownloading).Error; err != nil {
|
||||
return fmt.Errorf("step load: %w", err)
|
||||
}
|
||||
for _, pe := range podcastEpisodes {
|
||||
if pe.Filename == "" {
|
||||
continue
|
||||
}
|
||||
oldPath, err := fileutil.First(
|
||||
filepath.Join(pe.Podcast.RootDir, fileutil.Safe(pe.Filename)),
|
||||
filepath.Join(pe.Podcast.RootDir, strings.ReplaceAll(pe.Filename, string(filepath.Separator), "_")), // old safe func
|
||||
filepath.Join(pe.Podcast.RootDir, pe.Filename),
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("error finding old podcast episode path: %v. ignoring", err)
|
||||
continue
|
||||
}
|
||||
newName := fileutil.Safe(filepath.Base(oldPath))
|
||||
pe.Filename = newName
|
||||
if err := tx.Save(pe).Error; err != nil {
|
||||
return fmt.Errorf("saving podcast episode %d: %w", pe.ID, err)
|
||||
}
|
||||
newPath := filepath.Join(pe.Podcast.RootDir, newName)
|
||||
if oldPath == newPath {
|
||||
continue
|
||||
}
|
||||
if err := os.Rename(oldPath, newPath); err != nil {
|
||||
return fmt.Errorf("rename podcast episode path: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
ALTER TABLE podcast_episodes DROP COLUMN path
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop podcast_episodes path: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateAlbumTagArtistString(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(Album{}).Error
|
||||
}
|
||||
|
||||
func migrateTrackArtists(tx *gorm.DB, _ MigrationContext) error {
|
||||
// gorms seems to want to create the table automatically without ON DELETE rules
|
||||
step := tx.DropTableIfExists(TrackArtist{})
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop prev: %w", err)
|
||||
}
|
||||
return tx.AutoMigrate(TrackArtist{}).Error
|
||||
}
|
||||
|
||||
func migrateArtistAppearances(tx *gorm.DB, _ MigrationContext) error {
|
||||
// gorms seems to want to create the table automatically without ON DELETE rules
|
||||
step := tx.DropTableIfExists(ArtistAppearances{})
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step drop prev: %w", err)
|
||||
}
|
||||
|
||||
step = tx.AutoMigrate(ArtistAppearances{})
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
INSERT INTO artist_appearances (artist_id, album_id)
|
||||
SELECT artist_id, album_id
|
||||
FROM album_artists
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step transfer album artists: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
INSERT OR IGNORE INTO artist_appearances (artist_id, album_id)
|
||||
SELECT track_artists.artist_id, tracks.album_id
|
||||
FROM track_artists
|
||||
JOIN tracks ON tracks.id=track_artists.track_id
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step transfer album artists: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateAlbumInfo(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
AlbumInfo{},
|
||||
).
|
||||
Error
|
||||
}
|
||||
|
||||
func migrateTemporaryDisplayAlbumArtist(tx *gorm.DB, _ MigrationContext) error {
|
||||
// keep some things working so that people have an album.tag_artist_id until their next full scan
|
||||
return tx.Exec(`
|
||||
UPDATE albums
|
||||
SET tag_album_artist=(
|
||||
SELECT group_concat(artists.name, ', ')
|
||||
FROM artists
|
||||
JOIN album_artists ON album_artists.artist_id=artists.id AND album_artists.album_id=albums.id
|
||||
GROUP BY album_artists.album_id
|
||||
)
|
||||
WHERE tag_album_artist=''
|
||||
`).Error
|
||||
}
|
||||
|
||||
func migrateAddExtraIndexes(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.Exec(`
|
||||
CREATE INDEX idx_track_genres_genre_id ON "track_genres" (genre_id);
|
||||
CREATE INDEX idx_album_genres_genre_id ON "album_genres" (genre_id);
|
||||
CREATE INDEX idx_album_artists_artist_id ON "album_artists" (artist_id);
|
||||
CREATE INDEX idx_track_artists_artist_id ON "track_artists" (artist_id);
|
||||
CREATE INDEX idx_artist_appearances_album_id ON "artist_appearances" (album_id);
|
||||
`).Error
|
||||
}
|
||||
|
||||
func migrateAddReplayGainFields(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(Track{}).Error
|
||||
}
|
||||
|
||||
func migrateTrackAddIndexOnAlbumID(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.Exec(`
|
||||
CREATE INDEX idx_tracks_album_id ON "tracks" (album_id, length);
|
||||
`).Error
|
||||
}
|
||||
|
||||
func migrateAlbumAddIndexOnParentID(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.Exec(`
|
||||
CREATE INDEX idx_albums_parent_id ON "albums" (parent_id);
|
||||
`).Error
|
||||
}
|
||||
|
||||
func migratePodcastEpisode(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
PodcastEpisode{},
|
||||
).Error
|
||||
}
|
||||
|
||||
func migrateTrackAddIndexOnBrainzID(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.Exec(`
|
||||
CREATE INDEX idx_tracks_brainz_id ON "tracks" (tag_brainz_id);
|
||||
`).Error
|
||||
}
|
||||
|
||||
func migrateAlbumAddIndexOnBrainzID(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.Exec(`
|
||||
CREATE INDEX idx_albums_brainz_id ON "albums" (tag_brainz_id);
|
||||
`).Error
|
||||
}
|
||||
|
||||
func migrateAlbumCompilationReleaseType(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(
|
||||
Album{},
|
||||
).Error
|
||||
}
|
||||
|
||||
func migrateAddLyrics(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(Track{}).Error
|
||||
}
|
||||
|
||||
func migrateAddAlbumEmbeddedCoverTrackID(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(Album{}).Error
|
||||
}
|
||||
|
||||
func migrateAddTrackEmbeddedCover(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(Track{}).Error
|
||||
}
|
||||
|
||||
func migrateAlbumAddIndexOnCreatedAt(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.Exec(`
|
||||
CREATE INDEX idx_albums_created_at ON "albums" (created_at);
|
||||
`).Error
|
||||
}
|
||||
|
||||
func migrateAddAlbumDiscTitles(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(AlbumDiscTitle{}).Error
|
||||
}
|
||||
|
||||
func migrateAddTrackContributors(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(TrackContributor{}).Error
|
||||
}
|
||||
|
||||
func migrateAddTrackYear(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(Track{})
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
UPDATE tracks
|
||||
SET tag_year=(SELECT tag_year
|
||||
FROM albums
|
||||
WHERE tracks.album_id = albums.id)
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step set default track year based on album's : %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package db
|
||||
|
||||
import "time"
|
||||
|
||||
type __OldPlaylist struct { //nolint: staticcheck
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
User *User
|
||||
UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
Name string
|
||||
Comment string
|
||||
TrackCount int
|
||||
Items string
|
||||
IsPublic bool `sql:"default: null"`
|
||||
}
|
||||
|
||||
func (__OldPlaylist) TableName() string {
|
||||
return "playlists"
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
//go:build !nowasm
|
||||
|
||||
package deps
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
|
||||
// Cgo-free Wasm database
|
||||
_ "github.com/ncruces/go-sqlite3/driver"
|
||||
|
||||
// Cgo-free Wasm tagger
|
||||
"go.senan.xyz/gonic/tags/taglib"
|
||||
)
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var TagReader = taglib.Reader{}
|
||||
|
||||
// DBDriverOptions returns SQLite DSN options for the ncruces driver
|
||||
func DBDriverOptions() url.Values {
|
||||
return url.Values{
|
||||
"_pragma": {
|
||||
"busy_timeout(30000)",
|
||||
"journal_mode(WAL)",
|
||||
"foreign_keys(ON)",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
//go:build nowasm
|
||||
|
||||
package deps
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
|
||||
// Cgo database
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
|
||||
// Cgo tagger
|
||||
"go.senan.xyz/gonic/tags/ffprobe"
|
||||
)
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var TagReader = ffprobe.Reader{}
|
||||
|
||||
// DSNOptions returns SQLite DSN options for the mattn driver
|
||||
func DBDriverOptions() url.Values {
|
||||
return url.Values{
|
||||
"_busy_timeout": {"30000"},
|
||||
"_journal_mode": {"WAL"},
|
||||
"_foreign_keys": {"true"},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { FlatCompat } from "@eslint/eslintrc";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
});
|
||||
|
||||
const eslintConfig = [
|
||||
...compat.extends("next/core-web-vitals", "next/typescript"),
|
||||
];
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -1,65 +0,0 @@
|
||||
// TODO: this package shouldn't really exist. we can usually just attempt our normal filesystem operations
|
||||
// and handle errors atomically. eg.
|
||||
// - Safe could instead be try create file, handle error
|
||||
// - Unique could be try create file, on err create file (1), etc
|
||||
package fileutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var nonAlphaNumExpr = regexp.MustCompile("[^a-zA-Z0-9_.]+")
|
||||
|
||||
const maxFilenameLength = 200
|
||||
|
||||
func Safe(filename string) string {
|
||||
filename = nonAlphaNumExpr.ReplaceAllString(filename, "")
|
||||
ext := filepath.Ext(filename)
|
||||
filename = filename[:min(maxFilenameLength, len(filename))-len(ext)]
|
||||
return filename + ext
|
||||
}
|
||||
|
||||
// try to find a unqiue file (or dir) name. incrementing like "example (1)"
|
||||
func Unique(base, filename string) (string, error) {
|
||||
return unique(base, filename, 0)
|
||||
}
|
||||
|
||||
func unique(base, filename string, count uint) (string, error) {
|
||||
var suffix string
|
||||
if count > 0 {
|
||||
suffix = fmt.Sprintf(" (%d)", count)
|
||||
}
|
||||
path := base + suffix
|
||||
if filename != "" {
|
||||
noExt := strings.TrimSuffix(filename, filepath.Ext(filename))
|
||||
path = filepath.Join(base, noExt+suffix+filepath.Ext(filename))
|
||||
}
|
||||
_, err := os.Stat(path)
|
||||
if os.IsNotExist(err) {
|
||||
return path, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return unique(base, filename, count+1)
|
||||
}
|
||||
|
||||
func First(path ...string) (string, error) {
|
||||
var err error
|
||||
for _, p := range path {
|
||||
_, err = os.Stat(p)
|
||||
if err == nil {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
// HasPrefix checks a path has a prefix, making sure to respect path boundaries. So that /aa & /a does not match, but /a/a & /a does.
|
||||
func HasPrefix(p, prefix string) bool {
|
||||
return p == prefix || strings.HasPrefix(p, filepath.Clean(prefix)+string(filepath.Separator))
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package fileutil
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestUniquePath(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
unq := func(base, filename string, count uint) string {
|
||||
r, err := unique(base, filename, count)
|
||||
require.NoError(t, err)
|
||||
return r
|
||||
}
|
||||
|
||||
require.Equal(t, "test/wow.mp3", unq("test", "wow.mp3", 0))
|
||||
require.Equal(t, "test/wow (1).mp3", unq("test", "wow.mp3", 1))
|
||||
require.Equal(t, "test/wow (2).mp3", unq("test", "wow.mp3", 2))
|
||||
|
||||
require.Equal(t, "test", unq("test", "", 0))
|
||||
require.Equal(t, "test (1)", unq("test", "", 1))
|
||||
|
||||
base := filepath.Join(t.TempDir(), "a")
|
||||
|
||||
require.NoError(t, os.MkdirAll(base, os.ModePerm))
|
||||
|
||||
next := base + " (1)"
|
||||
require.Equal(t, next, unq(base, "", 0))
|
||||
|
||||
require.NoError(t, os.MkdirAll(next, os.ModePerm))
|
||||
|
||||
next = base + " (2)"
|
||||
require.Equal(t, next, unq(base, "", 0))
|
||||
|
||||
_, err := os.Create(filepath.Join(base, "test.mp3"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, filepath.Join(base, "test (1).mp3"), unq(base, "test.mp3", 0))
|
||||
}
|
||||
|
||||
func TestFirst(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
base := t.TempDir()
|
||||
name := filepath.Join(base, "test")
|
||||
_, err := os.Create(name)
|
||||
require.NoError(t, err)
|
||||
|
||||
p := func(name string) string {
|
||||
return filepath.Join(base, name)
|
||||
}
|
||||
|
||||
r, err := First(p("one"), p("two"), p("test"), p("four"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, p("test"), r)
|
||||
}
|
||||
|
||||
func TestSafe(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
longName := "hi_00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
|
||||
result := Safe(longName)
|
||||
require.Equal(t, 200, len(result))
|
||||
require.Equal(t, longName[:200], result)
|
||||
|
||||
longNameWithExt := "hi_00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.mp3"
|
||||
result = Safe(longNameWithExt)
|
||||
require.Equal(t, 200, len(result))
|
||||
require.Equal(t, ".mp3", result[len(result)-4:])
|
||||
|
||||
require.Equal(t, "test.mp3", Safe("test.mp3"))
|
||||
require.Equal(t, "testing.mp3", Safe("test ing.mp3"))
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
module go.senan.xyz/gonic
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible
|
||||
github.com/andybalholm/cascadia v1.3.3
|
||||
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de
|
||||
github.com/dexterlb/mpvipc v0.0.0-20241005113212-7cdefca0e933
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/djherbis/times v1.6.0
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/env25/mpdlrc v0.7.4
|
||||
github.com/fatih/structs v1.1.0
|
||||
github.com/fsnotify/fsnotify v1.9.0
|
||||
github.com/go-ldap/ldap/v3 v3.4.6
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/securecookie v1.1.2
|
||||
github.com/gorilla/sessions v1.4.0
|
||||
github.com/jinzhu/gorm v1.9.17-0.20211120011537-5c235b72a414
|
||||
github.com/josephburnett/jd v1.9.2
|
||||
github.com/mattn/go-sqlite3 v1.14.42
|
||||
github.com/microcosm-cc/bluemonday v1.0.27
|
||||
github.com/mitchellh/mapstructure v1.5.0
|
||||
github.com/mmcdole/gofeed v1.3.0
|
||||
github.com/ncruces/go-sqlite3 v0.33.3
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
|
||||
github.com/philippta/go-template v0.0.0-20220911145045-4556aca435e4
|
||||
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be
|
||||
github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981
|
||||
github.com/stretchr/testify v1.11.1
|
||||
go.senan.xyz/flagconf v0.1.11
|
||||
go.senan.xyz/taglib v0.11.1
|
||||
go.senan.xyz/wrtag v0.30.1-0.20260423121427-fec4b6e433cb
|
||||
golang.org/x/net v0.53.0
|
||||
golang.org/x/sync v0.20.0
|
||||
gopkg.in/gormigrate.v1 v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||
github.com/Masterminds/goutils v1.1.1 // indirect
|
||||
github.com/Masterminds/semver v1.5.0 // indirect
|
||||
github.com/PuerkitoBio/goquery v1.12.0 // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.23.1 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.26.0 // indirect
|
||||
github.com/gorilla/context v1.1.2 // indirect
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
github.com/huandu/xstrings v1.5.0 // indirect
|
||||
github.com/imdario/mergo v0.3.16 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/kr/pretty v0.1.0 // indirect
|
||||
github.com/lib/pq v1.3.0 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/mmcdole/goxpp v1.1.1 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/ncruces/go-sqlite3-wasm v1.1.1-0.20260409221933-87e4b35a38d0 // indirect
|
||||
github.com/ncruces/julianday v1.0.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/tetratelabs/wazero v1.11.0 // indirect
|
||||
golang.org/x/crypto v0.50.0 // indirect
|
||||
golang.org/x/image v0.39.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
||||
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -1,272 +0,0 @@
|
||||
cloud.google.com/go v0.33.1/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
|
||||
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
|
||||
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60=
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
|
||||
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
|
||||
github.com/PuerkitoBio/goquery v1.12.0 h1:pAcL4g3WRXekcB9AU/y1mbKez2dbY2AajVhtkO8RIBo=
|
||||
github.com/PuerkitoBio/goquery v1.12.0/go.mod h1:802ej+gV2y7bbIhOIoPY5sT183ZW0YFofScC4q/hIpQ=
|
||||
github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74 h1:Kk6a4nehpJ3UuJRqlA3JxYxBZEqCeOmATOvrbT4p9RA=
|
||||
github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
|
||||
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
|
||||
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
||||
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/denisenkom/go-mssqldb v0.0.0-20181014144952-4e0d7dc8888f/go.mod h1:xN/JuLBIz4bjkxNmByTiV1IbhfnYb6oo99phBn4Eqhc=
|
||||
github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM=
|
||||
github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
|
||||
github.com/dexterlb/mpvipc v0.0.0-20241005113212-7cdefca0e933 h1:r4hxcT6GBIA/j8Ox4OXI5MNgMKfR+9plcAWYi1OnmOg=
|
||||
github.com/dexterlb/mpvipc v0.0.0-20241005113212-7cdefca0e933/go.mod h1:RkQWLNITKkXHLP7LXxZSgEq+uFWU25M5qW7qfEhL9Wc=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
|
||||
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/env25/mpdlrc v0.7.4 h1:A9If5JKVjgJldaIjJztqkXpUKXlsoRIwXqGK3qS38pY=
|
||||
github.com/env25/mpdlrc v0.7.4/go.mod h1:Zyhq2WfcYeSJUCtx7mhbXwlh4Xt6mR7HDw0qQh7LvyY=
|
||||
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y=
|
||||
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
|
||||
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
|
||||
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-ldap/ldap/v3 v3.4.6 h1:ert95MdbiG7aWo/oPYp9btL3KJlMPKnP58r09rI8T+A=
|
||||
github.com/go-ldap/ldap/v3 v3.4.6/go.mod h1:IGMQANNtxpsOzj7uUAMjpGBaOVTC4DYyIy8VsTdxmtc=
|
||||
github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4=
|
||||
github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY=
|
||||
github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w=
|
||||
github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M=
|
||||
github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4=
|
||||
github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=
|
||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
||||
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||
github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
|
||||
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
|
||||
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
|
||||
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
|
||||
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
|
||||
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
|
||||
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
||||
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
||||
github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
|
||||
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4=
|
||||
github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY=
|
||||
github.com/jinzhu/gorm v1.9.2/go.mod h1:Vla75njaFJ8clLU1W44h34PjIkijhjHIYnZxMqCdxqo=
|
||||
github.com/jinzhu/gorm v1.9.17-0.20211120011537-5c235b72a414 h1:JkXdZo2OKW1t+GcTx5eb1kD2qW5lt1CDLrL2Ep9t+j4=
|
||||
github.com/jinzhu/gorm v1.9.17-0.20211120011537-5c235b72a414/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs=
|
||||
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v0.0.0-20181116074157-8ec929ed50c3/go.mod h1:oHTiXerJ20+SfYcrdlBO7rzZRJWGwSTQ0iUY2jI6Gfc=
|
||||
github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
|
||||
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
|
||||
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
|
||||
github.com/josephburnett/jd v1.9.2 h1:ECJRRFXCCqbtidkAHckHGSZm/JIaAxS1gygHLF8MI5Y=
|
||||
github.com/josephburnett/jd v1.9.2/go.mod h1:bImDr8QXpxMb3SD+w1cDRHp97xP6UwI88xUAuxwDQfM=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.3.0 h1:/qkRGz8zljWiDcFvgpwUpwIAPu3r07TDvs3Rws+o/pU=
|
||||
github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
|
||||
github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
|
||||
github.com/mattn/go-sqlite3 v1.14.42 h1:MigqEP4ZmHw3aIdIT7T+9TLa90Z6smwcthx+Azv4Cgo=
|
||||
github.com/mattn/go-sqlite3 v1.14.42/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
|
||||
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
|
||||
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/mmcdole/gofeed v1.3.0 h1:5yn+HeqlcvjMeAI4gu6T+crm7d0anY85+M+v6fIFNG4=
|
||||
github.com/mmcdole/gofeed v1.3.0/go.mod h1:9TGv2LcJhdXePDzxiuMnukhV2/zb6VtnZt1mS+SjkLE=
|
||||
github.com/mmcdole/goxpp v1.1.1 h1:RGIX+D6iQRIunGHrKqnA2+700XMCnNv0bAOOv5MUhx8=
|
||||
github.com/mmcdole/goxpp v1.1.1/go.mod h1:v+25+lT2ViuQ7mVxcncQ8ch1URund48oH+jhjiwEgS8=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/ncruces/go-sqlite3 v0.33.3 h1:6jCR3KuGvJSEwhaQrkHDGeIe2qCQ6nOUDNsPz7ZIotw=
|
||||
github.com/ncruces/go-sqlite3 v0.33.3/go.mod h1:t2Osfw0wcKzJTgv2EvrkTtVLqlbKTA5Yvwb2ypAlBcY=
|
||||
github.com/ncruces/go-sqlite3-wasm v1.1.1-0.20260409221933-87e4b35a38d0 h1:ymE9H30x1AyW5VfMNkJC9teuI2W1jjMsQS7kc6zl6Tg=
|
||||
github.com/ncruces/go-sqlite3-wasm v1.1.1-0.20260409221933-87e4b35a38d0/go.mod h1:/H3+JykPsfSlvKbOxNSx9kKwm3ecqQGzyCs1e9KkNsU=
|
||||
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
|
||||
github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/philippta/go-template v0.0.0-20220911145045-4556aca435e4 h1:SvVjZyjXBOjqjCdMiC9ndyWb709aP5qU4Qbun40GCxA=
|
||||
github.com/philippta/go-template v0.0.0-20220911145045-4556aca435e4/go.mod h1:Mpa6Hci7lO3vybfdYlWXmH5gEq2vyOmYYjhrlwCTW3w=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be h1:ta7tUOvsPHVHGom5hKW5VXNc2xZIkfCKP8iaqOyYtUQ=
|
||||
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be/go.mod h1:MIDFMn7db1kT65GmV94GzpX9Qdi7N/pQlwb+AN8wh+Q=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg=
|
||||
github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981 h1:sLILANWN76ja66/K4k/mBqJuCjDZaM67w+Ru6rEB0s0=
|
||||
github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981/go.mod h1:Rx8XB1ck+so+41uu9VY1gMKs1CPQ2NTq0pzf+OCCQHo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.senan.xyz/flagconf v0.1.11 h1:ApA9DpoSrfVQlLt8spKJC3fOT7oTEZ2/MmBGMnb9mt4=
|
||||
go.senan.xyz/flagconf v0.1.11/go.mod h1:NqOFfSwJvNWXOTUabcRZ8mPK9+sJmhStJhqtEt74wNQ=
|
||||
go.senan.xyz/taglib v0.11.1 h1:S3mO5e3HRRG0Ehw1jLUodYbAJK8TtqdOoNgqkC0D3uU=
|
||||
go.senan.xyz/taglib v0.11.1/go.mod h1:qyTl978MnGeZ/ny4d/t0ErLXxysA+39X4+SNSCk56Zs=
|
||||
go.senan.xyz/wrtag v0.30.1-0.20260423121427-fec4b6e433cb h1:hFxxWH6MlgcHZQv2BpkQ1KSp8MSbXMHtN338/HfSzdY=
|
||||
go.senan.xyz/wrtag v0.30.1-0.20260423121427-fec4b6e433cb/go.mod h1:sWPfwc3FM2O9Ka/l46vDp+/XwLCgywukxgfZipaWrKw=
|
||||
golang.org/x/crypto v0.0.0-20181112202954-3d3f9f413869/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww=
|
||||
golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/gormigrate.v1 v1.6.0 h1:XpYM6RHQPmzwY7Uyu+t+xxMXc86JYFJn4nEc9HzQjsI=
|
||||
gopkg.in/gormigrate.v1 v1.6.0/go.mod h1:Lf00lQrHqfSYWiTtPcyQabsDdM6ejZaMgV0OU6JMSlw=
|
||||
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU=
|
||||
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -1,130 +0,0 @@
|
||||
package handlerutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Middleware func(http.Handler) http.Handler
|
||||
|
||||
func Chain(middlewares ...Middleware) Middleware {
|
||||
return func(final http.Handler) http.Handler {
|
||||
for i := len(middlewares) - 1; i >= 0; i-- {
|
||||
final = middlewares[i](final)
|
||||
}
|
||||
return final
|
||||
}
|
||||
}
|
||||
|
||||
func TrimPathSuffix(suffix string) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.URL.Path = strings.TrimSuffix(r.URL.Path, suffix)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Log(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sw := &statusWriter{ResponseWriter: w}
|
||||
next.ServeHTTP(sw, r)
|
||||
log.Printf("response %s %s %v", statusToBlock(sw.status), r.Method, r.URL)
|
||||
})
|
||||
}
|
||||
|
||||
func BasicCORS(next http.Handler) http.Handler {
|
||||
allowMethods := strings.Join(
|
||||
[]string{http.MethodPost, http.MethodGet, http.MethodOptions, http.MethodPut, http.MethodDelete},
|
||||
", ",
|
||||
)
|
||||
allowHeaders := strings.Join(
|
||||
[]string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
|
||||
", ",
|
||||
)
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", allowMethods)
|
||||
w.Header().Set("Access-Control-Allow-Headers", allowHeaders)
|
||||
if r.Method == http.MethodOptions {
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func Message(message string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintln(w, message)
|
||||
})
|
||||
}
|
||||
|
||||
func BaseURL(r *http.Request) string {
|
||||
var fallbackScheme = "http"
|
||||
if r.TLS != nil {
|
||||
fallbackScheme = "https"
|
||||
}
|
||||
scheme := first(
|
||||
r.Header.Get("X-Forwarded-Proto"),
|
||||
r.Header.Get("X-Forwarded-Scheme"),
|
||||
r.URL.Scheme,
|
||||
fallbackScheme,
|
||||
)
|
||||
host := first(
|
||||
r.Header.Get("X-Forwarded-Host"),
|
||||
r.URL.Host,
|
||||
r.Host,
|
||||
)
|
||||
return fmt.Sprintf("%s://%s", scheme, host)
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(b []byte) (int, error) {
|
||||
if w.status == 0 {
|
||||
w.status = 200
|
||||
}
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Unwrap() http.ResponseWriter {
|
||||
return w.ResponseWriter
|
||||
}
|
||||
|
||||
func statusToBlock(code int) string {
|
||||
var bg int
|
||||
switch {
|
||||
case code >= 500:
|
||||
bg = 41 // bright red
|
||||
case code >= 400:
|
||||
bg = 43 // bright orange
|
||||
case code >= 300:
|
||||
bg = 46 // bright cyan
|
||||
case code >= 200:
|
||||
bg = 42 // bright green
|
||||
default:
|
||||
bg = 47 // bright white (grey)
|
||||
}
|
||||
return fmt.Sprintf("\u001b[%d;1m %d \u001b[0m", bg, code)
|
||||
}
|
||||
|
||||
func first[T comparable](vs ...T) T {
|
||||
var z T
|
||||
for _, s := range vs {
|
||||
if s != z {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return z
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
//nolint:revive
|
||||
package albuminfocache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
)
|
||||
|
||||
const keepFor = 30 * time.Hour * 24
|
||||
|
||||
type AlbumInfoCache struct {
|
||||
db *db.DB
|
||||
lastfmClient *lastfm.Client
|
||||
}
|
||||
|
||||
func New(db *db.DB, lastfmClient *lastfm.Client) *AlbumInfoCache {
|
||||
return &AlbumInfoCache{db: db, lastfmClient: lastfmClient}
|
||||
}
|
||||
|
||||
func (a *AlbumInfoCache) GetOrLookup(ctx context.Context, albumID int) (*db.AlbumInfo, error) {
|
||||
var album db.Album
|
||||
if err := a.db.Find(&album, "id=?", albumID).Error; err != nil {
|
||||
return nil, fmt.Errorf("find album in db: %w", err)
|
||||
}
|
||||
if album.TagAlbumArtist == "" || album.TagTitle == "" {
|
||||
return nil, fmt.Errorf("no metadata to look up")
|
||||
}
|
||||
|
||||
var albumInfo db.AlbumInfo
|
||||
if err := a.db.Find(&albumInfo, "id=?", albumID).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("find album info in db: %w", err)
|
||||
}
|
||||
|
||||
if albumInfo.ID == 0 || time.Since(albumInfo.UpdatedAt) > keepFor {
|
||||
return a.Lookup(ctx, &album)
|
||||
}
|
||||
|
||||
return &albumInfo, nil
|
||||
}
|
||||
|
||||
func (a *AlbumInfoCache) Get(ctx context.Context, albumID int) (*db.AlbumInfo, error) {
|
||||
var albumInfo db.AlbumInfo
|
||||
if err := a.db.Find(&albumInfo, "id=?", albumID).Error; err != nil {
|
||||
return nil, fmt.Errorf("find album info in db: %w", err)
|
||||
}
|
||||
return &albumInfo, nil
|
||||
}
|
||||
|
||||
func (a *AlbumInfoCache) Lookup(ctx context.Context, album *db.Album) (*db.AlbumInfo, error) {
|
||||
var albumInfo db.AlbumInfo
|
||||
albumInfo.ID = album.ID
|
||||
|
||||
if err := a.db.FirstOrCreate(&albumInfo, "id=?", albumInfo.ID).Error; err != nil {
|
||||
return nil, fmt.Errorf("first or create album info: %w", err)
|
||||
}
|
||||
if err := a.db.Save(&albumInfo).Error; err != nil {
|
||||
return nil, fmt.Errorf("bump updated_at time: %w", err)
|
||||
}
|
||||
|
||||
info, err := a.lastfmClient.AlbumGetInfo(album.TagAlbumArtist, album.TagTitle)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get upstream info: %w", err)
|
||||
}
|
||||
|
||||
albumInfo.ID = album.ID
|
||||
albumInfo.Notes = info.Wiki.Content
|
||||
albumInfo.MusicBrainzID = info.MBID
|
||||
albumInfo.LastFMURL = info.URL
|
||||
|
||||
if err := a.db.Save(&albumInfo).Error; err != nil {
|
||||
return nil, fmt.Errorf("save upstream info: %w", err)
|
||||
}
|
||||
|
||||
return &albumInfo, nil
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
//nolint:revive
|
||||
package artistinfocache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
)
|
||||
|
||||
const keepFor = 30 * time.Hour * 24
|
||||
|
||||
type ArtistInfoCache struct {
|
||||
db *db.DB
|
||||
lastfmClient *lastfm.Client
|
||||
}
|
||||
|
||||
func New(db *db.DB, lastfmClient *lastfm.Client) *ArtistInfoCache {
|
||||
return &ArtistInfoCache{db: db, lastfmClient: lastfmClient}
|
||||
}
|
||||
|
||||
func (a *ArtistInfoCache) GetOrLookup(ctx context.Context, artistID int) (*db.ArtistInfo, error) {
|
||||
var artist db.Artist
|
||||
if err := a.db.Find(&artist, "id=?", artistID).Error; err != nil {
|
||||
return nil, fmt.Errorf("find artist in db: %w", err)
|
||||
}
|
||||
if artist.Name == "" {
|
||||
return nil, fmt.Errorf("no metadata to look up")
|
||||
}
|
||||
|
||||
var artistInfo db.ArtistInfo
|
||||
if err := a.db.Find(&artistInfo, "id=?", artistID).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("find artist info in db: %w", err)
|
||||
}
|
||||
|
||||
if artistInfo.ID == 0 || artistInfo.Biography == "" /* prev not found maybe */ || time.Since(artistInfo.UpdatedAt) > keepFor {
|
||||
return a.Lookup(ctx, &artist)
|
||||
}
|
||||
|
||||
return &artistInfo, nil
|
||||
}
|
||||
|
||||
func (a *ArtistInfoCache) Get(ctx context.Context, artistID int) (*db.ArtistInfo, error) {
|
||||
var artistInfo db.ArtistInfo
|
||||
if err := a.db.Find(&artistInfo, "id=?", artistID).Error; err != nil {
|
||||
return nil, fmt.Errorf("find artist info in db: %w", err)
|
||||
}
|
||||
return &artistInfo, nil
|
||||
}
|
||||
|
||||
func (a *ArtistInfoCache) Lookup(ctx context.Context, artist *db.Artist) (*db.ArtistInfo, error) {
|
||||
var artistInfo db.ArtistInfo
|
||||
artistInfo.ID = artist.ID
|
||||
|
||||
if err := a.db.FirstOrCreate(&artistInfo, "id=?", artistInfo.ID).Error; err != nil {
|
||||
return nil, fmt.Errorf("first or create artist info: %w", err)
|
||||
}
|
||||
if err := a.db.Save(&artistInfo).Error; err != nil {
|
||||
return nil, fmt.Errorf("bump updated_at time: %w", err)
|
||||
}
|
||||
|
||||
info, err := a.lastfmClient.ArtistGetInfo(artist.Name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get upstream info: %w", err)
|
||||
}
|
||||
|
||||
artistInfo.ID = artist.ID
|
||||
artistInfo.Biography = info.Bio.Summary
|
||||
artistInfo.MusicBrainzID = info.MBID
|
||||
artistInfo.LastFMURL = info.URL
|
||||
|
||||
var similar []string
|
||||
for _, sim := range info.Similar.Artists {
|
||||
similar = append(similar, sim.Name)
|
||||
}
|
||||
artistInfo.SetSimilarArtists(similar)
|
||||
|
||||
if url, _ := a.lastfmClient.StealArtistImage(info.URL); url != "" {
|
||||
artistInfo.ImageURL = url
|
||||
}
|
||||
|
||||
topTracksResponse, err := a.lastfmClient.ArtistGetTopTracks(artist.Name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get top tracks: %w", err)
|
||||
}
|
||||
var topTracks []string
|
||||
for _, tr := range topTracksResponse.Tracks {
|
||||
topTracks = append(topTracks, tr.Name)
|
||||
}
|
||||
artistInfo.SetTopTracks(topTracks)
|
||||
|
||||
if err := a.db.Save(&artistInfo).Error; err != nil {
|
||||
return nil, fmt.Errorf("save upstream info: %w", err)
|
||||
}
|
||||
|
||||
return &artistInfo, nil
|
||||
}
|
||||
|
||||
func (a *ArtistInfoCache) Refresh() error {
|
||||
q := a.db.
|
||||
Where("artist_infos.id IS NULL OR artist_infos.updated_at<?", time.Now().Add(-keepFor)).
|
||||
Joins("LEFT JOIN artist_infos ON artist_infos.id=artists.id")
|
||||
|
||||
var artist db.Artist
|
||||
if err := q.Find(&artist).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("finding non cached artist: %w", err)
|
||||
}
|
||||
|
||||
if artist.ID == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := a.Lookup(context.Background(), &artist); err != nil {
|
||||
return fmt.Errorf("looking up non cached artist %s: %w", artist.Name, err)
|
||||
}
|
||||
|
||||
log.Printf("cached artist info for %q", artist.Name)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package artistinfocache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
"go.senan.xyz/gonic/lastfm/mockclient"
|
||||
"go.senan.xyz/gonic/mockfs"
|
||||
)
|
||||
|
||||
func TestInfoCache(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
m := mockfs.New(t)
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
assert := assert.New(t)
|
||||
|
||||
var artist db.Artist
|
||||
assert.NoError(m.DB().Preload("Info").Find(&artist).Error)
|
||||
assert.Greater(artist.ID, 0)
|
||||
assert.Nil(artist.Info)
|
||||
|
||||
var count atomic.Int32
|
||||
lastfmClient := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
switch method := r.URL.Query().Get("method"); method {
|
||||
case "artist.getInfo":
|
||||
count.Add(1)
|
||||
w.Write(mockclient.ArtistGetInfoResponse)
|
||||
case "artist.getTopTracks":
|
||||
w.Write(mockclient.ArtistGetTopTracksResponse)
|
||||
}
|
||||
}),
|
||||
func() (apiKey string, secret string, err error) {
|
||||
return "", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
cache := New(m.DB(), lastfmClient)
|
||||
_, err := cache.GetOrLookup(context.Background(), artist.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = cache.GetOrLookup(context.Background(), artist.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, int32(1), count.Load())
|
||||
|
||||
assert.NoError(m.DB().Preload("Info").Find(&artist, "id=?", artist.ID).Error)
|
||||
assert.Greater(artist.ID, 0)
|
||||
assert.NotNil(artist.Info)
|
||||
assert.Equal("Summary", artist.Info.Biography)
|
||||
}
|
||||
@@ -1,409 +0,0 @@
|
||||
// author: AlexKraak (https://github.com/alexkraak/)
|
||||
// author: sentriz (https://github.com/sentriz/)
|
||||
|
||||
package jukebox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/dexterlb/mpvipc"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrMPVTimeout = fmt.Errorf("mpv not responding")
|
||||
ErrMPVNeverStarted = fmt.Errorf("mpv never started")
|
||||
ErrMPVTooOld = fmt.Errorf("mpv too old")
|
||||
)
|
||||
|
||||
func MPVArg(k string, v any) string {
|
||||
if v, ok := v.(bool); ok {
|
||||
if v {
|
||||
return fmt.Sprintf("%s=yes", k)
|
||||
}
|
||||
return fmt.Sprintf("%s=no", k)
|
||||
}
|
||||
return fmt.Sprintf("%s=%v", k, v)
|
||||
}
|
||||
|
||||
type Jukebox struct {
|
||||
cmd *exec.Cmd
|
||||
conn *mpvipc.Connection
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func New() *Jukebox {
|
||||
return &Jukebox{}
|
||||
}
|
||||
|
||||
func (j *Jukebox) Start(ctx context.Context, sockPath string, mpvExtraArgs []string) error {
|
||||
const mpvName = "mpv"
|
||||
if _, err := exec.LookPath(mpvName); err != nil {
|
||||
return fmt.Errorf("look path: %w. did you forget to install it?", err)
|
||||
}
|
||||
|
||||
var mpvArgs []string
|
||||
mpvArgs = append(mpvArgs, "--idle", "--no-config", "--no-video", MPVArg("--audio-display", "no"), MPVArg("--input-ipc-server", sockPath))
|
||||
mpvArgs = append(mpvArgs, mpvExtraArgs...)
|
||||
|
||||
j.cmd = exec.CommandContext(ctx, mpvName, mpvArgs...)
|
||||
if err := j.cmd.Start(); err != nil {
|
||||
return fmt.Errorf("start mpv process: %w", err)
|
||||
}
|
||||
|
||||
ok := waitUntil(5*time.Second, func() bool {
|
||||
_, err := os.Stat(sockPath)
|
||||
return err == nil
|
||||
})
|
||||
if !ok {
|
||||
_ = j.cmd.Process.Kill()
|
||||
return ErrMPVNeverStarted
|
||||
}
|
||||
|
||||
j.conn = mpvipc.NewConnection(sockPath)
|
||||
if err := j.conn.Open(); err != nil {
|
||||
return fmt.Errorf("open connection: %w", err)
|
||||
}
|
||||
|
||||
var mpvVersionStr string
|
||||
if err := getDecode(j.conn, &mpvVersionStr, "mpv-version"); err != nil {
|
||||
return fmt.Errorf("get mpv version: %w", err)
|
||||
}
|
||||
if major, minor, patch := parseMPVVersion(mpvVersionStr); major == 0 && minor < 34 {
|
||||
return fmt.Errorf("%w: v0.34.0+ required, found v%d.%d.%d", ErrMPVTooOld, major, minor, patch)
|
||||
}
|
||||
|
||||
if _, err := j.conn.Call("observe_property", 0, "seekable"); err != nil {
|
||||
return fmt.Errorf("observe property: %w", err)
|
||||
}
|
||||
|
||||
var exitError *exec.ExitError
|
||||
if err := j.cmd.Wait(); err != nil && !errors.As(err, &exitError) {
|
||||
return fmt.Errorf("wait jukebox: %w", err)
|
||||
}
|
||||
|
||||
if err := j.conn.Close(); err != nil {
|
||||
return fmt.Errorf("close: %w", err)
|
||||
}
|
||||
j.conn.WaitUntilClosed()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) GetPlaylist() ([]string, error) {
|
||||
defer lockr(&j.mu)()
|
||||
|
||||
var playlist mpvPlaylist
|
||||
if err := getDecode(j.conn, &playlist, "playlist"); err != nil {
|
||||
return nil, fmt.Errorf("get playlist: %w", err)
|
||||
}
|
||||
var items []string
|
||||
for _, item := range playlist {
|
||||
items = append(items, item.Filename)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) SetPlaylist(items []string) error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
var playlist mpvPlaylist
|
||||
if err := getDecode(j.conn, &playlist, "playlist"); err != nil {
|
||||
return fmt.Errorf("get playlist: %w", err)
|
||||
}
|
||||
currentPlayingIndex := slices.IndexFunc(playlist, func(pl mpvPlaylistItem) bool {
|
||||
return pl.Current
|
||||
})
|
||||
|
||||
tmp, cleanup, err := tmp()
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temp file: %w", err)
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
var newPlayingIndex = -1
|
||||
for i, item := range items {
|
||||
if !strings.HasPrefix(item, "http") {
|
||||
item, _ = filepath.Abs(item)
|
||||
}
|
||||
if currentPlayingIndex >= 0 && playlist[currentPlayingIndex].Filename == item {
|
||||
newPlayingIndex = i
|
||||
continue // don't add current track to loadlist
|
||||
}
|
||||
|
||||
fmt.Fprintln(tmp, item)
|
||||
}
|
||||
|
||||
if newPlayingIndex < 0 {
|
||||
if _, err := j.conn.Call("loadlist", tmp.Name(), "replace"); err != nil {
|
||||
return fmt.Errorf("load list: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := j.conn.Call("playlist-clear"); err != nil { // leaves current at index 0
|
||||
return fmt.Errorf("clear playlist: %w", err)
|
||||
}
|
||||
if _, err := j.conn.Call("loadlist", tmp.Name(), "append-play"); err != nil {
|
||||
return fmt.Errorf("load list: %w", err)
|
||||
}
|
||||
if newPlayingIndex > 0 {
|
||||
if _, err := j.conn.Call("playlist-move", 0, newPlayingIndex+1); err != nil {
|
||||
return fmt.Errorf("playlist move: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) AppendToPlaylist(items []string) error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
tmp, cleanup, err := tmp()
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temp file: %w", err)
|
||||
}
|
||||
defer cleanup()
|
||||
for _, item := range items {
|
||||
fmt.Fprintln(tmp, item)
|
||||
}
|
||||
if _, err := j.conn.Call("loadlist", tmp.Name(), "append"); err != nil {
|
||||
return fmt.Errorf("load list: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) RemovePlaylistIndex(i int) error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
if _, err := j.conn.Call("playlist-remove", i); err != nil {
|
||||
return fmt.Errorf("playlist remove: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) SkipToPlaylistIndex(i int, offsetSecs int) error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
matchEventSeekable := func(e *mpvipc.Event) bool {
|
||||
seekable, _ := e.Data.(bool)
|
||||
return e.Name == "property-change" &&
|
||||
e.ExtraData["name"] == "seekable" &&
|
||||
seekable
|
||||
}
|
||||
|
||||
if offsetSecs > 0 {
|
||||
if err := j.conn.Set("pause", true); err != nil {
|
||||
return fmt.Errorf("pause: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ch, stop := j.conn.NewEventListener()
|
||||
defer close(stop)
|
||||
|
||||
if _, err := j.conn.Call("playlist-play-index", i); err != nil {
|
||||
return fmt.Errorf("playlist play index: %w", err)
|
||||
}
|
||||
|
||||
if offsetSecs > 0 {
|
||||
if err := waitFor(ch, matchEventSeekable); err != nil {
|
||||
return fmt.Errorf("waiting for file load: %w", err)
|
||||
}
|
||||
if _, err := j.conn.Call("seek", offsetSecs, "absolute"); err != nil {
|
||||
return fmt.Errorf("seek: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := j.conn.Set("pause", false); err != nil {
|
||||
return fmt.Errorf("play: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) ClearPlaylist() error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
if _, err := j.conn.Call("playlist-clear"); err != nil {
|
||||
return fmt.Errorf("seek: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) Pause() error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
if err := j.conn.Set("pause", true); err != nil {
|
||||
return fmt.Errorf("pause: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) Play() error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
if err := j.conn.Set("pause", false); err != nil {
|
||||
return fmt.Errorf("pause: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) SetVolumePct(v int) error {
|
||||
defer lock(&j.mu)()
|
||||
|
||||
if err := j.conn.Set("volume", v); err != nil {
|
||||
return fmt.Errorf("set volume: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *Jukebox) GetVolumePct() (float64, error) {
|
||||
defer lockr(&j.mu)()
|
||||
|
||||
var volume float64
|
||||
if err := getDecode(j.conn, &volume, "volume"); err != nil {
|
||||
return 0, fmt.Errorf("get volume: %w", err)
|
||||
}
|
||||
return volume, nil
|
||||
}
|
||||
|
||||
type Status struct {
|
||||
CurrentIndex int
|
||||
CurrentFilename string
|
||||
Length int
|
||||
Playing bool
|
||||
GainPct int
|
||||
Position int
|
||||
}
|
||||
|
||||
func (j *Jukebox) GetStatus() (*Status, error) {
|
||||
defer lockr(&j.mu)()
|
||||
|
||||
var status Status
|
||||
_ = getDecode(j.conn, &status.Position, "time-pos") // property may not always be there
|
||||
_ = getDecode(j.conn, &status.GainPct, "volume") // property may not always be there
|
||||
|
||||
var playlist mpvPlaylist
|
||||
_ = getDecode(j.conn, &playlist, "playlist")
|
||||
|
||||
status.CurrentIndex = slices.IndexFunc(playlist, func(pl mpvPlaylistItem) bool {
|
||||
return pl.Current
|
||||
})
|
||||
|
||||
status.Length = len(playlist)
|
||||
|
||||
if status.CurrentIndex < 0 {
|
||||
return &status, nil
|
||||
}
|
||||
|
||||
status.CurrentFilename = playlist[status.CurrentIndex].Filename
|
||||
|
||||
var paused bool
|
||||
_ = getDecode(j.conn, &paused, "pause") // property may not always be there
|
||||
status.Playing = !paused
|
||||
|
||||
return &status, nil
|
||||
}
|
||||
|
||||
func getDecode(conn *mpvipc.Connection, dest any, property string) error {
|
||||
raw, err := conn.Get(property)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get property: %w", err)
|
||||
}
|
||||
if err := mapstructure.Decode(raw, dest); err != nil {
|
||||
return fmt.Errorf("decode: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type (
|
||||
mpvPlaylist []mpvPlaylistItem
|
||||
mpvPlaylistItem struct {
|
||||
ID int
|
||||
Filename string
|
||||
Current bool
|
||||
Playing bool
|
||||
}
|
||||
)
|
||||
|
||||
func waitUntil(timeout time.Duration, f func() bool) bool {
|
||||
quit := time.NewTicker(timeout)
|
||||
defer quit.Stop()
|
||||
check := time.NewTicker(100 * time.Millisecond)
|
||||
defer check.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-quit.C:
|
||||
return false
|
||||
case <-check.C:
|
||||
if f() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitFor[T any](ch <-chan T, match func(e T) bool) error {
|
||||
quit := time.NewTicker(1 * time.Second)
|
||||
defer quit.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-quit.C:
|
||||
return ErrMPVTimeout
|
||||
case ev := <-ch:
|
||||
if match(ev) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func tmp() (*os.File, func(), error) {
|
||||
tmp, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create temp file: %w", err)
|
||||
}
|
||||
cleanup := func() {
|
||||
os.Remove(tmp.Name())
|
||||
tmp.Close()
|
||||
}
|
||||
return tmp, cleanup, nil
|
||||
}
|
||||
|
||||
func lock(mu *sync.RWMutex) func() {
|
||||
mu.Lock()
|
||||
return func() {
|
||||
// let mpv "settle" since it seems to return from ipc calls before everything is sorted out
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func lockr(mu *sync.RWMutex) func() {
|
||||
mu.RLock()
|
||||
return mu.RUnlock
|
||||
}
|
||||
|
||||
var mpvVersionExpr = regexp.MustCompile(`mpv\sv?(\d+)\.(\d+)\.(\d+)`)
|
||||
|
||||
func parseMPVVersion(version string) (major, minor, patch int) {
|
||||
m := mpvVersionExpr.FindStringSubmatch(version)
|
||||
if len(m) != 4 {
|
||||
return
|
||||
}
|
||||
major, _ = strconv.Atoi(m[1])
|
||||
minor, _ = strconv.Atoi(m[2])
|
||||
patch, _ = strconv.Atoi(m[3])
|
||||
return
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
package jukebox_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.senan.xyz/gonic/jukebox"
|
||||
)
|
||||
|
||||
func TestPlaySkipReset(t *testing.T) {
|
||||
t.Skip("bit flakey since mpv ipc doesn't block while internal state has settled")
|
||||
|
||||
t.Parallel()
|
||||
j := newJukebox(t)
|
||||
|
||||
require.NoError(t, j.SetPlaylist([]string{
|
||||
testPath("tr_0.mp3"),
|
||||
testPath("tr_1.mp3"),
|
||||
testPath("tr_2.mp3"),
|
||||
testPath("tr_3.mp3"),
|
||||
testPath("tr_4.mp3"),
|
||||
}))
|
||||
|
||||
status, err := j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, status.CurrentIndex)
|
||||
require.Equal(t, testPath("tr_0.mp3"), status.CurrentFilename)
|
||||
require.Equal(t, 5, status.Length)
|
||||
require.Equal(t, true, status.Playing)
|
||||
|
||||
items, err := j.GetPlaylist()
|
||||
require.NoError(t, err)
|
||||
|
||||
itemsSorted := append([]string(nil), items...)
|
||||
sort.Strings(itemsSorted)
|
||||
require.Equal(t, itemsSorted, items)
|
||||
|
||||
require.NoError(t, j.Play())
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, true, status.Playing)
|
||||
|
||||
require.NoError(t, j.Pause())
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, false, status.Playing)
|
||||
|
||||
require.NoError(t, j.Play())
|
||||
|
||||
// skip to 2
|
||||
require.NoError(t, j.SkipToPlaylistIndex(2, 0))
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, status.CurrentIndex)
|
||||
require.Equal(t, testPath("tr_2.mp3"), status.CurrentFilename)
|
||||
require.Equal(t, 5, status.Length)
|
||||
require.Equal(t, true, status.Playing)
|
||||
|
||||
// skip to 3
|
||||
require.NoError(t, j.SkipToPlaylistIndex(3, 0))
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 3, status.CurrentIndex)
|
||||
require.Equal(t, testPath("tr_3.mp3"), status.CurrentFilename)
|
||||
require.Equal(t, 5, status.Length)
|
||||
require.Equal(t, true, status.Playing)
|
||||
|
||||
// just add one more by overwriting the playlist like some clients do
|
||||
// we should move keep the playing indedx
|
||||
require.NoError(t, j.SetPlaylist([]string{
|
||||
"testdata/tr_0.mp3",
|
||||
"testdata/tr_1.mp3",
|
||||
"testdata/tr_2.mp3",
|
||||
"testdata/tr_3.mp3",
|
||||
"testdata/tr_4.mp3",
|
||||
"testdata/tr_5.mp3",
|
||||
}))
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 3, status.CurrentIndex) // index moved to start
|
||||
require.Equal(t, testPath("tr_3.mp3"), status.CurrentFilename)
|
||||
require.Equal(t, 6, status.Length) // we added one more track
|
||||
require.Equal(t, true, status.Playing)
|
||||
|
||||
// new playlist with out current track (tr_2)
|
||||
require.NoError(t, j.SetPlaylist([]string{
|
||||
"testdata/tr_6.mp3",
|
||||
"testdata/tr_7.mp3",
|
||||
"testdata/tr_8.mp3",
|
||||
"testdata/tr_9.mp3",
|
||||
}))
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, status.CurrentIndex) // index unchanged
|
||||
require.Equal(t, testPath("tr_6.mp3"), status.CurrentFilename)
|
||||
require.Equal(t, 4, status.Length)
|
||||
require.Equal(t, true, status.Playing)
|
||||
|
||||
// skip to index 2 (5s long) in the middle of the track
|
||||
require.NoError(t, j.SkipToPlaylistIndex(2, 2))
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, status.CurrentIndex) // index unchanged
|
||||
require.Equal(t, testPath("tr_8.mp3"), status.CurrentFilename)
|
||||
require.Equal(t, 4, status.Length)
|
||||
require.Equal(t, true, status.Playing)
|
||||
require.Equal(t, 2, status.Position) // at new position
|
||||
}
|
||||
|
||||
func TestShuffle(t *testing.T) {
|
||||
t.Skip("bit flakey since mpv ipc doesn't block while internal state has settled")
|
||||
|
||||
t.Parallel()
|
||||
j := newJukebox(t)
|
||||
|
||||
require.NoError(t, j.SetPlaylist([]string{
|
||||
testPath("tr_0.mp3"),
|
||||
testPath("tr_1.mp3"),
|
||||
testPath("tr_2.mp3"),
|
||||
testPath("tr_3.mp3"),
|
||||
testPath("tr_4.mp3"),
|
||||
testPath("tr_5.mp3"),
|
||||
testPath("tr_6.mp3"),
|
||||
testPath("tr_7.mp3"),
|
||||
}))
|
||||
|
||||
require.NoError(t, j.SkipToPlaylistIndex(2, 0))
|
||||
|
||||
status, err := j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, status.CurrentIndex)
|
||||
require.True(t, status.Playing)
|
||||
|
||||
desiredOrder := []string{
|
||||
testPath("tr_2.mp3"), // the was-playing index moves to position 0
|
||||
testPath("tr_1.mp3"),
|
||||
testPath("tr_0.mp3"),
|
||||
testPath("tr_3.mp3"),
|
||||
testPath("tr_5.mp3"),
|
||||
testPath("tr_6.mp3"),
|
||||
testPath("tr_7.mp3"),
|
||||
testPath("tr_4.mp3"),
|
||||
}
|
||||
|
||||
require.NoError(t, j.SetPlaylist(desiredOrder))
|
||||
|
||||
status, err = j.GetStatus()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, status.CurrentIndex)
|
||||
require.Equal(t, len(desiredOrder), status.Length)
|
||||
|
||||
playlist, err := j.GetPlaylist()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, desiredOrder, playlist)
|
||||
}
|
||||
|
||||
func TestVolume(t *testing.T) {
|
||||
t.Skip("bit flakey since mpv ipc doesn't block while internal state has settled")
|
||||
|
||||
t.Parallel()
|
||||
j := newJukebox(t)
|
||||
|
||||
vol, err := j.GetVolumePct()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 100.0, vol)
|
||||
|
||||
require.NoError(t, j.SetVolumePct(69.0))
|
||||
|
||||
vol, err = j.GetVolumePct()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 69.0, vol)
|
||||
|
||||
require.NoError(t, j.SetVolumePct(0.0))
|
||||
|
||||
vol, err = j.GetVolumePct()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0.0, vol)
|
||||
}
|
||||
|
||||
func newJukebox(tb testing.TB) *jukebox.Jukebox {
|
||||
tb.Helper()
|
||||
|
||||
sockPath := filepath.Join(tb.TempDir(), "mpv.sock")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
j := jukebox.New()
|
||||
err := j.Start(
|
||||
ctx,
|
||||
sockPath,
|
||||
[]string{jukebox.MPVArg("--ao", "null")},
|
||||
)
|
||||
if errors.Is(err, jukebox.ErrMPVTooOld) {
|
||||
tb.Skip("old mpv found, skipping")
|
||||
}
|
||||
if err != nil {
|
||||
tb.Fatalf("start jukebox: %v", err)
|
||||
}
|
||||
tb.Cleanup(func() {
|
||||
cancel()
|
||||
})
|
||||
return j
|
||||
}
|
||||
|
||||
func testPath(path string) string {
|
||||
cwd, _ := os.Getwd()
|
||||
return filepath.Join(cwd, "testdata", path)
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1 +0,0 @@
|
||||
5s.mp3
|
||||
@@ -1,355 +0,0 @@
|
||||
package lastfm
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andybalholm/cascadia"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/scrobble"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrLastFM = errors.New("last.fm error")
|
||||
ErrNoUserSession = errors.New("no lastfm user session present")
|
||||
)
|
||||
|
||||
type KeySecretFunc func() (apiKey, secret string, err error)
|
||||
|
||||
type Client struct {
|
||||
httpClient *http.Client
|
||||
keySecret KeySecretFunc
|
||||
}
|
||||
|
||||
func NewClient(keySecret KeySecretFunc) *Client {
|
||||
return NewClientCustom(http.DefaultClient, keySecret)
|
||||
}
|
||||
|
||||
func NewClientCustom(httpClient *http.Client, keySecret KeySecretFunc) *Client {
|
||||
return &Client{httpClient: httpClient, keySecret: keySecret}
|
||||
}
|
||||
|
||||
const (
|
||||
BaseURL = "https://ws.audioscrobbler.com/2.0/"
|
||||
)
|
||||
|
||||
func (c *Client) ArtistGetInfo(artistName string) (Artist, error) {
|
||||
apiKey, _, err := c.keySecret()
|
||||
if err != nil {
|
||||
return Artist{}, fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "artist.getInfo")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("artist", artistName)
|
||||
params.Add("autocorrect", "1")
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return Artist{}, fmt.Errorf("make request: %w", err)
|
||||
}
|
||||
|
||||
return resp.Artist, nil
|
||||
}
|
||||
|
||||
func (c *Client) AlbumGetInfo(artistName, albumName string) (Album, error) {
|
||||
apiKey, _, err := c.keySecret()
|
||||
if err != nil {
|
||||
return Album{}, fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "album.getInfo")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("artist", artistName)
|
||||
params.Add("album", albumName)
|
||||
params.Add("autocorrect", "1")
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return Album{}, fmt.Errorf("make request: %w", err)
|
||||
}
|
||||
|
||||
return resp.Album, nil
|
||||
}
|
||||
|
||||
func (c *Client) ArtistGetTopTracks(artistName string) (TopTracks, error) {
|
||||
apiKey, _, err := c.keySecret()
|
||||
if err != nil {
|
||||
return TopTracks{}, fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "artist.getTopTracks")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("artist", artistName)
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return TopTracks{}, fmt.Errorf("make request: %w", err)
|
||||
}
|
||||
return resp.TopTracks, nil
|
||||
}
|
||||
|
||||
func (c *Client) TrackGetSimilarTracks(artistName, trackName string) (SimilarTracks, error) {
|
||||
apiKey, _, err := c.keySecret()
|
||||
if err != nil {
|
||||
return SimilarTracks{}, fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "track.getSimilar")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("track", trackName)
|
||||
params.Add("artist", artistName)
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return SimilarTracks{}, fmt.Errorf("make request: %w", err)
|
||||
}
|
||||
return resp.SimilarTracks, nil
|
||||
}
|
||||
|
||||
func (c *Client) ArtistGetSimilar(artistName string) (SimilarArtists, error) {
|
||||
apiKey, _, err := c.keySecret()
|
||||
if err != nil {
|
||||
return SimilarArtists{}, fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "artist.getSimilar")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("artist", artistName)
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return SimilarArtists{}, fmt.Errorf("making similar artists GET: %w", err)
|
||||
}
|
||||
return resp.SimilarArtists, nil
|
||||
}
|
||||
|
||||
func (c *Client) UserGetLovedTracks(userName string) (LovedTracks, error) {
|
||||
apiKey, _, err := c.keySecret()
|
||||
if err != nil {
|
||||
return LovedTracks{}, fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "user.getLovedTracks")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("user", userName)
|
||||
|
||||
var (
|
||||
page = 1
|
||||
limit = 1000
|
||||
)
|
||||
|
||||
var loved LovedTracks
|
||||
for {
|
||||
params.Set("page", fmt.Sprint(page))
|
||||
params.Set("limit", fmt.Sprint(limit))
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return LovedTracks{}, fmt.Errorf("making user get loved tracks GET: %w", err)
|
||||
}
|
||||
|
||||
loved.Tracks = append(loved.Tracks, resp.LovedTracks.Tracks...)
|
||||
if len(resp.LovedTracks.Tracks) < limit {
|
||||
break
|
||||
}
|
||||
|
||||
page++
|
||||
}
|
||||
|
||||
return loved, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetSession(token string) (string, error) {
|
||||
apiKey, secret, err := c.keySecret()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "auth.getSession")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("token", token)
|
||||
params.Add("api_sig", GetParamSignature(params, secret))
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("make request: %w", err)
|
||||
}
|
||||
return resp.Session.Key, nil
|
||||
}
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
|
||||
|
||||
func (c *Client) StealArtistImage(artistURL string) (string, error) {
|
||||
resp, err := c.httpClient.Get(artistURL) //nolint:gosec
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("get artist url: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return "", fmt.Errorf("get artist url: %s", resp.Status)
|
||||
}
|
||||
|
||||
node, err := html.Parse(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse html: %w", err)
|
||||
}
|
||||
|
||||
n := cascadia.Query(node, artistOpenGraphQuery)
|
||||
if n == nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
var imageURL string
|
||||
for _, attr := range n.Attr {
|
||||
if attr.Key == "content" {
|
||||
imageURL = attr.Val
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return imageURL, nil
|
||||
}
|
||||
|
||||
func (c *Client) IsUserAuthenticated(user db.User) bool {
|
||||
return user.LastFMSession != ""
|
||||
}
|
||||
|
||||
func (c *Client) Scrobble(user db.User, track scrobble.Track, stamp time.Time, submission bool) error {
|
||||
apiKey, secret, err := c.keySecret()
|
||||
if err != nil {
|
||||
return fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
if !c.IsUserAuthenticated(user) {
|
||||
return ErrNoUserSession
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
if submission {
|
||||
params.Add("method", "track.Scrobble")
|
||||
params.Add("timestamp", strconv.Itoa(int(stamp.Unix()))) // last.fm wants the timestamp in seconds
|
||||
} else {
|
||||
params.Add("method", "track.updateNowPlaying")
|
||||
}
|
||||
|
||||
params.Add("artist", track.Artist)
|
||||
params.Add("track", track.Track)
|
||||
params.Add("trackNumber", strconv.Itoa(int(track.TrackNumber)))
|
||||
params.Add("album", track.Album)
|
||||
params.Add("albumArtist", track.AlbumArtist)
|
||||
params.Add("duration", strconv.Itoa(int(track.Duration.Seconds())))
|
||||
|
||||
if track.MusicBrainzID != "" {
|
||||
params.Add("mbid", track.MusicBrainzID)
|
||||
}
|
||||
|
||||
params.Add("sk", user.LastFMSession)
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("api_sig", GetParamSignature(params, secret))
|
||||
|
||||
_, err = c.makeRequest(http.MethodPost, params)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) LoveTrack(user *db.User, track *db.Track) error {
|
||||
apiKey, secret, err := c.keySecret()
|
||||
if err != nil {
|
||||
return fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
if !c.IsUserAuthenticated(*user) {
|
||||
return ErrNoUserSession
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "track.love")
|
||||
params.Add("track", track.TagTitle)
|
||||
params.Add("artist", track.TagTrackArtist)
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("sk", user.LastFMSession)
|
||||
params.Add("api_sig", GetParamSignature(params, secret))
|
||||
|
||||
_, err = c.makeRequest(http.MethodPost, params)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) GetCurrentUser(user *db.User) (User, error) {
|
||||
apiKey, secret, err := c.keySecret()
|
||||
if err != nil {
|
||||
return User{}, fmt.Errorf("get key and secret: %w", err)
|
||||
}
|
||||
if !c.IsUserAuthenticated(*user) {
|
||||
return User{}, ErrNoUserSession
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("method", "user.getInfo")
|
||||
params.Add("api_key", apiKey)
|
||||
params.Add("sk", user.LastFMSession)
|
||||
params.Add("api_sig", GetParamSignature(params, secret))
|
||||
|
||||
resp, err := c.makeRequest(http.MethodGet, params)
|
||||
if err != nil {
|
||||
return User{}, fmt.Errorf("make request: %w", err)
|
||||
}
|
||||
return resp.User, nil
|
||||
}
|
||||
|
||||
func (c *Client) makeRequest(method string, params url.Values) (LastFM, error) {
|
||||
req, err := http.NewRequest(method, BaseURL, nil)
|
||||
if err != nil {
|
||||
return LastFM{}, fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
|
||||
req.URL.RawQuery = params.Encode()
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return LastFM{}, fmt.Errorf("get: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var lastfm LastFM
|
||||
if err := xml.NewDecoder(resp.Body).Decode(&lastfm); err != nil {
|
||||
return LastFM{}, fmt.Errorf("decoding: %w", err)
|
||||
}
|
||||
|
||||
if lastfm.Error.Code != 0 {
|
||||
return LastFM{}, fmt.Errorf("%v: %w", lastfm.Error.Value, ErrLastFM)
|
||||
}
|
||||
return lastfm, nil
|
||||
}
|
||||
|
||||
func GetParamSignature(params url.Values, secret string) string {
|
||||
// the parameters must be in order before hashing
|
||||
paramKeys := make([]string, 0, len(params))
|
||||
for k := range params {
|
||||
paramKeys = append(paramKeys, k)
|
||||
}
|
||||
sort.Strings(paramKeys)
|
||||
var toHash strings.Builder
|
||||
for _, k := range paramKeys {
|
||||
toHash.WriteString(k)
|
||||
toHash.WriteString(params[k][0])
|
||||
}
|
||||
toHash.WriteString(secret)
|
||||
hash := md5.Sum([]byte(toHash.String()))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
@@ -1,580 +0,0 @@
|
||||
//nolint:goconst
|
||||
package lastfm_test
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
"go.senan.xyz/gonic/lastfm/mockclient"
|
||||
"go.senan.xyz/gonic/scrobble"
|
||||
)
|
||||
|
||||
func TestArtistGetInfo(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{"method": []string{"artist.getInfo"}, "api_key": []string{"apiKey1"}, "artist": []string{"Artist 1"}, "autocorrect": []string{"1"}}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(mockclient.ArtistGetInfoResponse)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.ArtistGetInfo("Artist 1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, lastfm.Artist{
|
||||
XMLName: xml.Name{
|
||||
Local: "artist",
|
||||
},
|
||||
Name: "Artist 1",
|
||||
MBID: "366c1119-ec4f-4312-b729-a5637d148e3e",
|
||||
Streamable: "0",
|
||||
Stats: struct {
|
||||
Listeners string `xml:"listeners"`
|
||||
Playcount string `xml:"playcount"`
|
||||
}{
|
||||
Listeners: "1",
|
||||
Playcount: "2",
|
||||
},
|
||||
URL: "https://www.last.fm/music/Artist+1",
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Size: "small",
|
||||
Text: "https://last.fm/artist-1-small.png",
|
||||
},
|
||||
},
|
||||
Bio: lastfm.ArtistBio{
|
||||
Published: "13 May 2023, 00:24",
|
||||
Summary: "Summary",
|
||||
Content: "Content",
|
||||
},
|
||||
Similar: struct {
|
||||
Artists []lastfm.Artist `xml:"artist"`
|
||||
}{
|
||||
Artists: []lastfm.Artist{
|
||||
{
|
||||
XMLName: xml.Name{
|
||||
Local: "artist",
|
||||
},
|
||||
Name: "Similar Artist 1",
|
||||
URL: "https://www.last.fm/music/Similar+Artist+1",
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Size: "small",
|
||||
Text: "https://last.fm/similar-artist-1-small.png",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Tags: struct {
|
||||
Tag []lastfm.ArtistTag `xml:"tag"`
|
||||
}{
|
||||
Tag: []lastfm.ArtistTag{
|
||||
{
|
||||
Name: "tag1",
|
||||
URL: "https://www.last.fm/tag/tag1",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, actual)
|
||||
}
|
||||
|
||||
func TestArtistGetInfoClientRequestFails(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"artist.getInfo"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"artist": []string{"Artist 1"},
|
||||
"autocorrect": []string{"1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.ArtistGetInfo("Artist 1")
|
||||
require.Error(t, err)
|
||||
require.Zero(t, actual)
|
||||
}
|
||||
|
||||
func TestArtistGetTopTracks(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"artist.getTopTracks"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"artist": []string{"artist1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(mockclient.ArtistGetTopTracksResponse)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.ArtistGetTopTracks("artist1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, lastfm.TopTracks{
|
||||
Artist: "Artist 1",
|
||||
XMLName: xml.Name{
|
||||
Local: "toptracks",
|
||||
},
|
||||
Tracks: []lastfm.Track{
|
||||
{
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Text: "https://last.fm/track-1-small.png",
|
||||
Size: "small",
|
||||
},
|
||||
{
|
||||
Text: "https://last.fm/track-1-large.png",
|
||||
Size: "large",
|
||||
},
|
||||
},
|
||||
Listeners: 2,
|
||||
MBID: "fdfc47cb-69d3-4318-ba71-d54fbc20169a",
|
||||
Name: "Track 1",
|
||||
PlayCount: 1,
|
||||
Rank: 1,
|
||||
URL: "https://www.last.fm/music/Artist+1/_/Track+1",
|
||||
},
|
||||
{
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Text: "https://last.fm/track-2-small.png",
|
||||
Size: "small",
|
||||
},
|
||||
{
|
||||
Text: "https://last.fm/track-2-large.png",
|
||||
Size: "large",
|
||||
},
|
||||
},
|
||||
Listeners: 3,
|
||||
MBID: "cf32e694-1ea6-4ba0-9e8b-d5f1950da9c8",
|
||||
Name: "Track 2",
|
||||
PlayCount: 2,
|
||||
Rank: 2,
|
||||
URL: "https://www.last.fm/music/Artist+1/_/Track+2",
|
||||
},
|
||||
},
|
||||
}, actual)
|
||||
}
|
||||
|
||||
func TestArtistGetTopTracksClientRequestFails(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"artist.getTopTracks"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"artist": []string{"artist1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.ArtistGetTopTracks("artist1")
|
||||
require.Error(t, err)
|
||||
require.Zero(t, actual)
|
||||
}
|
||||
|
||||
func TestArtistGetSimilar(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"artist.getSimilar"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"artist": []string{"artist1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(mockclient.ArtistGetSimilarResponse)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.ArtistGetSimilar("artist1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, lastfm.SimilarArtists{
|
||||
XMLName: xml.Name{
|
||||
Local: "similarartists",
|
||||
},
|
||||
Artist: "Artist 1",
|
||||
Artists: []lastfm.Artist{
|
||||
{
|
||||
XMLName: xml.Name{
|
||||
Local: "artist",
|
||||
},
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Text: "https://last.fm/artist-2-small.png",
|
||||
Size: "small",
|
||||
},
|
||||
{
|
||||
Text: "https://last.fm/artist-2-large.png",
|
||||
Size: "large",
|
||||
},
|
||||
},
|
||||
MBID: "d2addad9-3fc4-4ce8-9cd4-63f2a19bb922",
|
||||
Name: "Artist 2",
|
||||
Similar: struct {
|
||||
Artists []lastfm.Artist `xml:"artist"`
|
||||
}{},
|
||||
Streamable: "0",
|
||||
URL: "https://www.last.fm/music/Artist+2",
|
||||
},
|
||||
{
|
||||
XMLName: xml.Name{
|
||||
Local: "artist",
|
||||
},
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Text: "https://last.fm/artist-3-small.png",
|
||||
Size: "small",
|
||||
},
|
||||
{
|
||||
Text: "https://last.fm/artist-3-large.png",
|
||||
Size: "large",
|
||||
},
|
||||
},
|
||||
MBID: "dc95d067-df3e-4b83-a5fe-5ec773b1883f",
|
||||
Name: "Artist 3",
|
||||
Similar: struct {
|
||||
Artists []lastfm.Artist `xml:"artist"`
|
||||
}{},
|
||||
Streamable: "0",
|
||||
URL: "https://www.last.fm/music/Artist+3",
|
||||
},
|
||||
},
|
||||
}, actual)
|
||||
}
|
||||
|
||||
func TestArtistGetSimilarClientRequestFails(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"artist.getSimilar"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"artist": []string{"artist1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.ArtistGetSimilar("artist1")
|
||||
require.Error(t, err)
|
||||
require.Zero(t, actual)
|
||||
}
|
||||
|
||||
func TestTrackGetSimilarTracks(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"track.getSimilar"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"artist": []string{"artist1"},
|
||||
"track": []string{"track1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(mockclient.TrackGetSimilarResponse)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.TrackGetSimilarTracks("artist1", "track1")
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, lastfm.SimilarTracks{
|
||||
Artist: "Artist 1",
|
||||
Track: "Track 1",
|
||||
XMLName: xml.Name{
|
||||
Local: "similartracks",
|
||||
},
|
||||
Tracks: []lastfm.Track{
|
||||
{
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Text: "https://last.fm/track-1-small.png",
|
||||
Size: "small",
|
||||
},
|
||||
{
|
||||
Text: "https://last.fm/track-1-large.png",
|
||||
Size: "large",
|
||||
},
|
||||
},
|
||||
MBID: "7096931c-bf82-4896-b1e7-42b60a0e16ea",
|
||||
Name: "Track 1",
|
||||
PlayCount: 1,
|
||||
URL: "https://www.last.fm/music/Artist+1/_/Track+1",
|
||||
},
|
||||
{
|
||||
Image: []lastfm.Image{
|
||||
{
|
||||
Text: "https://last.fm/track-2-small.png",
|
||||
Size: "small",
|
||||
},
|
||||
{
|
||||
Text: "https://last.fm/track-2-large.png",
|
||||
Size: "large",
|
||||
},
|
||||
},
|
||||
MBID: "2aff1321-149f-4000-8762-3468c917600c",
|
||||
Name: "Track 2",
|
||||
PlayCount: 2,
|
||||
URL: "https://www.last.fm/music/Artist+2/_/Track+2",
|
||||
},
|
||||
},
|
||||
}, actual)
|
||||
}
|
||||
|
||||
func TestTrackGetSimilarTracksClientRequestFails(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"track.getSimilar"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"artist": []string{"artist1"},
|
||||
"track": []string{"track1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.TrackGetSimilarTracks("artist1", "track1")
|
||||
require.Error(t, err)
|
||||
require.Zero(t, actual)
|
||||
}
|
||||
|
||||
func TestGetSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"auth.getSession"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"api_sig": []string{"b872a708a0b8b1d9fc1230b1cb6493f8"},
|
||||
"token": []string{"token1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(mockclient.GetSessionResponse)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "secret1", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.GetSession("token1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "sessionKey1", actual)
|
||||
}
|
||||
|
||||
func TestGetSessionClientRequestFails(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"method": []string{"auth.getSession"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"api_sig": []string{"b872a708a0b8b1d9fc1230b1cb6493f8"},
|
||||
"token": []string{"token1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}),
|
||||
func() (string, string, error) {
|
||||
return "apiKey1", "secret1", nil
|
||||
},
|
||||
)
|
||||
|
||||
actual, err := client.GetSession("token1")
|
||||
|
||||
require.Error(t, err)
|
||||
require.Zero(t, actual)
|
||||
}
|
||||
|
||||
func TestScrobble(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClientCustom(
|
||||
mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPost, r.Method)
|
||||
require.Equal(t, url.Values{
|
||||
"album": []string{"album1"},
|
||||
"albumArtist": []string{"artist1"},
|
||||
"api_key": []string{"apiKey1"},
|
||||
"api_sig": []string{"d235a0b911eb4923953f496c61a2a6af"},
|
||||
"artist": []string{"trackArtist1"},
|
||||
"duration": []string{"100"},
|
||||
"method": []string{"track.Scrobble"},
|
||||
"sk": []string{"lastFMSession1"},
|
||||
"mbid": []string{"916b242d-d439-4ae4-a439-556eef99c06e"},
|
||||
"timestamp": []string{"1691843641"},
|
||||
"track": []string{"title1"},
|
||||
"trackNumber": []string{"1"},
|
||||
}, r.URL.Query())
|
||||
|
||||
require.Equal(t, "/2.0/", r.URL.Path)
|
||||
require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(mockclient.ArtistGetTopTracksResponse)
|
||||
}),
|
||||
func() (apiKey string, secret string, err error) {
|
||||
return "apiKey1", "secret1", nil
|
||||
},
|
||||
)
|
||||
|
||||
user := db.User{
|
||||
LastFMSession: "lastFMSession1",
|
||||
}
|
||||
track := scrobble.Track{
|
||||
Track: "title1",
|
||||
Artist: "trackArtist1",
|
||||
Album: "album1",
|
||||
AlbumArtist: "artist1",
|
||||
TrackNumber: 1,
|
||||
Duration: 100 * time.Second,
|
||||
MusicBrainzID: "916b242d-d439-4ae4-a439-556eef99c06e",
|
||||
}
|
||||
|
||||
stamp := time.Date(2023, 8, 12, 12, 34, 1, 200, time.UTC)
|
||||
|
||||
err := client.Scrobble(user, track, stamp, true)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestScrobbleErrorsWithoutLastFMSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := lastfm.NewClient(func() (apiKey string, secret string, err error) {
|
||||
return "", "", nil
|
||||
})
|
||||
|
||||
err := client.Scrobble(db.User{}, scrobble.Track{}, time.Now(), false)
|
||||
require.ErrorIs(t, err, lastfm.ErrNoUserSession)
|
||||
}
|
||||
|
||||
func TestScrobbleFailsWithoutLastFMAPIKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
user := db.User{
|
||||
LastFMSession: "lastFMSession1",
|
||||
}
|
||||
|
||||
scrobbler := lastfm.NewClient(func() (string, string, error) {
|
||||
return "", "", fmt.Errorf("no keys")
|
||||
})
|
||||
|
||||
err := scrobbler.Scrobble(user, scrobble.Track{}, time.Now(), false)
|
||||
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestGetParamSignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("ccc", "CCC")
|
||||
params.Add("bbb", "BBB")
|
||||
params.Add("aaa", "AAA")
|
||||
params.Add("ddd", "DDD")
|
||||
actual := lastfm.GetParamSignature(params, "secret")
|
||||
expected := fmt.Sprintf("%x", md5.Sum([]byte(
|
||||
"aaaAAAbbbBBBcccCCCdddDDDsecret",
|
||||
)))
|
||||
if actual != expected {
|
||||
t.Errorf("expected %x, got %s", expected, actual)
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<lfm status="ok">
|
||||
<artist>
|
||||
<name>Artist 1</name>
|
||||
<mbid>366c1119-ec4f-4312-b729-a5637d148e3e</mbid>
|
||||
<url>https://www.last.fm/music/Artist+1</url>
|
||||
<image size="small">https://last.fm/artist-1-small.png</image>
|
||||
<streamable>0</streamable>
|
||||
<ontour>0</ontour>
|
||||
<stats>
|
||||
<listeners>1</listeners>
|
||||
<playcount>2</playcount>
|
||||
</stats>
|
||||
<similar>
|
||||
<artist>
|
||||
<name>Similar Artist 1</name>
|
||||
<url>https://www.last.fm/music/Similar+Artist+1</url>
|
||||
<image size="small">https://last.fm/similar-artist-1-small.png</image>
|
||||
</artist>
|
||||
</similar>
|
||||
<tags>
|
||||
<tag>
|
||||
<name>tag1</name>
|
||||
<url>https://www.last.fm/tag/tag1</url>
|
||||
</tag>
|
||||
</tags>
|
||||
<bio>
|
||||
<links>
|
||||
<link rel="original" href="https://last.fm/music/Artist+1/+wiki"></link>
|
||||
</links>
|
||||
<published>13 May 2023, 00:24</published>
|
||||
<summary>Summary</summary>
|
||||
<content>Content</content>
|
||||
</bio>
|
||||
</artist>
|
||||
</lfm>
|
||||
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<lfm status="ok">
|
||||
<similarartists artist="Artist 1">
|
||||
<artist>
|
||||
<name>Artist 2</name>
|
||||
<mbid>d2addad9-3fc4-4ce8-9cd4-63f2a19bb922</mbid>
|
||||
<match>1</match>
|
||||
<url>https://www.last.fm/music/Artist+2</url>
|
||||
<image size="small">https://last.fm/artist-2-small.png</image>
|
||||
<image size="large">https://last.fm/artist-2-large.png</image>
|
||||
<streamable>0</streamable>
|
||||
</artist>
|
||||
<artist>
|
||||
<name>Artist 3</name>
|
||||
<mbid>dc95d067-df3e-4b83-a5fe-5ec773b1883f</mbid>
|
||||
<match>0.790991</match>
|
||||
<url>https://www.last.fm/music/Artist+3</url>
|
||||
<image size="small">https://last.fm/artist-3-small.png</image>
|
||||
<image size="large">https://last.fm/artist-3-large.png</image>
|
||||
<streamable>0</streamable>
|
||||
</artist>
|
||||
</similarartists>
|
||||
</lfm>
|
||||
@@ -1,35 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<lfm status="ok">
|
||||
<toptracks artist="Artist 1" page="1" perPage="50" totalPages="5" total="225">
|
||||
<track rank="1">
|
||||
<name>Track 1</name>
|
||||
<playcount>1</playcount>
|
||||
<listeners>2</listeners>
|
||||
<mbid>fdfc47cb-69d3-4318-ba71-d54fbc20169a</mbid>
|
||||
<url>https://www.last.fm/music/Artist+1/_/Track+1</url>
|
||||
<streamable>0</streamable>
|
||||
<artist>
|
||||
<name>Artist 1</name>
|
||||
<mbid>366c1119-ec4f-4312-b729-a5637d148e3e</mbid>
|
||||
<url>https://www.last.fm/music/Artist+1</url>
|
||||
</artist>
|
||||
<image size="small">https://last.fm/track-1-small.png</image>
|
||||
<image size="large">https://last.fm/track-1-large.png</image>
|
||||
</track>
|
||||
<track rank="2">
|
||||
<name>Track 2</name>
|
||||
<playcount>2</playcount>
|
||||
<listeners>3</listeners>
|
||||
<mbid>cf32e694-1ea6-4ba0-9e8b-d5f1950da9c8</mbid>
|
||||
<url>https://www.last.fm/music/Artist+1/_/Track+2</url>
|
||||
<streamable>0</streamable>
|
||||
<artist>
|
||||
<name>Artist 1</name>
|
||||
<mbid>366c1119-ec4f-4312-b729-a5637d148e3e</mbid>
|
||||
<url>https://www.last.fm/music/Artist+1</url>
|
||||
</artist>
|
||||
<image size="small">https://last.fm/track-2-small.png</image>
|
||||
<image size="large">https://last.fm/track-2-large.png</image>
|
||||
</track>
|
||||
</toptracks>
|
||||
</lfm>
|
||||
@@ -1,7 +0,0 @@
|
||||
<lfm status="ok">
|
||||
<session>
|
||||
<name>username1</name>
|
||||
<key>sessionKey1</key>
|
||||
<subscriber>0</subscriber>
|
||||
</session>
|
||||
</lfm>
|
||||
@@ -1,44 +0,0 @@
|
||||
package mockclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
_ "embed"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func New(tb testing.TB, handler http.HandlerFunc) *http.Client {
|
||||
tb.Helper()
|
||||
|
||||
server := httptest.NewTLSServer(handler)
|
||||
tb.Cleanup(server.Close)
|
||||
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return net.Dial(network, server.Listener.Addr().String())
|
||||
},
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true, //nolint:gosec
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
//go:embed artist_get_info_response.xml
|
||||
var ArtistGetInfoResponse []byte
|
||||
|
||||
//go:embed artist_get_top_tracks_response.xml
|
||||
var ArtistGetTopTracksResponse []byte
|
||||
|
||||
//go:embed artist_get_similar_response.xml
|
||||
var ArtistGetSimilarResponse []byte
|
||||
|
||||
//go:embed track_get_similar_response.xml
|
||||
var TrackGetSimilarResponse []byte
|
||||
|
||||
//go:embed get_session_response.xml
|
||||
var GetSessionResponse []byte
|
||||
@@ -1,37 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<lfm status="ok">
|
||||
<similartracks artist="Artist 1" track="Track 1">
|
||||
<track>
|
||||
<name>Track 1</name>
|
||||
<playcount>1</playcount>
|
||||
<mbid>7096931c-bf82-4896-b1e7-42b60a0e16ea</mbid>
|
||||
<match>1.000</match>
|
||||
<url>https://www.last.fm/music/Artist+1/_/Track+1</url>
|
||||
<streamable fulltrack="0">0</streamable>
|
||||
<duration>80</duration>
|
||||
<artist>
|
||||
<name>Artist+1</name>
|
||||
<mbid>366c1119-ec4f-4312-b729-a5637d148e3e</mbid>
|
||||
<url>https://www.last.fm/music/Artist+1</url>
|
||||
</artist>
|
||||
<image size="small">https://last.fm/track-1-small.png</image>
|
||||
<image size="large">https://last.fm/track-1-large.png</image>
|
||||
</track>
|
||||
<track>
|
||||
<name>Track 2</name>
|
||||
<playcount>2</playcount>
|
||||
<mbid>2aff1321-149f-4000-8762-3468c917600c</mbid>
|
||||
<match>0.422</match>
|
||||
<url>https://www.last.fm/music/Artist+2/_/Track+2</url>
|
||||
<streamable fulltrack="0">0</streamable>
|
||||
<duration>80</duration>
|
||||
<artist>
|
||||
<name>Artist+2</name>
|
||||
<mbid>9842b07f-956b-4c36-8ce1-884b4b96254d</mbid>
|
||||
<url>https://www.last.fm/music/Artist+1</url>
|
||||
</artist>
|
||||
<image size="small">https://last.fm/track-2-small.png</image>
|
||||
<image size="large">https://last.fm/track-2-large.png</image>
|
||||
</track>
|
||||
</similartracks>
|
||||
</lfm>
|
||||
@@ -1,191 +0,0 @@
|
||||
package lastfm
|
||||
|
||||
import "encoding/xml"
|
||||
|
||||
type (
|
||||
LastFM struct {
|
||||
XMLName xml.Name `xml:"lfm"`
|
||||
Status string `xml:"status,attr"`
|
||||
Session Session `xml:"session"`
|
||||
Error Error `xml:"error"`
|
||||
Artist Artist `xml:"artist"`
|
||||
Album Album `xml:"album"`
|
||||
TopTracks TopTracks `xml:"toptracks"`
|
||||
SimilarTracks SimilarTracks `xml:"similartracks"`
|
||||
SimilarArtists SimilarArtists `xml:"similarartists"`
|
||||
LovedTracks LovedTracks `xml:"lovedtracks"`
|
||||
User User `xml:"user"`
|
||||
}
|
||||
|
||||
Session struct {
|
||||
Name string `xml:"name"`
|
||||
Key string `xml:"key"`
|
||||
Subscriber uint `xml:"subscriber"`
|
||||
}
|
||||
|
||||
Error struct {
|
||||
Code uint `xml:"code,attr"`
|
||||
Value string `xml:",chardata"`
|
||||
}
|
||||
|
||||
SimilarArtist struct {
|
||||
XMLName xml.Name `xml:"artist"`
|
||||
Name string `xml:"name"`
|
||||
MBID string `xml:"mbid"`
|
||||
URL string `xml:"url"`
|
||||
Image []Image `xml:"image"`
|
||||
Streamable string `xml:"streamable"`
|
||||
}
|
||||
|
||||
Image struct {
|
||||
Text string `xml:",chardata"`
|
||||
Size string `xml:"size,attr"`
|
||||
}
|
||||
|
||||
Artist struct {
|
||||
XMLName xml.Name `xml:"artist"`
|
||||
Name string `xml:"name"`
|
||||
MBID string `xml:"mbid"`
|
||||
URL string `xml:"url"`
|
||||
Image []Image `xml:"image"`
|
||||
Streamable string `xml:"streamable"`
|
||||
Stats struct {
|
||||
Listeners string `xml:"listeners"`
|
||||
Playcount string `xml:"playcount"`
|
||||
} `xml:"stats"`
|
||||
Similar struct {
|
||||
Artists []Artist `xml:"artist"`
|
||||
} `xml:"similar"`
|
||||
Tags struct {
|
||||
Tag []ArtistTag `xml:"tag"`
|
||||
} `xml:"tags"`
|
||||
Bio ArtistBio `xml:"bio"`
|
||||
}
|
||||
|
||||
Album struct {
|
||||
XMLName xml.Name `xml:"album"`
|
||||
Name string `xml:"name"`
|
||||
Artist string `xml:"artist"`
|
||||
MBID string `xml:"mbid"`
|
||||
URL string `xml:"url"`
|
||||
Image []struct {
|
||||
Text string `xml:",chardata"`
|
||||
Size string `xml:"size,attr"`
|
||||
} `xml:"image"`
|
||||
Listeners string `xml:"listeners"`
|
||||
Playcount string `xml:"playcount"`
|
||||
Tracks struct {
|
||||
Text string `xml:",chardata"`
|
||||
Track []struct {
|
||||
Text string `xml:",chardata"`
|
||||
Rank string `xml:"rank,attr"`
|
||||
Name string `xml:"name"`
|
||||
URL string `xml:"url"`
|
||||
Duration string `xml:"duration"`
|
||||
Streamable struct {
|
||||
Text string `xml:",chardata"`
|
||||
Fulltrack string `xml:"fulltrack,attr"`
|
||||
} `xml:"streamable"`
|
||||
Artist struct {
|
||||
Text string `xml:",chardata"`
|
||||
Name string `xml:"name"`
|
||||
Mbid string `xml:"mbid"`
|
||||
URL string `xml:"url"`
|
||||
} `xml:"artist"`
|
||||
} `xml:"track"`
|
||||
} `xml:"tracks"`
|
||||
Tags struct {
|
||||
Text string `xml:",chardata"`
|
||||
Tag []struct {
|
||||
Text string `xml:",chardata"`
|
||||
Name string `xml:"name"`
|
||||
URL string `xml:"url"`
|
||||
} `xml:"tag"`
|
||||
} `xml:"tags"`
|
||||
Wiki struct {
|
||||
Text string `xml:",chardata"`
|
||||
Published string `xml:"published"`
|
||||
Summary string `xml:"summary"`
|
||||
Content string `xml:"content"`
|
||||
} `xml:"wiki"`
|
||||
}
|
||||
|
||||
ArtistTag struct {
|
||||
Name string `xml:"name"`
|
||||
URL string `xml:"url"`
|
||||
}
|
||||
|
||||
ArtistBio struct {
|
||||
Published string `xml:"published"`
|
||||
Summary string `xml:"summary"`
|
||||
Content string `xml:"content"`
|
||||
}
|
||||
|
||||
TopTracks struct {
|
||||
XMLName xml.Name `xml:"toptracks"`
|
||||
Artist string `xml:"artist,attr"`
|
||||
Tracks []Track `xml:"track"`
|
||||
}
|
||||
|
||||
SimilarTracks struct {
|
||||
XMLName xml.Name `xml:"similartracks"`
|
||||
Artist string `xml:"artist,attr"`
|
||||
Track string `xml:"track,attr"`
|
||||
Tracks []Track `xml:"track"`
|
||||
}
|
||||
|
||||
SimilarArtists struct {
|
||||
XMLName xml.Name `xml:"similarartists"`
|
||||
Artist string `xml:"artist,attr"`
|
||||
Artists []Artist `xml:"artist"`
|
||||
}
|
||||
|
||||
Track struct {
|
||||
Rank int `xml:"rank,attr"`
|
||||
Tracks []Track `xml:"track"`
|
||||
Name string `xml:"name"`
|
||||
MBID string `xml:"mbid"`
|
||||
PlayCount int `xml:"playcount"`
|
||||
Listeners int `xml:"listeners"`
|
||||
URL string `xml:"url"`
|
||||
Image []Image `xml:"image"`
|
||||
}
|
||||
|
||||
LovedTracks struct {
|
||||
XMLName xml.Name `xml:"lovedtracks"`
|
||||
Tracks []struct {
|
||||
Track
|
||||
Date struct {
|
||||
Text string `xml:",chardata"`
|
||||
UTS string `xml:"uts,attr"`
|
||||
} `xml:"date"`
|
||||
Artist Artist `xml:"artist"`
|
||||
} `xml:"track"`
|
||||
}
|
||||
|
||||
User struct {
|
||||
Text string `xml:",chardata"`
|
||||
Name string `xml:"name"`
|
||||
Realname string `xml:"realname"`
|
||||
Image []struct {
|
||||
Text string `xml:",chardata"`
|
||||
Size string `xml:"size,attr"`
|
||||
} `xml:"image"`
|
||||
URL string `xml:"url"`
|
||||
Country string `xml:"country"`
|
||||
Age string `xml:"age"`
|
||||
Gender string `xml:"gender"`
|
||||
Subscriber string `xml:"subscriber"`
|
||||
Playcount string `xml:"playcount"`
|
||||
Playlists string `xml:"playlists"`
|
||||
Bootstrap string `xml:"bootstrap"`
|
||||
Registered struct {
|
||||
Text string `xml:",chardata"`
|
||||
Unixtime string `xml:"unixtime,attr"`
|
||||
} `xml:"registered"`
|
||||
Type string `xml:"type"`
|
||||
ArtistCount string `xml:"artist_count"`
|
||||
AlbumCount string `xml:"album_count"`
|
||||
TrackCount string `xml:"track_count"`
|
||||
}
|
||||
)
|
||||
@@ -1,225 +0,0 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
// LDAPStore maps users to a cached password
|
||||
type LDAPStore map[string]CachedLDAPpassword
|
||||
|
||||
// Add caches a password username set.
|
||||
func (store LDAPStore) Add(username, password string) {
|
||||
store[username] = CachedLDAPpassword{
|
||||
Password: password,
|
||||
ExpiresAt: time.Now().Add(time.Hour * 8), // Keep the password valid for 8 hours.
|
||||
}
|
||||
}
|
||||
|
||||
// IsValid checks if a user's password is stored in the cache and checks if a
|
||||
// given password is valid.
|
||||
func (store LDAPStore) IsValid(username, password string) bool {
|
||||
cached, ok := store[username]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
if cached.Password != password {
|
||||
return false
|
||||
}
|
||||
|
||||
return cached.IsValid()
|
||||
}
|
||||
|
||||
// CachedLDAPpassword stores an LDAP user's password and a time at which the
|
||||
// server should no longer accept it.
|
||||
type CachedLDAPpassword struct {
|
||||
Password string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (password CachedLDAPpassword) IsValid() bool {
|
||||
return password.ExpiresAt.After(time.Now())
|
||||
}
|
||||
|
||||
// Cofig stores the user's LDAP server options.
|
||||
type Config struct {
|
||||
BindUser string
|
||||
BindPass string
|
||||
BaseDN string
|
||||
UsernameAttr string
|
||||
|
||||
Filter string
|
||||
AdminFilter string
|
||||
|
||||
FQDN string
|
||||
Port uint
|
||||
TLS bool
|
||||
}
|
||||
|
||||
func (c Config) IsSetup() bool {
|
||||
// This is basically checking if LDAP is setup, if ldapFQDN isn't set we can
|
||||
// assume that the user hasn't configured LDAP.
|
||||
return c.FQDN != ""
|
||||
}
|
||||
|
||||
func CheckLDAPcreds(username string, password string, dbc *db.DB, config Config, store LDAPStore) (bool, error) {
|
||||
if !config.IsSetup() {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if store.IsValid(username, password) {
|
||||
log.Println("Password authenticated via cache!")
|
||||
return true, nil
|
||||
}
|
||||
|
||||
log.Println("Checking password against LDAP server ...")
|
||||
|
||||
// Now, we can try to connect to the LDAP server.
|
||||
l, err := createLDAPconnection(config)
|
||||
if err != nil {
|
||||
// Return a generic error.
|
||||
log.Println("Failed to connect to LDAP server:", err)
|
||||
return false, errors.New("failed to connect to LDAP server")
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// Create the user if it doesn't exist on the database already.
|
||||
err = createUserFromLDAP(username, dbc, config, l)
|
||||
if err != nil {
|
||||
log.Println("Failed to create user from LDAP:", err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// After we have a connection, let's try binding
|
||||
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
|
||||
Username: fmt.Sprintf("%s=%s,%s", config.UsernameAttr, username, config.BaseDN),
|
||||
Password: password,
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
// Authentication was OK
|
||||
store.Add(username, password)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
log.Println("Failed to bind to LDAP server:", err)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Creates a user from creds
|
||||
func createUserFromLDAP(username string, dbc *db.DB, config Config, l *ldap.Conn) error {
|
||||
user := dbc.GetUserByName(username)
|
||||
if user != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !config.IsSetup() {
|
||||
return nil
|
||||
}
|
||||
|
||||
isAdmin := doesLDAPAdminExist(username, config, l)
|
||||
log.Println(username, isAdmin)
|
||||
|
||||
if !doesLDAPUserExist(username, config, l) {
|
||||
return errors.New("no such user")
|
||||
}
|
||||
|
||||
newUser := db.User{
|
||||
Name: username,
|
||||
Password: "", // no password because we want auth to fail.
|
||||
IsAdmin: isAdmin,
|
||||
}
|
||||
|
||||
err := dbc.Create(&newUser).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Println("User created via LDAP:", username)
|
||||
return nil
|
||||
}
|
||||
|
||||
// doesLDAPAdminExist checks if an admin exists on the server.
|
||||
func doesLDAPAdminExist(username string, config Config, l *ldap.Conn) bool {
|
||||
filter := fmt.Sprintf("(&(%s=%s)%s)", config.UsernameAttr, ldap.EscapeFilter(username), config.AdminFilter)
|
||||
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
config.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
filter,
|
||||
[]string{"dn"},
|
||||
nil,
|
||||
)
|
||||
|
||||
result, err := l.Search(searchReq)
|
||||
if err != nil {
|
||||
log.Println("failed to query LDAP server:", err)
|
||||
return false
|
||||
}
|
||||
|
||||
if len(result.Entries) == 1 {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// doesLDAPUserExist checks if a user exists on the server.
|
||||
func doesLDAPUserExist(username string, config Config, l *ldap.Conn) bool {
|
||||
filter := fmt.Sprintf("(&(%s=%s)%s)", config.UsernameAttr, ldap.EscapeFilter(username), config.Filter)
|
||||
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
config.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
filter,
|
||||
[]string{"dn"},
|
||||
nil,
|
||||
)
|
||||
|
||||
result, err := l.Search(searchReq)
|
||||
if err != nil {
|
||||
log.Println("failed to query LDAP server:", err)
|
||||
return false
|
||||
}
|
||||
|
||||
if len(result.Entries) == 1 {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Creates a connection to an LDAP server.
|
||||
func createLDAPconnection(config Config) (*ldap.Conn, error) {
|
||||
protocol := "ldap"
|
||||
if config.TLS {
|
||||
protocol = "ldaps"
|
||||
}
|
||||
|
||||
// Now, we can try to connect to the LDAP server.
|
||||
l, err := ldap.DialURL(fmt.Sprintf("%s://%s:%d", protocol, config.FQDN, config.Port))
|
||||
if err != nil {
|
||||
// Warn the server and return the error.
|
||||
log.Println("Failed to connect to LDAP server", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// After we have a connection, let's try binding
|
||||
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
|
||||
Username: fmt.Sprintf("%s=%s,%s", config.UsernameAttr, config.BindUser, config.BaseDN),
|
||||
Password: config.BindPass,
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("Failed to bind to LDAP:", err)
|
||||
return nil, errors.New("wrong username or password")
|
||||
}
|
||||
|
||||
return l, nil
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package listenbrainz
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"time"
|
||||
|
||||
"go.senan.xyz/gonic"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/scrobble"
|
||||
)
|
||||
|
||||
const (
|
||||
BaseURL = "https://api.listenbrainz.org"
|
||||
|
||||
submitPath = "/1/submit-listens"
|
||||
listenTypeSingle = "single"
|
||||
listenTypePlayingNow = "playing_now"
|
||||
)
|
||||
|
||||
var ErrListenBrainz = errors.New("listenbrainz error")
|
||||
|
||||
type Client struct {
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func NewClient() *Client {
|
||||
// disable post-quantum key exchange (Kyber) to avoid "connection reset by peer" errors.
|
||||
// listenbrainz's server can't handle the larger TLS ClientHello
|
||||
// https://github.com/golang/go/issues/70139
|
||||
return NewClientCustom(&http.Client{
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func NewClientCustom(httpClient *http.Client) *Client {
|
||||
return &Client{httpClient: httpClient}
|
||||
}
|
||||
|
||||
func (c *Client) IsUserAuthenticated(user db.User) bool {
|
||||
return user.ListenBrainzURL != "" && user.ListenBrainzToken != ""
|
||||
}
|
||||
|
||||
func (c *Client) Scrobble(user db.User, track scrobble.Track, stamp time.Time, submission bool) error {
|
||||
payload := &Payload{
|
||||
TrackMetadata: &TrackMetadata{
|
||||
AdditionalInfo: &AdditionalInfo{
|
||||
TrackNumber: int(track.TrackNumber),
|
||||
RecordingMBID: track.MusicBrainzID,
|
||||
ReleaseMBID: track.MusicBrainzReleaseID,
|
||||
Duration: int(track.Duration.Seconds()),
|
||||
SubmissionClient: gonic.Name,
|
||||
},
|
||||
ArtistName: track.Artist,
|
||||
TrackName: track.Track,
|
||||
ReleaseName: track.Album,
|
||||
},
|
||||
}
|
||||
scrobble := Scrobble{
|
||||
Payload: []*Payload{payload},
|
||||
}
|
||||
|
||||
if submission && len(scrobble.Payload) > 0 {
|
||||
scrobble.ListenType = listenTypeSingle
|
||||
scrobble.Payload[0].ListenedAt = int(stamp.Unix())
|
||||
} else {
|
||||
scrobble.ListenType = listenTypePlayingNow
|
||||
}
|
||||
|
||||
var payloadBuf bytes.Buffer
|
||||
if err := json.NewEncoder(&payloadBuf).Encode(scrobble); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
submitURL := fmt.Sprintf("%s%s", user.ListenBrainzURL, submitPath)
|
||||
authHeader := fmt.Sprintf("Token %s", user.ListenBrainzToken)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, submitURL, &payloadBuf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create submit request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.Header.Add("Authorization", authHeader)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("http post: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusUnauthorized:
|
||||
return fmt.Errorf("unauthorized: %w", ErrListenBrainz)
|
||||
case resp.StatusCode >= 400:
|
||||
respBytes, _ := httputil.DumpResponse(resp, true)
|
||||
log.Printf("received bad listenbrainz response:\n%s", string(respBytes))
|
||||
return fmt.Errorf(">= 400: %d: %w", resp.StatusCode, ErrListenBrainz)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package listenbrainz_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
_ "embed"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/listenbrainz"
|
||||
"go.senan.xyz/gonic/scrobble"
|
||||
)
|
||||
|
||||
func TestScrobble(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := listenbrainz.NewClientCustom(
|
||||
newMockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPost, r.Method)
|
||||
require.Equal(t, "/1/submit-listens", r.URL.Path)
|
||||
require.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
||||
require.Equal(t, "Token token1", r.Header.Get("Authorization"))
|
||||
bodyBytes, err := io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, submitListensRequest, string(bodyBytes))
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"accepted": 1}`))
|
||||
}),
|
||||
)
|
||||
|
||||
err := client.Scrobble(
|
||||
db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"},
|
||||
scrobble.Track{
|
||||
Track: "title",
|
||||
Artist: "artist",
|
||||
Album: "album",
|
||||
TrackNumber: 1,
|
||||
Duration: 242 * time.Second,
|
||||
MusicBrainzID: "00000000-0000-0000-0000-000000000000",
|
||||
MusicBrainzReleaseID: "00000000-0000-0000-0000-000000000001",
|
||||
},
|
||||
time.Unix(1683804525, 0),
|
||||
true,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestScrobbleUnauthorized(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := listenbrainz.NewClientCustom(
|
||||
newMockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPost, r.Method)
|
||||
require.Equal(t, "/1/submit-listens", r.URL.Path)
|
||||
require.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
||||
require.Equal(t, "Token token1", r.Header.Get("Authorization"))
|
||||
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(`{"code": 401, "error": "Invalid authorization token."}`))
|
||||
}),
|
||||
)
|
||||
|
||||
err := client.Scrobble(
|
||||
db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"},
|
||||
scrobble.Track{Track: "title", Artist: "artist", Album: "album", TrackNumber: 1},
|
||||
time.Now(),
|
||||
true,
|
||||
)
|
||||
|
||||
require.ErrorIs(t, err, listenbrainz.ErrListenBrainz)
|
||||
}
|
||||
|
||||
func TestScrobbleServerError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := listenbrainz.NewClientCustom(
|
||||
newMockClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPost, r.Method)
|
||||
require.Equal(t, "/1/submit-listens", r.URL.Path)
|
||||
require.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
||||
require.Equal(t, "Token token1", r.Header.Get("Authorization"))
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}),
|
||||
)
|
||||
|
||||
err := client.Scrobble(
|
||||
db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"},
|
||||
scrobble.Track{Track: "title", Artist: "artist", Album: "album", TrackNumber: 1},
|
||||
time.Now(),
|
||||
true,
|
||||
)
|
||||
|
||||
require.ErrorIs(t, err, listenbrainz.ErrListenBrainz)
|
||||
}
|
||||
|
||||
func newMockClient(tb testing.TB, handler http.HandlerFunc) *http.Client {
|
||||
tb.Helper()
|
||||
|
||||
server := httptest.NewTLSServer(handler)
|
||||
tb.Cleanup(server.Close)
|
||||
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return net.Dial(network, server.Listener.Addr().String())
|
||||
},
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: true, //nolint:gosec
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
//go:embed testdata/submit_listens_request.json
|
||||
var submitListensRequest string
|
||||
@@ -1,31 +0,0 @@
|
||||
package listenbrainz
|
||||
|
||||
// https://listenbrainz.readthedocs.io/en/latest/users/json.html#submission-json
|
||||
|
||||
type (
|
||||
Payload struct {
|
||||
ListenedAt int `json:"listened_at,omitempty"`
|
||||
TrackMetadata *TrackMetadata `json:"track_metadata"`
|
||||
}
|
||||
|
||||
AdditionalInfo struct {
|
||||
TrackNumber int `json:"tracknumber,omitempty"`
|
||||
TrackMBID string `json:"track_mbid,omitempty"`
|
||||
RecordingMBID string `json:"recording_mbid,omitempty"`
|
||||
ReleaseMBID string `json:"release_mbid,omitempty"`
|
||||
Duration int `json:"duration,omitempty"`
|
||||
SubmissionClient string `json:"submission_client,omitempty"`
|
||||
}
|
||||
|
||||
TrackMetadata struct {
|
||||
AdditionalInfo *AdditionalInfo `json:"additional_info"`
|
||||
ArtistName string `json:"artist_name,omitempty"`
|
||||
TrackName string `json:"track_name,omitempty"`
|
||||
ReleaseName string `json:"release_name,omitempty"`
|
||||
}
|
||||
|
||||
Scrobble struct {
|
||||
ListenType string `json:"listen_type,omitempty"`
|
||||
Payload []*Payload `json:"payload"`
|
||||
}
|
||||
)
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"listen_type": "single",
|
||||
"payload": [
|
||||
{
|
||||
"listened_at": 1683804525,
|
||||
"track_metadata": {
|
||||
"additional_info": {
|
||||
"tracknumber": 1,
|
||||
"duration": 242,
|
||||
"recording_mbid": "00000000-0000-0000-0000-000000000000",
|
||||
"release_mbid": "00000000-0000-0000-0000-000000000001",
|
||||
"submission_client": "gonic"
|
||||
},
|
||||
"artist_name": "artist",
|
||||
"track_name": "title",
|
||||
"release_name": "album"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,379 +0,0 @@
|
||||
//nolint:thelper
|
||||
package mockfs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/deps"
|
||||
"go.senan.xyz/gonic/scanner"
|
||||
"go.senan.xyz/gonic/tags"
|
||||
"go.senan.xyz/wrtag/tags/normtag"
|
||||
)
|
||||
|
||||
var ErrPathNotFound = errors.New("path not found")
|
||||
|
||||
type MockFS struct {
|
||||
t testing.TB
|
||||
scanner *scanner.Scanner
|
||||
dir string
|
||||
tagReader *tagReader
|
||||
db *db.DB
|
||||
}
|
||||
|
||||
func New(tb testing.TB) *MockFS { return newMockFS(tb, []string{""}, "") }
|
||||
func NewWithDirs(tb testing.TB, dirs []string) *MockFS { return newMockFS(tb, dirs, "") }
|
||||
func NewWithExcludePattern(tb testing.TB, excludePattern string) *MockFS {
|
||||
return newMockFS(tb, []string{""}, excludePattern)
|
||||
}
|
||||
|
||||
func newMockFS(tb testing.TB, dirs []string, excludePattern string) *MockFS {
|
||||
tb.Helper()
|
||||
|
||||
dbc, err := db.NewMock(deps.DBDriverOptions())
|
||||
if err != nil {
|
||||
tb.Fatalf("create db: %v", err)
|
||||
}
|
||||
tb.Cleanup(func() {
|
||||
if err := dbc.Close(); err != nil {
|
||||
tb.Fatalf("close db: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
if err := dbc.Migrate(db.MigrationContext{}); err != nil {
|
||||
tb.Fatalf("migrate db db: %v", err)
|
||||
}
|
||||
dbc.LogMode(false)
|
||||
|
||||
tmpDir := tb.TempDir()
|
||||
|
||||
var absDirs []string
|
||||
for _, dir := range dirs {
|
||||
absDirs = append(absDirs, filepath.Join(tmpDir, dir))
|
||||
}
|
||||
for _, absDir := range absDirs {
|
||||
if err := os.MkdirAll(absDir, os.ModePerm); err != nil {
|
||||
tb.Fatalf("mk abs dir: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
multiValueSettings := map[scanner.Tag]scanner.MultiValueSetting{
|
||||
scanner.Genre: {Mode: scanner.Delim, Delim: ";"},
|
||||
scanner.AlbumArtist: {Mode: scanner.Multi},
|
||||
}
|
||||
|
||||
tagReader := &tagReader{paths: map[string]*TagInfo{}}
|
||||
scanner := scanner.New(absDirs, dbc, multiValueSettings, tagReader, excludePattern, true)
|
||||
|
||||
return &MockFS{
|
||||
t: tb,
|
||||
scanner: scanner,
|
||||
dir: tmpDir,
|
||||
tagReader: tagReader,
|
||||
db: dbc,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockFS) DB() *db.DB { return m.db }
|
||||
func (m *MockFS) TmpDir() string { return m.dir }
|
||||
func (m *MockFS) TagReader() tags.Reader { return m.tagReader }
|
||||
|
||||
func (m *MockFS) ScanAndClean() *scanner.State {
|
||||
m.t.Helper()
|
||||
|
||||
st, err := m.scanner.ScanAndClean(scanner.ScanOptions{})
|
||||
if err != nil {
|
||||
m.t.Fatalf("error scan and cleaning: %v", err)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func (m *MockFS) ScanAndCleanErr() (*scanner.State, error) {
|
||||
m.t.Helper()
|
||||
|
||||
return m.scanner.ScanAndClean(scanner.ScanOptions{})
|
||||
}
|
||||
|
||||
func (m *MockFS) ResetDates() {
|
||||
t := time.Date(2020, 0, 0, 0, 0, 0, 0, time.UTC)
|
||||
if err := m.db.Model(db.Album{}).Updates(db.Album{CreatedAt: t, UpdatedAt: t, ModifiedAt: t}).Error; err != nil {
|
||||
m.t.Fatalf("reset album times: %v", err)
|
||||
}
|
||||
if err := m.db.Model(db.Track{}).Updates(db.Track{CreatedAt: t, UpdatedAt: t}).Error; err != nil {
|
||||
m.t.Fatalf("reset track times: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockFS) AddItems() { m.addItems("", "", false) }
|
||||
func (m *MockFS) AddItemsGlob(onlyGlob string) { m.addItems("", onlyGlob, false) }
|
||||
func (m *MockFS) AddItemsPrefix(prefix string) { m.addItems(prefix, "", false) }
|
||||
func (m *MockFS) AddItemsWithCovers() { m.addItems("", "", true) }
|
||||
func (m *MockFS) AddItemsPrefixWithCovers(prefix string) { m.addItems(prefix, "", true) }
|
||||
|
||||
func (m *MockFS) addItems(prefix string, onlyGlob string, covers bool) {
|
||||
p := func(format string, a ...any) string {
|
||||
return filepath.Join(prefix, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
for ar := range 3 {
|
||||
for al := range 3 {
|
||||
for tr := range 3 {
|
||||
path := p("artist-%d/album-%d/track-%d.flac", ar, al, tr)
|
||||
if !match(onlyGlob, path) {
|
||||
continue
|
||||
}
|
||||
|
||||
m.AddTrack(path)
|
||||
m.SetTags(path, func(info *TagInfo) {
|
||||
normtag.Set(info.Tags, normtag.Artist, fmt.Sprintf("artist-%d", ar))
|
||||
normtag.Set(info.Tags, normtag.AlbumArtist, fmt.Sprintf("artist-%d", ar))
|
||||
normtag.Set(info.Tags, normtag.Album, fmt.Sprintf("album-%d", al))
|
||||
normtag.Set(info.Tags, normtag.Title, fmt.Sprintf("title-%d", tr))
|
||||
})
|
||||
}
|
||||
|
||||
if covers {
|
||||
path := p("artist-%d/album-%d/cover.png", ar, al)
|
||||
if !match(onlyGlob, path) {
|
||||
continue
|
||||
}
|
||||
|
||||
m.AddCover(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockFS) NumTracks() int {
|
||||
return len(m.tagReader.paths)
|
||||
}
|
||||
|
||||
func (m *MockFS) RemoveAll(path string) {
|
||||
abspath := filepath.Join(m.dir, path)
|
||||
if err := os.RemoveAll(abspath); err != nil {
|
||||
m.t.Fatalf("remove all: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockFS) Move(src, dest string) {
|
||||
srcAbs := filepath.Join(m.dir, src)
|
||||
destAbs := filepath.Join(m.dir, dest)
|
||||
if err := os.MkdirAll(filepath.Dir(destAbs), os.ModePerm); err != nil {
|
||||
m.t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
if err := os.Rename(srcAbs, destAbs); err != nil {
|
||||
m.t.Fatalf("rename: %v", err)
|
||||
}
|
||||
if info, ok := m.tagReader.paths[srcAbs]; ok {
|
||||
m.tagReader.paths[destAbs] = info
|
||||
delete(m.tagReader.paths, srcAbs)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockFS) Symlink(src, dest string) {
|
||||
if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil {
|
||||
m.t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
if err := os.Symlink(src, dest); err != nil {
|
||||
m.t.Fatalf("symlink: %v", err)
|
||||
}
|
||||
src = filepath.Clean(src)
|
||||
dest = filepath.Clean(dest)
|
||||
for k, v := range m.tagReader.paths {
|
||||
m.tagReader.paths[strings.Replace(k, src, dest, 1)] = v
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockFS) SetAudio(path string, length time.Duration, bitrate uint, audioPath string) {
|
||||
abspath := filepath.Join(m.dir, path)
|
||||
if err := os.Remove(abspath); err != nil {
|
||||
m.t.Fatalf("remove all: %v", err)
|
||||
}
|
||||
wd, _ := os.Getwd()
|
||||
if err := os.Symlink(filepath.Join(wd, audioPath), abspath); err != nil {
|
||||
m.t.Fatalf("symlink: %v", err)
|
||||
}
|
||||
m.SetTags(path, func(tags *TagInfo) {
|
||||
tags.Length = length
|
||||
tags.Bitrate = bitrate
|
||||
})
|
||||
}
|
||||
|
||||
func (m *MockFS) LogItems() {
|
||||
m.t.Logf("\nitems")
|
||||
var items int
|
||||
err := filepath.WalkDir(m.dir, func(path string, info os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch info.Type() {
|
||||
case os.ModeSymlink:
|
||||
m.t.Logf("item %q [sym]", path)
|
||||
default:
|
||||
m.t.Logf("item %q", path)
|
||||
}
|
||||
items++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
m.t.Fatalf("error logging items: %v", err)
|
||||
}
|
||||
m.t.Logf("total %d", items)
|
||||
}
|
||||
|
||||
func (m *MockFS) LogAlbums() {
|
||||
var albums []*db.Album
|
||||
if err := m.db.Find(&albums).Error; err != nil {
|
||||
m.t.Fatalf("error logging items: %v", err)
|
||||
}
|
||||
|
||||
m.t.Logf("\nalbums")
|
||||
for _, album := range albums {
|
||||
m.t.Logf("id %-3d root %-3s lr %-15s %-10s pid %-3d cov %-10s",
|
||||
album.ID, album.RootDir, album.LeftPath, album.RightPath, album.ParentID, album.Cover)
|
||||
}
|
||||
m.t.Logf("total %d", len(albums))
|
||||
}
|
||||
|
||||
func (m *MockFS) LogArtists() {
|
||||
var artists []*db.Artist
|
||||
if err := m.db.Find(&artists).Error; err != nil {
|
||||
m.t.Fatalf("error logging items: %v", err)
|
||||
}
|
||||
|
||||
m.t.Logf("\nartists")
|
||||
for _, artist := range artists {
|
||||
m.t.Logf("id %-3d %-10s", artist.ID, artist.Name)
|
||||
}
|
||||
m.t.Logf("total %d", len(artists))
|
||||
}
|
||||
|
||||
func (m *MockFS) LogTracks() {
|
||||
var tracks []*db.Track
|
||||
if err := m.db.Find(&tracks).Error; err != nil {
|
||||
m.t.Fatalf("error logging items: %v", err)
|
||||
}
|
||||
|
||||
m.t.Logf("\ntracks")
|
||||
for _, track := range tracks {
|
||||
m.t.Logf("id %-3d aid %-3d filename %-10s tagtitle %-10s",
|
||||
track.ID, track.AlbumID, track.Filename, track.TagTitle)
|
||||
}
|
||||
m.t.Logf("total %d", len(tracks))
|
||||
}
|
||||
|
||||
func (m *MockFS) LogTrackGenres() {
|
||||
var tgs []*db.TrackGenre
|
||||
if err := m.db.Find(&tgs).Error; err != nil {
|
||||
m.t.Fatalf("error logging items: %v", err)
|
||||
}
|
||||
|
||||
m.t.Logf("\ntrack genres")
|
||||
for _, tg := range tgs {
|
||||
m.t.Logf("tid %-3d gid %-3d", tg.TrackID, tg.GenreID)
|
||||
}
|
||||
m.t.Logf("total %d", len(tgs))
|
||||
}
|
||||
|
||||
func (m *MockFS) AddTrack(path string) {
|
||||
abspath := filepath.Join(m.dir, path)
|
||||
dir := filepath.Dir(abspath)
|
||||
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
|
||||
m.t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
f, err := os.Create(abspath)
|
||||
if err != nil {
|
||||
m.t.Fatalf("create track: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
}
|
||||
|
||||
func (m *MockFS) AddCover(path string) {
|
||||
abspath := filepath.Join(m.dir, path)
|
||||
if err := os.MkdirAll(filepath.Dir(abspath), os.ModePerm); err != nil {
|
||||
m.t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
f, err := os.Create(abspath)
|
||||
if err != nil {
|
||||
m.t.Fatalf("create cover: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
}
|
||||
|
||||
func newTagInfo() *TagInfo {
|
||||
var info TagInfo
|
||||
info.Tags = map[string][]string{}
|
||||
|
||||
normtag.Set(info.Tags, normtag.TrackNumber, "1")
|
||||
normtag.Set(info.Tags, normtag.DiscNumber, "1")
|
||||
normtag.Set(info.Tags, normtag.Date, "2021-01-01")
|
||||
normtag.Set(info.Tags, normtag.ReleaseType, "Album")
|
||||
|
||||
info.Length = 100 * time.Second
|
||||
info.Bitrate = 100
|
||||
|
||||
return &info
|
||||
}
|
||||
|
||||
func (m *MockFS) SetTags(path string, cb func(*TagInfo)) {
|
||||
absPath := filepath.Join(m.dir, path)
|
||||
if err := os.Chtimes(absPath, time.Time{}, time.Now()); err != nil {
|
||||
m.t.Fatalf("touch track: %v", err)
|
||||
}
|
||||
if _, ok := m.tagReader.paths[absPath]; !ok {
|
||||
m.tagReader.paths[absPath] = newTagInfo()
|
||||
}
|
||||
cb(m.tagReader.paths[absPath])
|
||||
}
|
||||
|
||||
var _ tags.Reader = (*tagReader)(nil)
|
||||
|
||||
type tagReader struct {
|
||||
paths map[string]*TagInfo
|
||||
}
|
||||
|
||||
func (m *tagReader) CanRead(absPath string) bool {
|
||||
stat, _ := os.Stat(absPath)
|
||||
return stat.Mode().IsRegular()
|
||||
}
|
||||
|
||||
func (m *tagReader) Read(absPath string) (tags.Properties, map[string][]string, error) {
|
||||
p, ok := m.paths[absPath]
|
||||
if !ok {
|
||||
return tags.Properties{}, nil, ErrPathNotFound
|
||||
}
|
||||
if p.Error != nil {
|
||||
return tags.Properties{}, nil, p.Error
|
||||
}
|
||||
|
||||
props := tags.Properties{
|
||||
Length: p.Length,
|
||||
Bitrate: p.Bitrate,
|
||||
}
|
||||
return props, p.Tags, nil
|
||||
}
|
||||
|
||||
func (m *tagReader) ReadCover(absPath string) ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type TagInfo struct {
|
||||
Tags map[string][]string
|
||||
Length time.Duration
|
||||
Bitrate uint
|
||||
Error error
|
||||
}
|
||||
|
||||
func match(pattern, name string) bool {
|
||||
if pattern == "" {
|
||||
return true
|
||||
}
|
||||
ok, _ := filepath.Match(pattern, name)
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "hamburger",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"next": "15.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"postcss": "^8",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "15.1.2",
|
||||
"@eslint/eslintrc": "^3"
|
||||
}
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
package playlist
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.senan.xyz/gonic/fileutil"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidPathFormat = errors.New("invalid path format")
|
||||
ErrInvalidBasePath = errors.New("invalid base path")
|
||||
ErrNoUserPrefix = errors.New("no user prefix")
|
||||
)
|
||||
|
||||
const (
|
||||
extM3U = ".m3u"
|
||||
extM3U8 = ".m3u8"
|
||||
)
|
||||
|
||||
type Playlist struct {
|
||||
UpdatedAt time.Time
|
||||
UserID int
|
||||
Name string
|
||||
Comment string
|
||||
Items []string
|
||||
IsPublic bool
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
basePath string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewStore(basePath string) (*Store, error) {
|
||||
if basePath == "" {
|
||||
return nil, ErrInvalidBasePath
|
||||
}
|
||||
if err := sanityCheck(basePath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Store{
|
||||
basePath: basePath,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Store) BasePath() string {
|
||||
return s.basePath
|
||||
}
|
||||
|
||||
// List finds playlist items in s.basePath.
|
||||
// the expected format is <base path>/<user id>/**/<playlist name>.m3u
|
||||
func (s *Store) List() ([]string, error) {
|
||||
defer lock(&s.mu)()
|
||||
|
||||
if err := sanityCheck(s.basePath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var relPaths []string
|
||||
return relPaths, filepath.WalkDir(s.basePath, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
switch filepath.Ext(path) {
|
||||
case extM3U, extM3U8:
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
relPath, _ := filepath.Rel(s.basePath, path)
|
||||
relPaths = append(relPaths, relPath)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) Read(relPath string) (*Playlist, error) {
|
||||
defer lock(&s.mu)()
|
||||
|
||||
if err := sanityCheck(s.basePath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
absPath := filepath.Join(s.basePath, relPath)
|
||||
stat, err := os.Stat(absPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stat m3u: %w", err)
|
||||
}
|
||||
|
||||
if stat.IsDir() {
|
||||
return nil, errors.New("path is a directory")
|
||||
}
|
||||
|
||||
var playlist Playlist
|
||||
playlist.UpdatedAt = stat.ModTime()
|
||||
|
||||
playlist.UserID, err = userIDFromPath(relPath)
|
||||
if err != nil {
|
||||
playlist.UserID = 1
|
||||
}
|
||||
|
||||
playlist.Name = strings.TrimSuffix(filepath.Base(relPath), filepath.Ext(relPath))
|
||||
|
||||
file, err := os.Open(absPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open m3u: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
for sc := bufio.NewScanner(file); sc.Scan(); {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
switch name, value := decodeAttr(line); name {
|
||||
case attrName:
|
||||
playlist.Name = value
|
||||
case attrCommment:
|
||||
playlist.Comment = value
|
||||
case attrIsPublic:
|
||||
playlist.IsPublic, _ = strconv.ParseBool(value)
|
||||
}
|
||||
if strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
if !filepath.IsAbs(line) {
|
||||
line = filepath.Join(filepath.Dir(absPath), line)
|
||||
}
|
||||
playlist.Items = append(playlist.Items, line)
|
||||
}
|
||||
|
||||
return &playlist, nil
|
||||
}
|
||||
|
||||
func (s *Store) Write(relPath string, playlist *Playlist) error {
|
||||
defer lock(&s.mu)()
|
||||
|
||||
if err := sanityCheck(s.basePath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
absPath := filepath.Join(s.basePath, relPath)
|
||||
if err := os.MkdirAll(filepath.Dir(absPath), 0o777); err != nil {
|
||||
return fmt.Errorf("make m3u base dir: %w", err)
|
||||
}
|
||||
file, err := os.OpenFile(absPath, os.O_RDWR|os.O_CREATE, 0o666)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create m3u: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if err := os.Chtimes(absPath, time.Time{}, playlist.UpdatedAt); err != nil {
|
||||
return fmt.Errorf("touch m3u: %w", err)
|
||||
}
|
||||
|
||||
var existingComments []string
|
||||
for sc := bufio.NewScanner(file); sc.Scan(); {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if strings.HasPrefix(line, attrPrefix) {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "#") {
|
||||
existingComments = append(existingComments, sc.Text())
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := file.Seek(0, 0); err != nil {
|
||||
return fmt.Errorf("seek m3u: %w", err)
|
||||
}
|
||||
if err := file.Truncate(0); err != nil {
|
||||
return fmt.Errorf("truncate m3u: %w", err)
|
||||
}
|
||||
|
||||
for _, line := range existingComments {
|
||||
fmt.Fprintln(file, line)
|
||||
}
|
||||
fmt.Fprintln(file, encodeAttr(attrName, playlist.Name))
|
||||
fmt.Fprintln(file, encodeAttr(attrCommment, playlist.Comment))
|
||||
fmt.Fprintln(file, encodeAttr(attrIsPublic, fmt.Sprint(playlist.IsPublic)))
|
||||
for _, line := range playlist.Items {
|
||||
if rel, err := filepath.Rel(filepath.Dir(absPath), line); err == nil {
|
||||
line = rel
|
||||
}
|
||||
fmt.Fprintln(file, line)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Delete(relPath string) error {
|
||||
if err := sanityCheck(s.basePath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.Remove(filepath.Join(s.basePath, relPath))
|
||||
}
|
||||
|
||||
func firstPathEl(path string) string {
|
||||
path = strings.TrimPrefix(path, string(filepath.Separator))
|
||||
parts := strings.Split(path, string(filepath.Separator))
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
return parts[0]
|
||||
}
|
||||
|
||||
func userIDFromPath(relPath string) (int, error) {
|
||||
return strconv.Atoi(firstPathEl(relPath))
|
||||
}
|
||||
|
||||
func lock(mu *sync.Mutex) func() {
|
||||
mu.Lock()
|
||||
return mu.Unlock
|
||||
}
|
||||
|
||||
func sanityCheck(basePath string) error {
|
||||
// sanity check layout, just in case someone tries to use an existing folder
|
||||
entries, err := os.ReadDir(basePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sanity checking: reading dir: %w", err)
|
||||
}
|
||||
var found string
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
if _, err := userIDFromPath(entry.Name()); err != nil {
|
||||
found = entry.Name()
|
||||
break
|
||||
}
|
||||
}
|
||||
if found != "" {
|
||||
return fmt.Errorf("sanity checking: %w: item %q in playlists directory is not a user id. see wiki for details on layout of the playlists dir", ErrNoUserPrefix, found)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
attrPrefix = "#GONIC-"
|
||||
attrName = "NAME"
|
||||
attrCommment = "COMMENT"
|
||||
attrIsPublic = "IS-PUBLIC"
|
||||
)
|
||||
|
||||
func encodeAttr(name, value string) string {
|
||||
return fmt.Sprintf("%s%s:%s", attrPrefix, name, strconv.Quote(value))
|
||||
}
|
||||
|
||||
func decodeAttr(line string) (name, value string) {
|
||||
if !strings.HasPrefix(line, attrPrefix) {
|
||||
return "", ""
|
||||
}
|
||||
prefixAndName, rawValue, _ := strings.Cut(line, ":")
|
||||
name = strings.TrimPrefix(prefixAndName, attrPrefix)
|
||||
value, _ = strconv.Unquote(rawValue)
|
||||
return name, value
|
||||
}
|
||||
|
||||
func NewPath(userID int, playlistName string) string {
|
||||
playlistName = fileutil.Safe(playlistName)
|
||||
if playlistName == "" {
|
||||
playlistName = "pl"
|
||||
}
|
||||
playlistName = fmt.Sprintf("%s-%d%s", playlistName, time.Now().UnixMilli(), extM3U)
|
||||
return filepath.Join(fmt.Sprint(userID), playlistName)
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package playlist_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.senan.xyz/gonic/playlist"
|
||||
)
|
||||
|
||||
func TestPlaylist(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tmp := t.TempDir()
|
||||
store, err := playlist.NewStore(tmp)
|
||||
require.NoError(t, err)
|
||||
|
||||
playlistIDs, err := store.List()
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, playlistIDs)
|
||||
|
||||
for _, playlistID := range playlistIDs {
|
||||
playlist, err := store.Read(playlistID)
|
||||
require.NoError(t, err)
|
||||
require.NotZero(t, playlist.UpdatedAt)
|
||||
}
|
||||
|
||||
before := playlist.Playlist{
|
||||
UserID: 10,
|
||||
Name: "Examlpe playlist name",
|
||||
Comment: `
|
||||
Example comment
|
||||
It has multiple lines 👍
|
||||
`,
|
||||
Items: []string{
|
||||
"/music/item 1.flac",
|
||||
"/music/item 2.flac",
|
||||
"/music/item 3.flac",
|
||||
},
|
||||
IsPublic: true,
|
||||
}
|
||||
|
||||
newPath := playlist.NewPath(before.UserID, before.Name)
|
||||
require.NoError(t, store.Write(newPath, &before))
|
||||
|
||||
after, err := store.Read(newPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, after.UserID, before.UserID)
|
||||
require.Equal(t, after.Name, before.Name)
|
||||
require.Equal(t, after.Comment, before.Comment)
|
||||
require.Equal(t, after.Items, before.Items)
|
||||
require.Equal(t, after.IsPublic, before.IsPublic)
|
||||
|
||||
playlistIDs, err = store.List()
|
||||
require.NoError(t, err)
|
||||
require.True(t, len(playlistIDs) == 1)
|
||||
}
|
||||
@@ -1,567 +0,0 @@
|
||||
package podcast
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/mmcdole/gofeed"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/fileutil"
|
||||
"go.senan.xyz/gonic/tags"
|
||||
)
|
||||
|
||||
var ErrNoAudioInFeedItem = errors.New("no audio in feed item")
|
||||
|
||||
const (
|
||||
fetchUserAgent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11`
|
||||
)
|
||||
|
||||
type Podcasts struct {
|
||||
httpClient *http.Client
|
||||
db *db.DB
|
||||
baseDir string
|
||||
tagReader tags.Reader
|
||||
}
|
||||
|
||||
func New(db *db.DB, base string, tagReader tags.Reader) *Podcasts {
|
||||
return &Podcasts{
|
||||
db: db,
|
||||
baseDir: base,
|
||||
tagReader: tagReader,
|
||||
httpClient: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Podcasts) GetPodcastOrAll(id int, includeEpisodes bool) ([]*db.Podcast, error) {
|
||||
var podcasts []*db.Podcast
|
||||
q := p.db.DB
|
||||
if id != 0 {
|
||||
q = q.Where("id=?", id)
|
||||
}
|
||||
if includeEpisodes {
|
||||
q = q.Preload("Episodes", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("podcast_episodes.publish_date DESC")
|
||||
})
|
||||
}
|
||||
if err := q.Find(&podcasts).Error; err != nil {
|
||||
return nil, fmt.Errorf("find podcasts: %w", err)
|
||||
}
|
||||
return podcasts, nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) GetNewestPodcastEpisodes(count int) ([]*db.PodcastEpisode, error) {
|
||||
var episodes []*db.PodcastEpisode
|
||||
err := p.db.
|
||||
Order("publish_date DESC").
|
||||
Limit(count).
|
||||
Find(&episodes).
|
||||
Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find newest podcast episodes: %w", err)
|
||||
}
|
||||
return episodes, nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) AddNewPodcast(rssURL string, feed *gofeed.Feed) (*db.Podcast, error) {
|
||||
rootDir, err := fileutil.Unique(filepath.Join(p.baseDir, fileutil.Safe(feed.Title)), "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find unique podcast dir: %w", err)
|
||||
}
|
||||
var author string
|
||||
if feed.ITunesExt != nil {
|
||||
author = feed.ITunesExt.Author
|
||||
}
|
||||
podcast := db.Podcast{
|
||||
Description: feed.Description,
|
||||
ImageURL: "",
|
||||
Title: feed.Title,
|
||||
URL: rssURL,
|
||||
RootDir: rootDir,
|
||||
Author: author,
|
||||
}
|
||||
if feed.Image != nil {
|
||||
podcast.ImageURL = feed.Image.URL
|
||||
}
|
||||
if err := os.Mkdir(podcast.RootDir, 0o755); err != nil && !os.IsExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
if err := p.db.Save(&podcast).Error; err != nil {
|
||||
return &podcast, err
|
||||
}
|
||||
if err := p.RefreshPodcast(&podcast, feed.Items); err != nil {
|
||||
log.Printf("error adding new episodes : %v", err)
|
||||
}
|
||||
if err := p.downloadPodcastCover(&podcast); err != nil {
|
||||
log.Printf("error downloading podcast cover: %v", err)
|
||||
}
|
||||
return &podcast, nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) SetAutoDownload(podcastID int, setting db.PodcastAutoDownload) error {
|
||||
podcast := db.Podcast{}
|
||||
err := p.db.
|
||||
Where("id=?", podcastID).
|
||||
First(&podcast).
|
||||
Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
podcast.AutoDownload = setting
|
||||
if err := p.db.Save(&podcast).Error; err != nil {
|
||||
return fmt.Errorf("save setting: %w", err)
|
||||
}
|
||||
|
||||
// download most recent
|
||||
if setting == db.PodcastAutoDownloadLatest {
|
||||
err := p.db.
|
||||
Model(db.PodcastEpisode{}).
|
||||
Where("status=?", db.PodcastEpisodeStatusSkipped).
|
||||
Where("id=?", p.db.
|
||||
Select("id").
|
||||
Model(db.PodcastEpisode{}).
|
||||
Where("podcast_id=?", podcast.ID).
|
||||
Order("publish_date DESC").
|
||||
Limit(1).
|
||||
SubQuery(),
|
||||
).
|
||||
Update("status", db.PodcastEpisodeStatusDownloading).
|
||||
Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("update podcast most recent episode: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getEntriesAfterDate(feed []*gofeed.Item, after time.Time) []*gofeed.Item {
|
||||
items := []*gofeed.Item{}
|
||||
for _, item := range feed {
|
||||
if item.PublishedParsed.Before(after) || item.PublishedParsed.Equal(after) {
|
||||
continue
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (p *Podcasts) RefreshPodcast(podcast *db.Podcast, items []*gofeed.Item) error {
|
||||
var lastPodcastEpisode db.PodcastEpisode
|
||||
err := p.db.
|
||||
Where("podcast_id=?", podcast.ID).
|
||||
Order("publish_date DESC").
|
||||
First(&lastPodcastEpisode).
|
||||
Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
if lastPodcastEpisode.ID != 0 {
|
||||
items = getEntriesAfterDate(items, *lastPodcastEpisode.PublishDate)
|
||||
}
|
||||
|
||||
var episodeErrs []error
|
||||
for _, item := range items {
|
||||
podcastEpisode, err := p.addEpisode(podcast, item)
|
||||
if err != nil {
|
||||
episodeErrs = append(episodeErrs, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if lastPodcastEpisode.ID != 0 && podcast.AutoDownload == db.PodcastAutoDownloadLatest {
|
||||
podcastEpisode.Status = db.PodcastEpisodeStatusDownloading
|
||||
if err := p.db.Save(&podcastEpisode).Error; err != nil {
|
||||
return fmt.Errorf("save podcast episode: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Join(episodeErrs...)
|
||||
}
|
||||
|
||||
func (p *Podcasts) addEpisode(podcast *db.Podcast, item *gofeed.Item) (*db.PodcastEpisode, error) {
|
||||
var duration int
|
||||
// if it has the media extension use it
|
||||
for _, content := range item.Extensions["media"]["content"] {
|
||||
durationExt := content.Attrs["duration"]
|
||||
duration = getSecondsFromString(durationExt)
|
||||
if duration != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
// if the itunes extension is available, use AddEpisode
|
||||
if duration == 0 && item.ITunesExt != nil {
|
||||
duration = getSecondsFromString(item.ITunesExt.Duration)
|
||||
}
|
||||
if episode, ok := p.findEnclosureAudio(podcast, duration, item); ok {
|
||||
if err := p.db.Save(episode).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return episode, nil
|
||||
}
|
||||
if episode, ok := p.findMediaAudio(podcast, duration, item); ok {
|
||||
if err := p.db.Save(episode).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return episode, nil
|
||||
}
|
||||
return nil, ErrNoAudioInFeedItem
|
||||
}
|
||||
|
||||
func (p *Podcasts) isAudio(rawItemURL string) (bool, error) {
|
||||
itemURL, err := url.Parse(rawItemURL)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return p.tagReader.CanRead(itemURL.Path), nil
|
||||
}
|
||||
|
||||
func itemToEpisode(podcast *db.Podcast, size, duration int, audio string, item *gofeed.Item) *db.PodcastEpisode {
|
||||
author := podcast.Author
|
||||
if item.ITunesExt != nil {
|
||||
author = cmp.Or(item.ITunesExt.Author, podcast.Author)
|
||||
}
|
||||
return &db.PodcastEpisode{
|
||||
PodcastID: podcast.ID,
|
||||
Description: item.Description,
|
||||
Title: item.Title,
|
||||
Length: duration,
|
||||
Size: size,
|
||||
PublishDate: item.PublishedParsed,
|
||||
AudioURL: audio,
|
||||
Status: db.PodcastEpisodeStatusSkipped,
|
||||
Artist: cmp.Or(author),
|
||||
Album: podcast.Title,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Podcasts) findEnclosureAudio(podcast *db.Podcast, duration int, item *gofeed.Item) (*db.PodcastEpisode, bool) {
|
||||
for _, enc := range item.Enclosures {
|
||||
if t, err := p.isAudio(enc.URL); !t || err != nil {
|
||||
continue
|
||||
}
|
||||
size, _ := strconv.Atoi(enc.Length)
|
||||
return itemToEpisode(podcast, size, duration, enc.URL, item), true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (p *Podcasts) findMediaAudio(podcast *db.Podcast, duration int, item *gofeed.Item) (*db.PodcastEpisode, bool) {
|
||||
extensions, ok := item.Extensions["media"]["content"]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
for _, ext := range extensions {
|
||||
if t, err := p.isAudio(ext.Attrs["url"]); !t || err != nil {
|
||||
continue
|
||||
}
|
||||
return itemToEpisode(podcast, 0, duration, ext.Attrs["url"], item), true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (p *Podcasts) RefreshPodcasts() error {
|
||||
var podcasts []*db.Podcast
|
||||
if err := p.db.Find(&podcasts).Error; err != nil {
|
||||
return fmt.Errorf("find podcasts: %w", err)
|
||||
}
|
||||
|
||||
var errs []error
|
||||
for _, podcast := range podcasts {
|
||||
fp := gofeed.NewParser()
|
||||
feed, err := fp.ParseURL(podcast.URL)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("refreshing podcast with url %q: %w", podcast.URL, err))
|
||||
continue
|
||||
}
|
||||
if err := p.RefreshPodcast(podcast, feed.Items); err != nil {
|
||||
errs = append(errs, fmt.Errorf("adding episodes: %w", err))
|
||||
continue
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (p *Podcasts) DownloadPodcastAll(podcastID int) error {
|
||||
err := p.db.
|
||||
Model(db.PodcastEpisode{}).
|
||||
Where("status=?", db.PodcastEpisodeStatusSkipped).
|
||||
Where("podcast_id=?", podcastID).
|
||||
Update("status", db.PodcastEpisodeStatusDownloading).
|
||||
Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("update podcast episodes: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) DownloadEpisode(episodeID int) error {
|
||||
err := p.db.
|
||||
Model(db.PodcastEpisode{}).
|
||||
Where("id=?", episodeID).
|
||||
Update("status", db.PodcastEpisodeStatusDownloading).
|
||||
Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("update podcast episodes: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getContentDispositionFilename(header http.Header) (string, bool) {
|
||||
contentHeader := header.Get("content-disposition")
|
||||
_, params, _ := mime.ParseMediaType(contentHeader)
|
||||
filename, ok := params["filename"]
|
||||
return filename, ok
|
||||
}
|
||||
|
||||
func getPodcastEpisodeFilename(podcast *db.Podcast, podcastEpisode *db.PodcastEpisode, header http.Header) (string, error) {
|
||||
if podcastEpisode.Filename != "" {
|
||||
return podcastEpisode.Filename, nil
|
||||
}
|
||||
|
||||
filename, ok := getContentDispositionFilename(header)
|
||||
if !ok {
|
||||
audioURL, err := url.Parse(podcastEpisode.AudioURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse podcast audio url: %w", err)
|
||||
}
|
||||
filename = path.Base(audioURL.Path)
|
||||
}
|
||||
path, err := fileutil.Unique(podcast.RootDir, fileutil.Safe(filename))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find unique path: %w", err)
|
||||
}
|
||||
_, filename = filepath.Split(path)
|
||||
|
||||
return filename, nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) downloadPodcastCover(podcast *db.Podcast) error {
|
||||
if podcast.ImageURL == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
imageURL, err := url.Parse(podcast.ImageURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse image url: %w", err)
|
||||
}
|
||||
req, err := http.NewRequest("GET", podcast.ImageURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create http request: %w", err)
|
||||
}
|
||||
req.Header.Add("User-Agent", fetchUserAgent)
|
||||
|
||||
resp, err := p.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch image url: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var ext = path.Ext(imageURL.Path)
|
||||
if ext == "" {
|
||||
filename, _ := getContentDispositionFilename(resp.Header)
|
||||
ext = filepath.Ext(filename)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(podcast.RootDir, os.ModePerm); err != nil {
|
||||
return fmt.Errorf("make podcast root dir: %w", err)
|
||||
}
|
||||
coverFile, err := os.Create(filepath.Join(podcast.RootDir, "cover"+ext))
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating podcast cover: %w", err)
|
||||
}
|
||||
defer coverFile.Close()
|
||||
|
||||
if _, err := io.Copy(coverFile, resp.Body); err != nil {
|
||||
return fmt.Errorf("writing podcast cover: %w", err)
|
||||
}
|
||||
podcast.Image = fmt.Sprintf("cover%s", ext)
|
||||
if err := p.db.Save(podcast).Error; err != nil {
|
||||
return fmt.Errorf("save podcast: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) DeletePodcast(podcastID int) error {
|
||||
var podcast db.Podcast
|
||||
if err := p.db.Where("id=?", podcastID).First(&podcast).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if podcast.RootDir == "" {
|
||||
return fmt.Errorf("podcast has no root dir")
|
||||
}
|
||||
|
||||
if err := os.RemoveAll(podcast.RootDir); err != nil {
|
||||
return fmt.Errorf("delete podcast directory: %w", err)
|
||||
}
|
||||
|
||||
if err := p.db.Where("id=?", podcastID).Delete(db.Podcast{}).Error; err != nil {
|
||||
return fmt.Errorf("delete podcast row: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) DeletePodcastEpisode(podcastEpisodeID int) error {
|
||||
var podcastEpisode db.PodcastEpisode
|
||||
if err := p.db.Preload("Podcast").First(&podcastEpisode, podcastEpisodeID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
podcastEpisode.Status = db.PodcastEpisodeStatusDeleted
|
||||
if err := p.db.Save(&podcastEpisode).Error; err != nil {
|
||||
return fmt.Errorf("save podcast episode: %w", err)
|
||||
}
|
||||
if err := os.Remove(podcastEpisode.AbsPath()); err != nil {
|
||||
return fmt.Errorf("remove episode: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) PurgeOldPodcasts(maxAge time.Duration) error {
|
||||
expDate := time.Now().Add(-maxAge)
|
||||
var episodes []*db.PodcastEpisode
|
||||
err := p.db.
|
||||
Where("status=?", db.PodcastEpisodeStatusCompleted).
|
||||
Where("created_at<?", expDate).
|
||||
Where("updated_at<?", expDate).
|
||||
Where("modified_at<?", expDate).
|
||||
Preload("Podcast").
|
||||
Find(&episodes).
|
||||
Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("find podcasts: %w", err)
|
||||
}
|
||||
for _, episode := range episodes {
|
||||
episode.Status = db.PodcastEpisodeStatusDeleted
|
||||
if err := p.db.Save(episode).Error; err != nil {
|
||||
return fmt.Errorf("save new podcast status: %w", err)
|
||||
}
|
||||
if episode.Podcast == nil {
|
||||
return fmt.Errorf("episode %d has no podcast", episode.ID)
|
||||
}
|
||||
if err := os.Remove(episode.AbsPath()); err != nil {
|
||||
return fmt.Errorf("remove podcast path: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSecondsFromString(time string) int {
|
||||
duration, err := strconv.Atoi(time)
|
||||
if err == nil {
|
||||
return duration
|
||||
}
|
||||
splitTime := strings.Split(time, ":")
|
||||
if len(splitTime) == 3 {
|
||||
hours, _ := strconv.Atoi(splitTime[0])
|
||||
minutes, _ := strconv.Atoi(splitTime[1])
|
||||
seconds, _ := strconv.Atoi(splitTime[2])
|
||||
return (3600 * hours) + (60 * minutes) + seconds
|
||||
}
|
||||
if len(splitTime) == 2 {
|
||||
minutes, _ := strconv.Atoi(splitTime[0])
|
||||
seconds, _ := strconv.Atoi(splitTime[1])
|
||||
return (60 * minutes) + seconds
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (p *Podcasts) DownloadTick() error {
|
||||
var podcastEpisode db.PodcastEpisode
|
||||
err := p.db.
|
||||
Preload("Podcast").
|
||||
Where("status=?", db.PodcastEpisodeStatusDownloading).
|
||||
Order("updated_at DESC").
|
||||
Find(&podcastEpisode).
|
||||
Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("find episode: %w", err)
|
||||
}
|
||||
if podcastEpisode.ID == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("starting podcast episode download %q - %q", podcastEpisode.Podcast.Title, podcastEpisode.Title)
|
||||
|
||||
if err := p.doPodcastDownload(podcastEpisode.Podcast, &podcastEpisode); err != nil {
|
||||
return fmt.Errorf("do download: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("downloaded podcast episode")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) doPodcastDownload(podcast *db.Podcast, podcastEpisode *db.PodcastEpisode) (err error) {
|
||||
req, err := http.NewRequest(http.MethodGet, podcastEpisode.AudioURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create http request: %w", err)
|
||||
}
|
||||
req.Header.Add("User-Agent", fetchUserAgent)
|
||||
|
||||
resp, err := p.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch podcast audio: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
podcastEpisode.Status = db.PodcastEpisodeStatusError
|
||||
_ = p.db.Save(podcastEpisode).Error
|
||||
}
|
||||
}()
|
||||
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("fetch podcast audio: unexpected status %s", resp.Status)
|
||||
}
|
||||
|
||||
filename, err := getPodcastEpisodeFilename(podcast, podcastEpisode, resp.Header)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get podcast episode filename: %w", err)
|
||||
}
|
||||
podcastEpisode.Filename = filename
|
||||
if err := p.db.Save(podcastEpisode).Error; err != nil {
|
||||
return fmt.Errorf("save podcast episode: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(filepath.Join(podcast.RootDir, podcastEpisode.Filename)), os.ModePerm); err != nil {
|
||||
return fmt.Errorf("make podcast root dir: %w", err)
|
||||
}
|
||||
file, err := os.Create(filepath.Join(podcast.RootDir, podcastEpisode.Filename))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create audio file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if _, err := io.Copy(file, resp.Body); err != nil {
|
||||
return fmt.Errorf("writing podcast episode: %w", err)
|
||||
}
|
||||
|
||||
podcastProps, _, err := p.tagReader.Read(podcastEpisode.AbsPath())
|
||||
if err != nil {
|
||||
return fmt.Errorf("read podcast tags: %w", err)
|
||||
}
|
||||
|
||||
podcastEpisode.Status = db.PodcastEpisodeStatusCompleted
|
||||
podcastEpisode.Bitrate = int(podcastProps.Bitrate)
|
||||
podcastEpisode.Length = int(podcastProps.Length.Seconds())
|
||||
|
||||
stat, _ := file.Stat()
|
||||
podcastEpisode.Size = int(stat.Size())
|
||||
|
||||
if err := p.db.Save(podcastEpisode).Error; err != nil {
|
||||
return fmt.Errorf("save podcast episode: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package podcast
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
_ "embed"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mmcdole/gofeed"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/mockfs"
|
||||
)
|
||||
|
||||
//go:embed testdata/rss.new
|
||||
var testRSS []byte
|
||||
|
||||
func TestPodcastsAndEpisodesWithSameName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Skip("requires network access")
|
||||
|
||||
m := mockfs.New(t)
|
||||
|
||||
base := t.TempDir()
|
||||
podcasts := New(m.DB(), base, m.TagReader())
|
||||
|
||||
fp := gofeed.NewParser()
|
||||
newFeed, err := fp.Parse(bytes.NewReader(testRSS))
|
||||
if err != nil {
|
||||
t.Fatalf("parse test data: %v", err)
|
||||
}
|
||||
|
||||
podcast, err := podcasts.AddNewPodcast("file://testdata/rss.new", newFeed)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, podcast.RootDir, filepath.Join(base, "InternetBox"))
|
||||
|
||||
podcast, err = podcasts.AddNewPodcast("file://testdata/rss.new", newFeed)
|
||||
require.NoError(t, err)
|
||||
|
||||
// check we made a unique podcast name
|
||||
require.Equal(t, podcast.RootDir, filepath.Join(base, "InternetBox (1)"))
|
||||
|
||||
podcastEpisodes, err := podcasts.GetNewestPodcastEpisodes(10)
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, len(podcastEpisodes), 0)
|
||||
|
||||
var pe []*db.PodcastEpisode
|
||||
require.NoError(t, m.DB().Order("id").Find(&pe, "podcast_id=? AND title=?", podcast.ID, "Episode 126").Error)
|
||||
require.Len(t, pe, 2)
|
||||
|
||||
require.NoError(t, podcasts.DownloadEpisode(pe[0].ID))
|
||||
require.NoError(t, podcasts.DownloadEpisode(pe[1].ID))
|
||||
|
||||
require.NoError(t, m.DB().Order("id").Preload("Podcast").Find(&pe, "podcast_id=? AND title=?", podcast.ID, "Episode 126").Error)
|
||||
require.Len(t, pe, 2)
|
||||
|
||||
// check we made a unique podcast episode names
|
||||
require.Equal(t, "InternetBoxEpisode126.mp3", pe[0].Filename)
|
||||
require.Equal(t, "InternetBoxEpisode126 (1).mp3", pe[1].Filename)
|
||||
}
|
||||
|
||||
func TestGetMoreRecentEpisodes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fp := gofeed.NewParser()
|
||||
newFeed, err := fp.Parse(bytes.NewReader(testRSS))
|
||||
if err != nil {
|
||||
t.Fatalf("parse test data: %v", err)
|
||||
}
|
||||
after, err := time.Parse(time.RFC1123, "Mon, 27 Jun 2016 06:33:43 +0000")
|
||||
if err != nil {
|
||||
t.Fatalf("parse time: %v", err)
|
||||
}
|
||||
entries := getEntriesAfterDate(newFeed.Items, after)
|
||||
if len(entries) != 2 {
|
||||
t.Errorf("expected 2 entries, got %d", len(entries))
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:cc="http://web.resource.org/cc/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<channel>
|
||||
<atom:link href="https://internetbox.libsyn.com/rss" rel="self" type="application/rss+xml"/>
|
||||
<title>Internet Box!</title>
|
||||
<pubDate>Mon, 01 Apr 2019 04:35:43 +0000</pubDate>
|
||||
<lastBuildDate>Sun, 10 Jan 2021 00:07:33 +0000</lastBuildDate>
|
||||
<generator>Libsyn WebEngine 2.0</generator>
|
||||
<link>https://internetboxpodcast.com</link>
|
||||
<language>en</language>
|
||||
<copyright><![CDATA[]]></copyright>
|
||||
<docs>https://internetboxpodcast.com</docs>
|
||||
<managingEditor>admin@internetboxpodcast.com (admin@internetboxpodcast.com)</managingEditor>
|
||||
<itunes:summary><![CDATA[Michael, Mike, Barbara, Ray, Andrew, Dylon, Lindsay, and Kerry from the AH community talk about various subjects.]]></itunes:summary>
|
||||
<image>
|
||||
<url>https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png</url>
|
||||
<title>Internet Box</title>
|
||||
<link><![CDATA[https://internetboxpodcast.com]]></link>
|
||||
</image>
|
||||
<itunes:author>Internet Box Crew</itunes:author>
|
||||
<itunes:keywords>achievement,box,friendship,hunter,internet,is,little,magic,mlp,my,pony,rooster,teeth</itunes:keywords>
|
||||
<itunes:category text="Leisure">
|
||||
<itunes:category text="Video Games"/>
|
||||
</itunes:category>
|
||||
<itunes:category text="Comedy"/>
|
||||
<itunes:image href="https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png" />
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:owner>
|
||||
<itunes:name><![CDATA[Mike]]></itunes:name>
|
||||
<itunes:email>admin@internetboxpodcast.com</itunes:email>
|
||||
</itunes:owner>
|
||||
<description><![CDATA[Michael, Mike, Barbara, Ray, Andrew, Dylon, Lindsay, and Kerry from the AH community talk about various subjects.]]></description>
|
||||
<itunes:subtitle><![CDATA[Various members from the AH community discuss games, ponies, and life in general.]]></itunes:subtitle>
|
||||
<itunes:type>episodic</itunes:type>
|
||||
|
||||
|
||||
|
||||
|
||||
<item>
|
||||
<title>Episode 128</title>
|
||||
<pubDate>Mon, 01 Apr 2019 04:35:43 +0000</pubDate>
|
||||
<guid isPermaLink="false"><![CDATA[c60f174610d44b408901d6a8d98366b4]]></guid>
|
||||
<link><![CDATA[https://internetboxpodcast.com/episode-128/]]></link>
|
||||
<itunes:image href="https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png" />
|
||||
<description><![CDATA[<p> </p> <p>The Internet Box is fooling around this week!</p> <p> </p>]]></description>
|
||||
<content:encoded><![CDATA[<p> </p> <p>The Internet Box is fooling around this week!</p> <p> </p>]]></content:encoded>
|
||||
<enclosure length="14637384" type="audio/mpeg" url="https://traffic.libsyn.com/secure/internetbox/InternetBoxEpisode128.mp3?dest-id=79492" />
|
||||
<itunes:duration>44:41</itunes:duration>
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:keywords>box,meme,fools,april,reddit,copypaste,inernet</itunes:keywords>
|
||||
<itunes:subtitle><![CDATA[ The Internet Box is fooling around this week! ]]></itunes:subtitle>
|
||||
<itunes:episodeType>full</itunes:episodeType>
|
||||
</item>
|
||||
<item>
|
||||
<title>Episode 127</title>
|
||||
<pubDate>Sat, 06 Aug 2016 04:46:28 +0000</pubDate>
|
||||
<guid isPermaLink="false"><![CDATA[99b830789a90b2b6a712382fe4bffc6b]]></guid>
|
||||
<link><![CDATA[http://internetboxpodcast.com/episode-127/]]></link>
|
||||
<itunes:image href="https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png" />
|
||||
<description><![CDATA[<p>The Internet Box is a national treasure this week!</p>]]></description>
|
||||
<content:encoded><![CDATA[<p>The Internet Box is a national treasure this week!</p>]]></content:encoded>
|
||||
<enclosure length="152364335" type="audio/mpeg" url="https://traffic.libsyn.com/secure/internetbox/InternetBoxEpisode127.mp3?dest-id=79492" />
|
||||
<itunes:duration>01:45:48</itunes:duration>
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:keywords>box,2,internet,cage,movies,national,go,season,treasure,nic,bane,pokemon</itunes:keywords>
|
||||
<itunes:subtitle><![CDATA[The Internet Box is a national treasure this week!]]></itunes:subtitle>
|
||||
</item>
|
||||
<item>
|
||||
<title>Episode 126</title>
|
||||
<pubDate>Mon, 27 Jun 2016 06:33:43 +0000</pubDate>
|
||||
<guid isPermaLink="false"><![CDATA[d5113fc98b7baf005bf66b225b166ee0]]></guid>
|
||||
<link><![CDATA[http://internetboxpodcast.com/episode-126/]]></link>
|
||||
<itunes:image href="file://testdata/cover.png" />
|
||||
<description><![CDATA[<p>The Internet Box is clicking this week!</p>]]></description>
|
||||
<content:encoded><![CDATA[<p>The Internet Box is clicking this week!</p>]]></content:encoded>
|
||||
<enclosure length="66139165" type="audio/mpeg" url="https://traffic.libsyn.com/secure/internetbox/InternetBoxEpisode126.mp3?dest-id=79492" />
|
||||
<itunes:duration>01:20:42</itunes:duration>
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:keywords>box,2,factory,internet,pizza,future,robots,season,farts,cake,via,reddit,313,vorarephilia</itunes:keywords>
|
||||
<itunes:subtitle><![CDATA[The Internet Box is clicking this week!]]></itunes:subtitle>
|
||||
</item>
|
||||
|
||||
<!-- dupe episode name -->
|
||||
<item>
|
||||
<title>Episode 126</title>
|
||||
<pubDate>Mon, 27 Jun 2016 06:33:43 +0000</pubDate>
|
||||
<guid isPermaLink="false"><![CDATA[d5113fc98b7baf005bf66b225b166ee0]]></guid>
|
||||
<link><![CDATA[http://internetboxpodcast.com/episode-126/]]></link>
|
||||
<itunes:image href="file://testdata/cover.png" />
|
||||
<description><![CDATA[<p>The Internet Box is clicking this week!</p>]]></description>
|
||||
<content:encoded><![CDATA[<p>The Internet Box is clicking this week!</p>]]></content:encoded>
|
||||
<enclosure length="66139165" type="audio/mpeg" url="https://traffic.libsyn.com/secure/internetbox/InternetBoxEpisode126.mp3?dest-id=79492" />
|
||||
<itunes:duration>01:20:42</itunes:duration>
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:keywords>box,2,factory,internet,pizza,future,robots,season,farts,cake,via,reddit,313,vorarephilia</itunes:keywords>
|
||||
<itunes:subtitle><![CDATA[The Internet Box is clicking this week!]]></itunes:subtitle>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>
|
||||
@@ -0,0 +1,8 @@
|
||||
/** @type {import('postcss-load-config').Config} */
|
||||
const config = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
@@ -1,32 +0,0 @@
|
||||
package scanner_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"go.senan.xyz/gonic/mockfs"
|
||||
)
|
||||
|
||||
func BenchmarkScanIncremental(b *testing.B) {
|
||||
m := mockfs.New(b)
|
||||
for i := range 5 {
|
||||
m.AddItemsPrefix(fmt.Sprintf("t-%d", i))
|
||||
}
|
||||
m.ScanAndClean()
|
||||
|
||||
for b.Loop() {
|
||||
m.ScanAndClean()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkScanFull(b *testing.B) {
|
||||
for b.Loop() {
|
||||
m := mockfs.New(b)
|
||||
for i := range 5 {
|
||||
m.AddItemsPrefix(fmt.Sprintf("t-%d", i))
|
||||
}
|
||||
b.StartTimer()
|
||||
m.ScanAndClean()
|
||||
b.StopTimer()
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package scanner_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"go.senan.xyz/gonic/mockfs"
|
||||
)
|
||||
|
||||
func FuzzScanner(f *testing.F) {
|
||||
checkDelta := func(assert *assert.Assertions, m *mockfs.MockFS, expSeen, expNew int) {
|
||||
st := m.ScanAndClean()
|
||||
assert.Equal(st.SeenTracks(), expSeen)
|
||||
assert.Equal(st.SeenTracksNew(), expNew)
|
||||
assert.Equal(st.TracksMissing(), 0)
|
||||
assert.Equal(st.AlbumsMissing(), 0)
|
||||
assert.Equal(st.ArtistsMissing(), 0)
|
||||
assert.Equal(st.GenresMissing(), 0)
|
||||
}
|
||||
|
||||
f.Fuzz(func(t *testing.T, data []byte, seed int64) {
|
||||
assert := assert.New(t)
|
||||
m := mockfs.New(t)
|
||||
|
||||
const toAdd = 1000
|
||||
for i := range toAdd {
|
||||
path := fmt.Sprintf("artist-%d/album-%d/track-%d.flac", i/6, i/3, i)
|
||||
m.AddTrack(path)
|
||||
m.SetTags(path, func(tags *mockfs.TagInfo) {
|
||||
fuzzStruct(i, data, seed, tags)
|
||||
})
|
||||
}
|
||||
|
||||
checkDelta(assert, m, toAdd, toAdd) // we added all tracks, 0 delta
|
||||
checkDelta(assert, m, toAdd, 0) // we added 0 tracks, 0 delta
|
||||
})
|
||||
}
|
||||
|
||||
func fuzzStruct(taken int, data []byte, seed int64, dest any) {
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
r := rand.New(rand.NewSource(seed))
|
||||
v := reflect.ValueOf(dest)
|
||||
for i := 0; i < v.Elem().NumField(); i++ {
|
||||
if r.Float64() < 0.1 {
|
||||
continue
|
||||
}
|
||||
|
||||
take := int(r.Float64() * 12)
|
||||
b := make([]byte, take)
|
||||
for i := range b {
|
||||
b[i] = data[(i+taken)%len(data)]
|
||||
}
|
||||
taken += take
|
||||
|
||||
switch f := v.Elem().Field(i); f.Kind() {
|
||||
case reflect.Bool:
|
||||
f.SetBool(b[0] < 128)
|
||||
case reflect.String:
|
||||
f.SetString(string(b))
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
f.SetInt(int64(b[0]))
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
f.SetUint(uint64(b[0]))
|
||||
case reflect.Float32, reflect.Float64:
|
||||
f.SetFloat(float64(b[0]))
|
||||
case reflect.Struct:
|
||||
fuzzStruct(taken, data, seed, f.Addr().Interface())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,964 +0,0 @@
|
||||
//nolint:goconst,errorlint
|
||||
package scanner_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
_ "go.senan.xyz/gonic/deps"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/mockfs"
|
||||
"go.senan.xyz/gonic/scanner"
|
||||
"go.senan.xyz/wrtag/tags/normtag"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
log.SetOutput(io.Discard)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestTableCounts(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
var tracks int
|
||||
assert.NoError(t, m.DB().Model(&db.Track{}).Count(&tracks).Error) // not all tracks
|
||||
assert.Equal(t, tracks, m.NumTracks())
|
||||
|
||||
var albums int
|
||||
assert.NoError(t, m.DB().Model(&db.Album{}).Count(&albums).Error) // not all albums
|
||||
assert.Equal(t, albums, 13) // not all albums
|
||||
|
||||
var artists int
|
||||
assert.NoError(t, m.DB().Model(&db.Artist{}).Count(&artists).Error) // not all artists
|
||||
assert.Equal(t, artists, 3) // not all artists
|
||||
}
|
||||
|
||||
func TestWithExcludePattern(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.NewWithExcludePattern(t, "\\/artist-1\\/|track-0.flac$")
|
||||
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
var tracks int
|
||||
assert.NoError(t, m.DB().Model(&db.Track{}).Count(&tracks).Error) // not all tracks
|
||||
assert.Equal(t, tracks, 12)
|
||||
|
||||
var albums int
|
||||
assert.NoError(t, m.DB().Model(&db.Album{}).Count(&albums).Error) // not all albums
|
||||
assert.Equal(t, albums, 10) // not all albums
|
||||
|
||||
var artists int
|
||||
assert.NoError(t, m.DB().Model(&db.Artist{}).Count(&artists).Error) // not all artists
|
||||
assert.Equal(t, artists, 2) // not all artists
|
||||
}
|
||||
|
||||
func TestParentID(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
var nullParentAlbums []*db.Album
|
||||
assert.NoError(t, m.DB().Where("parent_id IS NULL").Find(&nullParentAlbums).Error) // one parent_id=NULL which is root folder
|
||||
assert.Equal(t, 1, len(nullParentAlbums)) // one parent_id=NULL which is root folder
|
||||
assert.Equal(t, "", nullParentAlbums[0].LeftPath)
|
||||
assert.Equal(t, ".", nullParentAlbums[0].RightPath)
|
||||
|
||||
assert.Equal(t, gorm.ErrRecordNotFound, m.DB().Where("id=parent_id").Find(&db.Album{}).Error) // no self-referencing albums
|
||||
|
||||
var album db.Album
|
||||
var parent db.Album
|
||||
assert.NoError(t, m.DB().Find(&album, "left_path=? AND right_path=?", "artist-0/", "album-0").Error) // album has parent ID
|
||||
assert.NoError(t, m.DB().Find(&parent, "right_path=?", "artist-0").Error) // album has parent ID
|
||||
assert.Equal(t, parent.ID, album.ParentID) // album has parent ID
|
||||
}
|
||||
|
||||
func TestUpdatedCover(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
m.AddCover("artist-0/album-0/cover.jpg")
|
||||
m.ScanAndClean()
|
||||
|
||||
var album db.Album
|
||||
assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&album).Error) // album has cover
|
||||
assert.Equal(t, album.Cover, "cover.jpg") // album has cover
|
||||
}
|
||||
|
||||
func TestCoverBeforeTracks(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddCover("artist-2/album-2/cover.jpg")
|
||||
m.ScanAndClean()
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
var album db.Album
|
||||
assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&album).Error) // album has cover
|
||||
assert.Equal(t, "cover.jpg", album.Cover) // album has cover
|
||||
|
||||
var albumArtist db.Artist
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", album.ID).Find(&albumArtist).Error) // album has cover
|
||||
assert.Equal(t, "artist-2", albumArtist.Name) // album artist
|
||||
|
||||
var tracks []*db.Track
|
||||
assert.NoError(t, m.DB().Where("album_id=?", album.ID).Find(&tracks).Error) // album has tracks
|
||||
assert.Equal(t, 3, len(tracks)) // album has tracks
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/issues/638
|
||||
func TestAlbumArtistsClearedWhenFolderLosesTracks(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
loosePath := "artist-0/fusion.flac"
|
||||
nestedPath := "artist-0/album-0/track-0.flac"
|
||||
|
||||
m.AddTrack(loosePath)
|
||||
m.SetTags(loosePath, func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, "artist-0")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, "artist-0")
|
||||
normtag.Set(tags.Tags, normtag.Album, "Fusion Firespace")
|
||||
normtag.Set(tags.Tags, normtag.Title, "Fusion Firespace")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var albumArtistCount int
|
||||
require.NoError(t, m.DB().Model(db.AlbumArtist{}).Count(&albumArtistCount).Error)
|
||||
require.Equal(t, 1, albumArtistCount)
|
||||
|
||||
m.Move(loosePath, nestedPath)
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var postAlbumArtistCount int
|
||||
require.NoError(t, m.DB().Model(db.AlbumArtist{}).Count(&postAlbumArtistCount).Error)
|
||||
require.Equal(t, 1, postAlbumArtistCount)
|
||||
}
|
||||
|
||||
func TestUpdatedTags(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddTrack("artist-10/album-10/track-10.flac")
|
||||
m.SetTags("artist-10/album-10/track-10.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, "artist")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, "album-artist")
|
||||
normtag.Set(tags.Tags, normtag.Album, "album")
|
||||
normtag.Set(tags.Tags, normtag.Title, "title")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var track db.Track
|
||||
assert.NoError(t, m.DB().Preload("Album").Where("filename=?", "track-10.flac").Find(&track).Error) // track has tags
|
||||
assert.Equal(t, "artist", track.TagTrackArtist) // track has tags
|
||||
assert.Equal(t, "album", track.Album.TagTitle) // track has tags
|
||||
assert.Equal(t, "title", track.TagTitle) // track has tags
|
||||
|
||||
var trackArtistA db.Artist
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", track.AlbumID).Limit(1).Find(&trackArtistA).Error) // updated has tags
|
||||
assert.Equal(t, "album-artist", trackArtistA.Name) // track has tags
|
||||
|
||||
m.SetTags("artist-10/album-10/track-10.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, "artist-upd")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, "album-artist-upd")
|
||||
normtag.Set(tags.Tags, normtag.Album, "album-upd")
|
||||
normtag.Set(tags.Tags, normtag.Title, "title-upd")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var updated db.Track
|
||||
assert.NoError(t, m.DB().Preload("Album").Where("filename=?", "track-10.flac").Find(&updated).Error) // updated has tags
|
||||
assert.Equal(t, track.ID, updated.ID) // updated has tags
|
||||
assert.Equal(t, "artist-upd", updated.TagTrackArtist) // updated has tags
|
||||
assert.Equal(t, "album-upd", updated.Album.TagTitle) // updated has tags
|
||||
assert.Equal(t, "title-upd", updated.TagTitle) // updated has tags
|
||||
|
||||
var trackArtistB db.Artist
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", track.AlbumID).Limit(1).Find(&trackArtistB).Error) // updated has tags
|
||||
assert.Equal(t, "album-artist-upd", trackArtistB.Name) // updated has tags
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/issues/225
|
||||
func TestUpdatedAlbumGenre(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Genre, "gen-a;gen-b")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var album db.Album
|
||||
assert.NoError(t, m.DB().Preload("Genres").Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&album).Error)
|
||||
assert.Equal(t, []string{"gen-a", "gen-b"}, genreStrings(album))
|
||||
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Genre, "gen-a-upd;gen-b-upd")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var updated db.Album
|
||||
assert.NoError(t, m.DB().Preload("Genres").Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&updated).Error)
|
||||
assert.Equal(t, []string{"gen-a-upd", "gen-b-upd"}, genreStrings(updated))
|
||||
}
|
||||
|
||||
func genreStrings(album db.Album) []string {
|
||||
var strs []string
|
||||
for _, genre := range album.Genres {
|
||||
strs = append(strs, genre.Name)
|
||||
}
|
||||
return strs
|
||||
}
|
||||
|
||||
func TestDeleteAlbum(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error) // album exists
|
||||
|
||||
m.RemoveAll("artist-2/album-2")
|
||||
m.ScanAndClean()
|
||||
|
||||
assert.Equal(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error, gorm.ErrRecordNotFound) // album doesn't exist
|
||||
}
|
||||
|
||||
func TestDeleteArtist(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error) // album exists
|
||||
|
||||
m.RemoveAll("artist-2")
|
||||
m.ScanAndClean()
|
||||
|
||||
assert.Equal(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error, gorm.ErrRecordNotFound) // album doesn't exist
|
||||
assert.Equal(t, m.DB().Where("name=?", "artist-2").Find(&db.Artist{}).Error, gorm.ErrRecordNotFound) // artist doesn't exist
|
||||
}
|
||||
|
||||
func TestGenres(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
albumGenre := func(artist, album, genre string) error {
|
||||
return m.DB().
|
||||
Where("albums.left_path=? AND albums.right_path=? AND genres.name=?", artist, album, genre).
|
||||
Joins("JOIN albums ON albums.id=album_genres.album_id").
|
||||
Joins("JOIN genres ON genres.id=album_genres.genre_id").
|
||||
Find(&db.AlbumGenre{}).
|
||||
Error
|
||||
}
|
||||
isAlbumGenre := func(artist, album, genreName string) {
|
||||
assert.NoError(t, albumGenre(artist, album, genreName))
|
||||
}
|
||||
isAlbumGenreMissing := func(artist, album, genreName string) {
|
||||
assert.Equal(t, albumGenre(artist, album, genreName), gorm.ErrRecordNotFound)
|
||||
}
|
||||
|
||||
trackGenre := func(artist, album, filename, genreName string) error {
|
||||
return m.DB().
|
||||
Where("albums.left_path=? AND albums.right_path=? AND tracks.filename=? AND genres.name=?", artist, album, filename, genreName).
|
||||
Joins("JOIN tracks ON tracks.id=track_genres.track_id").
|
||||
Joins("JOIN genres ON genres.id=track_genres.genre_id").
|
||||
Joins("JOIN albums ON albums.id=tracks.album_id").
|
||||
Find(&db.TrackGenre{}).
|
||||
Error
|
||||
}
|
||||
isTrackGenre := func(artist, album, filename, genreName string) {
|
||||
assert.NoError(t, trackGenre(artist, album, filename, genreName))
|
||||
}
|
||||
isTrackGenreMissing := func(artist, album, filename, genreName string) {
|
||||
assert.Equal(t, trackGenre(artist, album, filename, genreName), gorm.ErrRecordNotFound)
|
||||
}
|
||||
|
||||
genre := func(genre string) error {
|
||||
return m.DB().Where("name=?", genre).Find(&db.Genre{}).Error
|
||||
}
|
||||
isGenre := func(genreName string) {
|
||||
assert.NoError(t, genre(genreName))
|
||||
}
|
||||
isGenreMissing := func(genreName string) {
|
||||
assert.Equal(t, genre(genreName), gorm.ErrRecordNotFound)
|
||||
}
|
||||
|
||||
m.AddItems()
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-a;genre-b") })
|
||||
m.SetTags("artist-0/album-0/track-1.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-c;genre-d") })
|
||||
m.SetTags("artist-1/album-2/track-0.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-e;genre-f") })
|
||||
m.SetTags("artist-1/album-2/track-1.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-g;genre-h") })
|
||||
m.ScanAndClean()
|
||||
|
||||
isGenre("genre-a") // genre exists
|
||||
isGenre("genre-b") // genre exists
|
||||
isGenre("genre-c") // genre exists
|
||||
isGenre("genre-d") // genre exists
|
||||
|
||||
isTrackGenre("artist-0/", "album-0", "track-0.flac", "genre-a") // track genre exists
|
||||
isTrackGenre("artist-0/", "album-0", "track-0.flac", "genre-b") // track genre exists
|
||||
isTrackGenre("artist-0/", "album-0", "track-1.flac", "genre-c") // track genre exists
|
||||
isTrackGenre("artist-0/", "album-0", "track-1.flac", "genre-d") // track genre exists
|
||||
isTrackGenre("artist-1/", "album-2", "track-0.flac", "genre-e") // track genre exists
|
||||
isTrackGenre("artist-1/", "album-2", "track-0.flac", "genre-f") // track genre exists
|
||||
isTrackGenre("artist-1/", "album-2", "track-1.flac", "genre-g") // track genre exists
|
||||
isTrackGenre("artist-1/", "album-2", "track-1.flac", "genre-h") // track genre exists
|
||||
|
||||
isAlbumGenre("artist-0/", "album-0", "genre-a") // album genre exists
|
||||
isAlbumGenre("artist-0/", "album-0", "genre-b") // album genre exists
|
||||
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-aa;genre-bb") })
|
||||
m.ScanAndClean()
|
||||
|
||||
isTrackGenre("artist-0/", "album-0", "track-0.flac", "genre-aa") // updated track genre exists
|
||||
isTrackGenre("artist-0/", "album-0", "track-0.flac", "genre-bb") // updated track genre exists
|
||||
isTrackGenreMissing("artist-0/", "album-0", "track-0.flac", "genre-a") // old track genre missing
|
||||
isTrackGenreMissing("artist-0/", "album-0", "track-0.flac", "genre-b") // old track genre missing
|
||||
|
||||
isAlbumGenreMissing("artist-0/", "album-0", "genre-a") // old album genre missing
|
||||
isAlbumGenreMissing("artist-0/", "album-0", "genre-b") // old album genre missing
|
||||
|
||||
isGenreMissing("genre-a") // old genre missing
|
||||
isGenreMissing("genre-b") // old genre missing
|
||||
}
|
||||
|
||||
func TestMultiFolders(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.NewWithDirs(t, []string{"m-1", "m-2", "m-3"})
|
||||
|
||||
m.AddItemsPrefix("m-1")
|
||||
m.AddItemsPrefix("m-2")
|
||||
m.AddItemsPrefix("m-3")
|
||||
m.ScanAndClean()
|
||||
|
||||
var rootDirs []*db.Album
|
||||
assert.NoError(t, m.DB().Where("parent_id IS NULL").Find(&rootDirs).Error)
|
||||
assert.Equal(t, 3, len(rootDirs))
|
||||
for i, r := range rootDirs {
|
||||
assert.Equal(t, filepath.Join(m.TmpDir(), fmt.Sprintf("m-%d", i+1)), r.RootDir)
|
||||
assert.Equal(t, 0, r.ParentID)
|
||||
assert.Equal(t, "", r.LeftPath)
|
||||
assert.Equal(t, ".", r.RightPath)
|
||||
}
|
||||
|
||||
m.AddCover("m-3/artist-0/album-0/cover.jpg")
|
||||
m.ScanAndClean()
|
||||
m.LogItems()
|
||||
|
||||
checkCover := func(root string, q string) {
|
||||
assert.NoError(t, m.DB().Where(q, filepath.Join(m.TmpDir(), root)).Find(&db.Album{}).Error)
|
||||
}
|
||||
|
||||
checkCover("m-1", "root_dir=? AND cover IS NULL") // mf 1 no cover
|
||||
checkCover("m-2", "root_dir=? AND cover IS NULL") // mf 2 no cover
|
||||
checkCover("m-3", "root_dir=? AND cover='cover.jpg'") // mf 3 has cover
|
||||
}
|
||||
|
||||
func TestNewAlbumForExistingArtist(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.ScanAndClean()
|
||||
|
||||
m.LogAlbums()
|
||||
m.LogArtists()
|
||||
|
||||
var artist db.Artist
|
||||
assert.NoError(t, m.DB().Where("name=?", "artist-2").Find(&artist).Error) // find orig artist
|
||||
assert.Greater(t, artist.ID, 0)
|
||||
|
||||
for tr := range 3 {
|
||||
m.AddTrack(fmt.Sprintf("artist-2/new-album/track-%d.mp3", tr))
|
||||
m.SetTags(fmt.Sprintf("artist-2/new-album/track-%d.mp3", tr), func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, "artist-2")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, "artist-2")
|
||||
normtag.Set(tags.Tags, normtag.Album, "new-album")
|
||||
normtag.Set(tags.Tags, normtag.Title, fmt.Sprintf("title-%d", tr))
|
||||
})
|
||||
}
|
||||
|
||||
var updated db.Artist
|
||||
assert.NoError(t, m.DB().Where("name=?", "artist-2").Find(&updated).Error) // find updated artist
|
||||
assert.Equal(t, updated.ID, artist.ID) // find updated artist
|
||||
|
||||
var all []*db.Artist
|
||||
assert.NoError(t, m.DB().Find(&all).Error) // still only 3?
|
||||
assert.Equal(t, 3, len(all)) // still only 3?
|
||||
}
|
||||
|
||||
func TestMultiFolderWithSharedArtist(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.NewWithDirs(t, []string{"m-0", "m-1"})
|
||||
|
||||
const artistName = "artist-a"
|
||||
|
||||
m.AddTrack(fmt.Sprintf("m-0/%s/album-a/track-1.flac", artistName))
|
||||
m.SetTags(fmt.Sprintf("m-0/%s/album-a/track-1.flac", artistName), func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, artistName)
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, artistName)
|
||||
normtag.Set(tags.Tags, normtag.Album, "album-a")
|
||||
normtag.Set(tags.Tags, normtag.Title, "track-1")
|
||||
})
|
||||
m.ScanAndClean()
|
||||
|
||||
m.AddTrack(fmt.Sprintf("m-1/%s/album-a/track-1.flac", artistName))
|
||||
m.SetTags(fmt.Sprintf("m-1/%s/album-a/track-1.flac", artistName), func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, artistName)
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, artistName)
|
||||
normtag.Set(tags.Tags, normtag.Album, "album-a")
|
||||
normtag.Set(tags.Tags, normtag.Title, "track-1")
|
||||
})
|
||||
m.ScanAndClean()
|
||||
|
||||
var artist db.Artist
|
||||
assert.NoError(t, m.DB().Where("name=?", artistName).First(&artist).Error)
|
||||
assert.Equal(t, artistName, artist.Name)
|
||||
|
||||
var artistAlbums []*db.Album
|
||||
assert.NoError(t, m.DB().
|
||||
Select("*, count(sub.id) child_count, sum(sub.length) duration").
|
||||
Joins("JOIN album_artists ON album_artists.album_id=albums.id").
|
||||
Joins("LEFT JOIN tracks sub ON albums.id=sub.album_id").
|
||||
Where("album_artists.artist_id=?", artist.ID).
|
||||
Group("albums.id").
|
||||
Find(&artistAlbums).Error)
|
||||
|
||||
assert.Equal(t, 2, len(artistAlbums))
|
||||
|
||||
for _, album := range artistAlbums {
|
||||
assert.Greater(t, album.TagYear, 0)
|
||||
assert.Greater(t, album.ChildCount, 0)
|
||||
assert.Greater(t, album.Duration, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrackContributors(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddTrack("artist-a/album-a/track-1.flac")
|
||||
m.SetTags("artist-a/album-a/track-1.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, "artist-a")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, "artist-a")
|
||||
normtag.Set(tags.Tags, normtag.Album, "album-a")
|
||||
normtag.Set(tags.Tags, normtag.Title, "track-1")
|
||||
normtag.Set(tags.Tags, normtag.Composers, "comp-a", "comp-b")
|
||||
normtag.Set(tags.Tags, normtag.Remixer, "rem-a")
|
||||
normtag.Set(tags.Tags, "LYRICIST", "lyr-a")
|
||||
normtag.Set(tags.Tags, "PRODUCER", "prod-a")
|
||||
})
|
||||
m.ScanAndClean()
|
||||
|
||||
var track db.Track
|
||||
require.NoError(t, m.DB().Preload("Contributors.Artist").Where("tag_title=?", "track-1").First(&track).Error)
|
||||
|
||||
type pair struct {
|
||||
Role db.ContributorRole
|
||||
Artist string
|
||||
}
|
||||
var got []pair
|
||||
for _, c := range track.Contributors {
|
||||
got = append(got, pair{Role: c.Role, Artist: c.Artist.Name})
|
||||
}
|
||||
assert.ElementsMatch(t, []pair{
|
||||
{db.ContributorRoleComposer, "comp-a"},
|
||||
{db.ContributorRoleComposer, "comp-b"},
|
||||
{db.ContributorRoleRemixer, "rem-a"},
|
||||
{db.ContributorRoleLyricist, "lyr-a"},
|
||||
{db.ContributorRoleProducer, "prod-a"},
|
||||
}, got)
|
||||
|
||||
// contributor artists should also show up on the album via artist_appearances
|
||||
for _, name := range []string{"comp-a", "comp-b", "rem-a", "lyr-a", "prod-a"} {
|
||||
var count int
|
||||
require.NoError(t, m.DB().
|
||||
Model(&db.ArtistAppearances{}).
|
||||
Joins("JOIN artists ON artists.id=artist_appearances.artist_id").
|
||||
Where("artists.name=?", name).
|
||||
Count(&count).Error)
|
||||
assert.Equal(t, 1, count, "expected %q in artist_appearances", name)
|
||||
}
|
||||
|
||||
// re-scanning with a changed composer list should clear the stale row (comp-b)
|
||||
// and add the new one (comp-c). other roles stay since their tags didn't change.
|
||||
m.SetTags("artist-a/album-a/track-1.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Composers, "comp-a", "comp-c")
|
||||
})
|
||||
m.ScanAndClean()
|
||||
|
||||
require.NoError(t, m.DB().Preload("Contributors.Artist").Where("tag_title=?", "track-1").First(&track).Error)
|
||||
got = got[:0]
|
||||
for _, c := range track.Contributors {
|
||||
got = append(got, pair{Role: c.Role, Artist: c.Artist.Name})
|
||||
}
|
||||
assert.ElementsMatch(t, []pair{
|
||||
{db.ContributorRoleComposer, "comp-a"},
|
||||
{db.ContributorRoleComposer, "comp-c"},
|
||||
{db.ContributorRoleRemixer, "rem-a"},
|
||||
{db.ContributorRoleLyricist, "lyr-a"},
|
||||
{db.ContributorRoleProducer, "prod-a"},
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestSymlinkedAlbum(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.NewWithDirs(t, []string{"scan"})
|
||||
|
||||
m.AddItemsPrefixWithCovers("temp")
|
||||
|
||||
tempAlbum0 := filepath.Join(m.TmpDir(), "temp", "artist-0", "album-0")
|
||||
scanAlbum0 := filepath.Join(m.TmpDir(), "scan", "artist-sym", "album-0")
|
||||
m.Symlink(tempAlbum0, scanAlbum0)
|
||||
|
||||
m.ScanAndClean()
|
||||
m.LogTracks()
|
||||
m.LogAlbums()
|
||||
|
||||
var track db.Track
|
||||
require.NoError(t, m.DB().Preload("Album.Parent").Find(&track).Error) // track exists
|
||||
require.NotNil(t, track.Album) // track has album
|
||||
require.NotZero(t, track.Album.Cover) // album has cover
|
||||
require.Equal(t, "artist-sym", track.Album.Parent.RightPath) // artist is sym
|
||||
|
||||
info, err := os.Stat(track.AbsPath())
|
||||
require.NoError(t, err) // track resolves
|
||||
require.False(t, info.IsDir()) // track resolves
|
||||
require.NotZero(t, info.ModTime()) // track resolves
|
||||
}
|
||||
|
||||
func TestSymlinkedSubdiscs(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.NewWithDirs(t, []string{"scan"})
|
||||
|
||||
addItem := func(prefix, artist, album, disc, track string) {
|
||||
p := fmt.Sprintf("%s/%s/%s/%s/%s", prefix, artist, album, disc, track)
|
||||
m.AddTrack(p)
|
||||
m.SetTags(p, func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Artist, artist)
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, artist)
|
||||
normtag.Set(tags.Tags, normtag.Album, album)
|
||||
normtag.Set(tags.Tags, normtag.Title, track)
|
||||
})
|
||||
}
|
||||
|
||||
addItem("temp", "artist-a", "album-a", "disc-1", "track-1.flac")
|
||||
addItem("temp", "artist-a", "album-a", "disc-1", "track-2.flac")
|
||||
addItem("temp", "artist-a", "album-a", "disc-1", "track-3.flac")
|
||||
addItem("temp", "artist-a", "album-a", "disc-2", "track-1.flac")
|
||||
addItem("temp", "artist-a", "album-a", "disc-2", "track-2.flac")
|
||||
addItem("temp", "artist-a", "album-a", "disc-2", "track-3.flac")
|
||||
|
||||
tempAlbum0 := filepath.Join(m.TmpDir(), "temp", "artist-a", "album-a")
|
||||
scanAlbum0 := filepath.Join(m.TmpDir(), "scan", "artist-a", "album-sym")
|
||||
m.Symlink(tempAlbum0, scanAlbum0)
|
||||
|
||||
m.ScanAndClean()
|
||||
m.LogTracks()
|
||||
m.LogAlbums()
|
||||
|
||||
var track db.Track
|
||||
assert.NoError(t, m.DB().Preload("Album.Parent").Find(&track).Error) // track exists
|
||||
assert.NotNil(t, track.Album) // track has album
|
||||
assert.Equal(t, "album-sym", track.Album.Parent.RightPath) // artist is sym
|
||||
|
||||
info, err := os.Stat(track.AbsPath())
|
||||
assert.NoError(t, err) // track resolves
|
||||
assert.False(t, info.IsDir()) // track resolves
|
||||
assert.NotZero(t, info.ModTime()) // track resolves
|
||||
}
|
||||
|
||||
func TestSymlinkEscapesMusicDirs(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.NewWithDirs(t, []string{"scandir"})
|
||||
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(m.TmpDir(), "otherdir", "artist", "album-test"), os.ModePerm))
|
||||
require.NoError(t, os.Symlink(
|
||||
filepath.Join(m.TmpDir(), "otherdir", "artist"),
|
||||
filepath.Join(m.TmpDir(), "scandir", "artist"),
|
||||
))
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var albums []*db.Album
|
||||
require.NoError(t, m.DB().Find(&albums).Error)
|
||||
require.Len(t, albums, 3)
|
||||
}
|
||||
|
||||
func TestTagErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItemsWithCovers()
|
||||
m.SetTags("artist-1/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
tags.Error = scanner.ErrReadingTags
|
||||
})
|
||||
m.SetTags("artist-1/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
tags.Error = scanner.ErrReadingTags
|
||||
})
|
||||
|
||||
st, err := m.ScanAndCleanErr()
|
||||
errs, ok := err.(interface{ Unwrap() []error })
|
||||
assert.True(t, ok)
|
||||
|
||||
assert.ErrorAs(t, err, &errs)
|
||||
assert.Equal(t, 2, len(errs.Unwrap())) // we have 2 dir errors
|
||||
assert.Equal(t, m.NumTracks()-(3*2), st.SeenTracks()) // we saw all tracks bar 2 album contents
|
||||
assert.Equal(t, m.NumTracks()-(3*2), st.SeenTracksNew()) // we have all tracks bar 2 album contents
|
||||
|
||||
st, err = m.ScanAndCleanErr()
|
||||
errs, ok = err.(interface{ Unwrap() []error })
|
||||
assert.True(t, ok)
|
||||
|
||||
assert.Equal(t, 2, len(errs.Unwrap())) // we have 2 dir errors
|
||||
assert.Equal(t, m.NumTracks()-(3*2), st.SeenTracks()) // we saw all tracks bar 2 album contents
|
||||
assert.Equal(t, 0, st.SeenTracksNew()) // we have no new tracks
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/issues/185#issuecomment-1050092128
|
||||
func TestCompilationAlbumWithoutAlbumArtist(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
const pathArtist = "various-artists"
|
||||
const pathAlbum = "my-compilation"
|
||||
const toAdd = 5
|
||||
|
||||
// add tracks to one folder with random artists and no album artist tag
|
||||
for i := range toAdd {
|
||||
p := fmt.Sprintf("%s/%s/track-%d.flac", pathArtist, pathAlbum, i)
|
||||
m.AddTrack(p)
|
||||
m.SetTags(p, func(tags *mockfs.TagInfo) {
|
||||
// don't set an album artist
|
||||
normtag.Set(tags.Tags, normtag.Title, fmt.Sprintf("track %d", i))
|
||||
normtag.Set(tags.Tags, normtag.Artist, fmt.Sprintf("artist %d", i))
|
||||
normtag.Set(tags.Tags, normtag.Album, pathArtist)
|
||||
})
|
||||
}
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var trackCount int
|
||||
assert.NoError(t, m.DB().Model(&db.Track{}).Count(&trackCount).Error)
|
||||
assert.Equal(t, 5, trackCount)
|
||||
|
||||
var artists []*db.Artist
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
|
||||
assert.Equal(t, 1, len(artists)) // we only have one album artist
|
||||
assert.Equal(t, "artist 0", artists[0].Name) // it came from the first track's fallback to artist tag
|
||||
|
||||
var artistAlbums []*db.Album
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Where("album_artists.artist_id=?", artists[0].ID).Find(&artistAlbums).Error)
|
||||
assert.Equal(t, 1, len(artistAlbums)) // the artist has one album
|
||||
assert.Equal(t, pathAlbum, artistAlbums[0].RightPath)
|
||||
assert.Equal(t, pathArtist+"/", artistAlbums[0].LeftPath)
|
||||
}
|
||||
|
||||
func TestIncrementalScanNoChangeNoUpdatedAt(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
|
||||
m.ScanAndClean()
|
||||
var albumA db.Album
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Order("updated_at DESC").Find(&albumA).Error)
|
||||
|
||||
m.ScanAndClean()
|
||||
var albumB db.Album
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Order("updated_at DESC").Find(&albumB).Error)
|
||||
|
||||
assert.Equal(t, albumB.UpdatedAt, albumA.UpdatedAt)
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/issues/230
|
||||
func TestAlbumAndArtistSameNameWeirdness(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
const name = "same"
|
||||
|
||||
add := func(path string, a ...any) {
|
||||
m.AddTrack(fmt.Sprintf(path, a...))
|
||||
m.SetTags(fmt.Sprintf(path, a...), func(tags *mockfs.TagInfo) {})
|
||||
}
|
||||
|
||||
add("an-artist/%s/track-1.flac", name)
|
||||
add("an-artist/%s/track-2.flac", name)
|
||||
add("%s/an-album/track-1.flac", name)
|
||||
add("%s/an-album/track-2.flac", name)
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var albums []*db.Album
|
||||
assert.NoError(t, m.DB().Find(&albums).Error)
|
||||
assert.Equal(t, len(albums), 5) // root, 2 artists, 2 albums
|
||||
}
|
||||
|
||||
func TestNoOrphanedGenres(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-a;genre-b") })
|
||||
m.SetTags("artist-0/album-0/track-1.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-c;genre-d") })
|
||||
m.SetTags("artist-1/album-2/track-0.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-e;genre-f") })
|
||||
m.SetTags("artist-1/album-2/track-1.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-g;genre-h") })
|
||||
m.ScanAndClean()
|
||||
|
||||
m.RemoveAll("artist-0")
|
||||
m.RemoveAll("artist-1")
|
||||
m.RemoveAll("artist-2")
|
||||
m.ScanAndClean()
|
||||
|
||||
var genreCount int
|
||||
assert.NoError(t, m.DB().Model(&db.Genre{}).Count(&genreCount).Error)
|
||||
assert.Equal(t, 0, genreCount)
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/issues/466
|
||||
func TestNoOrphanedGenresButOnlyDeleteTracks(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { normtag.Set(tags.Tags, normtag.Genre, "genre-a") })
|
||||
m.ScanAndClean()
|
||||
|
||||
trackPaths, err := filepath.Glob(filepath.Join(m.TmpDir(), "*", "*", "*.flac"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
for _, path := range trackPaths {
|
||||
assert.NoError(t, os.Remove(path))
|
||||
}
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var tracks []*db.Track
|
||||
assert.NoError(t, m.DB().Find(&tracks).Error)
|
||||
assert.Len(t, tracks, 0)
|
||||
|
||||
var genres []*db.Genre
|
||||
assert.NoError(t, m.DB().Find(&genres).Error)
|
||||
assert.Len(t, genres, 0)
|
||||
|
||||
var trackGenres []*db.TrackGenre
|
||||
assert.NoError(t, m.DB().Find(&trackGenres).Error)
|
||||
assert.Len(t, trackGenres, 0)
|
||||
|
||||
var albumGenres []*db.AlbumGenre
|
||||
assert.NoError(t, m.DB().Find(&albumGenres).Error)
|
||||
assert.Len(t, albumGenres, 0)
|
||||
}
|
||||
|
||||
func TestMultiArtistSupport(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItemsGlob("artist-0/album-[012]/track-0.*")
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Album, "Mutator")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtists, "Alan Vega", "Liz Lamere")
|
||||
})
|
||||
m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Album, "Dead Man")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtists, "Alan Vega", "Mercury Rev")
|
||||
})
|
||||
m.SetTags("artist-0/album-2/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Album, "Yerself Is Steam")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, "Mercury Rev")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var artists []*db.Artist
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
|
||||
assert.Len(t, artists, 3) // alan, liz, mercury
|
||||
|
||||
var albumArtists []*db.AlbumArtist
|
||||
assert.NoError(t, m.DB().Find(&albumArtists).Error)
|
||||
assert.Len(t, albumArtists, 5)
|
||||
|
||||
type row struct{ Artist, Albums string }
|
||||
state := func() []row {
|
||||
var table []row
|
||||
assert.NoError(t, m.DB().
|
||||
Select("artists.name artist, group_concat(albums.tag_title, ';') albums").
|
||||
Model(db.Artist{}).
|
||||
Joins("JOIN album_artists ON album_artists.artist_id=artists.id").
|
||||
Joins("JOIN albums ON albums.id=album_artists.album_id").
|
||||
Order("artists.name, albums.tag_title").
|
||||
Group("artists.id").
|
||||
Scan(&table).
|
||||
Error)
|
||||
|
||||
return table
|
||||
}
|
||||
|
||||
assert.Equal(t,
|
||||
[]row{
|
||||
{"Alan Vega", "Mutator;Dead Man"},
|
||||
{"Liz Lamere", "Mutator"},
|
||||
{"Mercury Rev", "Dead Man;Yerself Is Steam"},
|
||||
},
|
||||
state())
|
||||
|
||||
m.RemoveAll("artist-0/album-2")
|
||||
m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Album, "Dead Man")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtists, "Alan Vega")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
|
||||
assert.Len(t, artists, 2) // alan, liz
|
||||
|
||||
assert.NoError(t, m.DB().Find(&albumArtists).Error)
|
||||
assert.Len(t, albumArtists, 3)
|
||||
|
||||
assert.Equal(t,
|
||||
[]row{
|
||||
{"Alan Vega", "Mutator;Dead Man"},
|
||||
{"Liz Lamere", "Mutator"},
|
||||
},
|
||||
state())
|
||||
}
|
||||
|
||||
func TestMultiArtistPreload(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItemsGlob("artist-0/album-[012]/track-0.*")
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Album, "Mutator")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtists, "Alan Vega", "Liz Lamere")
|
||||
})
|
||||
m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Album, "Dead Man")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtists, "Alan Vega", "Mercury Rev")
|
||||
})
|
||||
m.SetTags("artist-0/album-2/track-0.flac", func(tags *mockfs.TagInfo) {
|
||||
normtag.Set(tags.Tags, normtag.Album, "Yerself Is Steam")
|
||||
normtag.Set(tags.Tags, normtag.AlbumArtist, "Mercury Rev")
|
||||
})
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var albums []*db.Album
|
||||
assert.NoError(t, m.DB().Preload("Artists").Find(&albums).Error)
|
||||
assert.GreaterOrEqual(t, len(albums), 3)
|
||||
|
||||
for _, album := range albums {
|
||||
switch album.TagTitle {
|
||||
case "Mutator":
|
||||
assert.Len(t, album.Artists, 2)
|
||||
case "Dead Man":
|
||||
assert.Len(t, album.Artists, 2)
|
||||
case "Yerself Is Steam":
|
||||
assert.Len(t, album.Artists, 1)
|
||||
}
|
||||
}
|
||||
|
||||
var artists []*db.Artist
|
||||
assert.NoError(t, m.DB().Preload("Albums").Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
|
||||
assert.Equal(t, 3, len(artists))
|
||||
|
||||
for _, artist := range artists {
|
||||
switch artist.Name {
|
||||
case "Alan Vega":
|
||||
assert.Len(t, artist.Albums, 2)
|
||||
case "Mercury Rev":
|
||||
assert.Len(t, artist.Albums, 2)
|
||||
case "Liz Lamere":
|
||||
assert.Len(t, artist.Albums, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/issues/402
|
||||
func TestRootNoClobberOnError(t *testing.T) {
|
||||
t.Parallel()
|
||||
m := mockfs.New(t)
|
||||
|
||||
m.AddItems()
|
||||
|
||||
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { tags.Error = fmt.Errorf("no") }) // give a track an error
|
||||
m.AddCover("artist-0/album-0/Artwork/cover.png") // and add an extra cover dir
|
||||
|
||||
_, err := m.ScanAndCleanErr()
|
||||
require.Error(t, err)
|
||||
|
||||
var roots []*db.Album
|
||||
require.NoError(t, m.DB().Find(&roots, "parent_id IS NULL").Error)
|
||||
require.Len(t, roots, 1)
|
||||
require.Equal(t, ".", roots[0].RightPath)
|
||||
require.Equal(t, 0, roots[0].ParentID)
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/issues/437
|
||||
func TestPrefixOverlap(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
m := mockfs.NewWithDirs(t, []string{
|
||||
"/music/tagged",
|
||||
"/music/taggedmanual",
|
||||
})
|
||||
|
||||
m.AddItemsPrefix("/music/tagged")
|
||||
m.AddItemsPrefix("/music/taggedmanual")
|
||||
|
||||
m.ScanAndClean()
|
||||
|
||||
var taggedManual int
|
||||
require.NoError(t, m.DB().Model(db.Album{}).Where("root_dir LIKE ?", `%/taggedmanual`).Count(&taggedManual).Error)
|
||||
require.Greater(t, taggedManual, 1)
|
||||
|
||||
var tagged int
|
||||
require.NoError(t, m.DB().Model(db.Album{}).Where("root_dir LIKE ?", `%/tagged`).Count(&tagged).Error)
|
||||
require.Greater(t, tagged, 1)
|
||||
}
|
||||
|
||||
// https://github.com/sentriz/gonic/pull/448
|
||||
func TestParseMultiDoubleDelim(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
setting := scanner.MultiValueSetting{
|
||||
Mode: scanner.Delim,
|
||||
Delim: `/`,
|
||||
}
|
||||
|
||||
values := scanner.ParseMulti(setting, nil, `DON'T//BE//⚜⚜⚜`)
|
||||
require.Len(t, values, 3)
|
||||
require.Equal(t, `DON'T`, values[0])
|
||||
require.Equal(t, `BE`, values[1])
|
||||
require.Equal(t, `⚜⚜⚜`, values[2])
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package scrobble
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
)
|
||||
|
||||
type Track struct {
|
||||
Track string
|
||||
Artist string
|
||||
Album string
|
||||
AlbumArtist string
|
||||
TrackNumber uint
|
||||
Duration time.Duration
|
||||
MusicBrainzID string
|
||||
MusicBrainzReleaseID string
|
||||
}
|
||||
|
||||
type Scrobbler interface {
|
||||
IsUserAuthenticated(user db.User) bool
|
||||
Scrobble(user db.User, track Track, stamp time.Time, submission bool) error
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package adminui
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed components.tmpl pages/*.tmpl
|
||||
var TemplatesFS embed.FS
|
||||
|
||||
//go:generate npx tailwindcss@v3.2.4 --config tailwind.config.js --input style.css --output static/style.css --minify
|
||||
//go:embed static/*
|
||||
var StaticFS embed.FS
|
||||
@@ -1,125 +0,0 @@
|
||||
{{ define "block" }}
|
||||
<div class="border-b-2 border-r-2 border-gray-300/80 bg-gray-50 p-4">
|
||||
<div class="inline-flex items-center gap-x-3">
|
||||
<span class="text-gray-500/80 w-4">{{ component "icon" .Props.Icon }}{{ end }}</span>
|
||||
<span class="text-gray-900 font-bold">{{ .Props.Name }}</span>
|
||||
</div>
|
||||
<hr class="bg-gray-900/30 my-1" />
|
||||
{{ if .Props.Desc }}
|
||||
<div class="font-medium text-gray-500 max-w-[700px]">{{ .Props.Desc }}</div>
|
||||
{{ end }}
|
||||
<div class="mt-3 max-w-[700px] ml-auto space-y-2 text-right">
|
||||
{{ slot }}
|
||||
</div>
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ define "link" }}
|
||||
<a class="text-blue-500" href="{{ .Props.To }}">{{ slot }}<span class="hidden md:inline">…</span></a>
|
||||
{{ end }}
|
||||
|
||||
{{ define "ext_link" }}
|
||||
<a class="text-blue-500" href="{{ .Props.To }}" target="_blank" rel="noopener noreferrer">{{ slot }}</a>
|
||||
{{ end }}
|
||||
|
||||
{{ define "layout_user" }}
|
||||
<div class="px-4 text-gray-500 text-right whitespace-nowrap">
|
||||
welcome {{ .User.Name }}
|
||||
|
|
||||
{{ component "link" (props . "To" (path "/admin/home")) }}home{{ end }}
|
||||
|
|
||||
{{ component "link" (props . "To" (path "/admin/logout")) }}logout{{ end }}
|
||||
</div>
|
||||
{{ slot }}
|
||||
{{ end }}
|
||||
|
||||
{{ define "layout" }}
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>gonic</title>
|
||||
<style>
|
||||
@font-face {
|
||||
font-family: "Inconsolata";
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
src: local(""),
|
||||
url("{{ path "/admin/static/inconsolata-v31-latin-500.woff2" }}") format("woff2"),
|
||||
url("{{ path "/admin/static/inconsolata-v31-latin-500.woff" }}") format("woff");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Inconsolata";
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
src: local(""),
|
||||
url("{{ path "/admin/static/inconsolata-v31-latin-600.woff2" }}") format("woff2"),
|
||||
url("{{ path "/admin/static/inconsolata-v31-latin-600.woff" }}") format("woff");
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="{{ path "/admin/static/style.css" | noCache }}">
|
||||
<link rel="shortcut icon" href="{{ path "/admin/static/favicon.ico" }}" type="image/x-icon">
|
||||
<link rel="icon" href="{{ path "/admin/static/favicon.ico" }}" type="image/x-icon">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<script src="{{ path "/admin/static/main.js" }}" defer></script>
|
||||
</head>
|
||||
<body class="font-mono leading-4 text-base text-gray-800">
|
||||
<div class="container mx-auto min-w-min space-y-5 p-5">
|
||||
<div class="border-b-2 border-gray-300">
|
||||
<a href="{{ path "/admin/home" }}">
|
||||
<img class="mx-auto w-[400px]" src="{{ path "/admin/static/gonic.png" }}">
|
||||
</a>
|
||||
</div>
|
||||
{{ range $flash := .Flashes }}
|
||||
{{ $colour := "bg-green-200" }}
|
||||
{{ if eq $flash.Type "warning" }}{{ $colour = "bg-red-200" }}{{ end }}
|
||||
<div class="p-4 shadow-sm {{ $colour }} inline-flex items-center gap-x-3 w-full">
|
||||
<span class="text-gray-500/80 w-5">{{ component "icon" "circle-info" }}{{ end }}</span>
|
||||
<span>{{ $flash.Message }}</span>
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ slot }}
|
||||
<div class="px-5 text-right whitespace-nowrap">
|
||||
<span class="text-gray-500">v{{ .Version }}</span>
|
||||
senan kelly, 2020
|
||||
<span class="text-gray-500">|</span>
|
||||
{{ component "ext_link" (props . "To" "https://github.com/sentriz/gonic") }}github{{ end }}
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
{{ end }}
|
||||
|
||||
|
||||
{{/* from https://github.com/FortAwesome/Font-Awesome/tree/6.x/svgs/brand */}}
|
||||
{{/* TODO: see if we can dynamically render templates based on a variable instead of this */}}
|
||||
|
||||
{{ define "icon" }}
|
||||
{{ if (eq . "lastfm") }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M225.8 367.1l-18.8-51s-30.5 34-76.2 34c-40.5 0-69.2-35.2-69.2-91.5 0-72.1 36.4-97.9 72.1-97.9 66.5 0 74.8 53.3 100.9 134.9 18.8 56.9 54 102.6 155.4 102.6 72.7 0 122-22.3 122-80.9 0-72.9-62.7-80.6-115-92.1-25.8-5.9-33.4-16.4-33.4-34 0-19.9 15.8-31.7 41.6-31.7 28.2 0 43.4 10.6 45.7 35.8l58.6-7c-4.7-52.8-41.1-74.5-100.9-74.5-52.8 0-104.4 19.9-104.4 83.9 0 39.9 19.4 65.1 68 76.8 44.9 10.6 79.8 13.8 79.8 45.7 0 21.7-21.1 30.5-61 30.5-59.2 0-83.9-31.1-97.9-73.9-32-96.8-43.6-163-161.3-163C45.7 113.8 0 168.3 0 261c0 89.1 45.7 137.2 127.9 137.2 66.2 0 97.9-31.1 97.9-31.1z"/></svg>
|
||||
{{ else if (eq . "brain" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M184 0c30.9 0 56 25.1 56 56V456c0 30.9-25.1 56-56 56c-28.9 0-52.7-21.9-55.7-50.1c-5.2 1.4-10.7 2.1-16.3 2.1c-35.3 0-64-28.7-64-64c0-7.4 1.3-14.6 3.6-21.2C21.4 367.4 0 338.2 0 304c0-31.9 18.7-59.5 45.8-72.3C37.1 220.8 32 207 32 192c0-30.7 21.6-56.3 50.4-62.6C80.8 123.9 80 118 80 112c0-29.9 20.6-55.1 48.3-62.1C131.3 21.9 155.1 0 184 0zM328 0c28.9 0 52.6 21.9 55.7 49.9c27.8 7 48.3 32.1 48.3 62.1c0 6-.8 11.9-2.4 17.4c28.8 6.2 50.4 31.9 50.4 62.6c0 15-5.1 28.8-13.8 39.7C493.3 244.5 512 272.1 512 304c0 34.2-21.4 63.4-51.6 74.8c2.3 6.6 3.6 13.8 3.6 21.2c0 35.3-28.7 64-64 64c-5.6 0-11.1-.7-16.3-2.1c-3 28.2-26.8 50.1-55.7 50.1c-30.9 0-56-25.1-56-56V56c0-30.9 25.1-56 56-56z"/></svg>
|
||||
{{ else if (eq . "chart-pie" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M302 240V16.6c0-9 7-16.6 16-16.6C441.7 0 542 100.3 542 224c0 9-7.6 16-16.6 16H302zM30 272C30 150.7 120.1 50.3 237 34.3c9.2-1.3 17 6.1 17 15.4V288L410.5 444.5c6.7 6.7 6.2 17.7-1.5 23.1C369.8 495.6 321.8 512 270 512C137.5 512 30 404.6 30 272zm526.4 16c9.3 0 16.6 7.8 15.4 17c-7.7 55.9-34.6 105.6-73.9 142.3c-6 5.6-15.4 5.2-21.2-.7L318 288H556.4z"/></svg>
|
||||
{{ else if (eq . "brain" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M184 0c30.9 0 56 25.1 56 56V456c0 30.9-25.1 56-56 56c-28.9 0-52.7-21.9-55.7-50.1c-5.2 1.4-10.7 2.1-16.3 2.1c-35.3 0-64-28.7-64-64c0-7.4 1.3-14.6 3.6-21.2C21.4 367.4 0 338.2 0 304c0-31.9 18.7-59.5 45.8-72.3C37.1 220.8 32 207 32 192c0-30.7 21.6-56.3 50.4-62.6C80.8 123.9 80 118 80 112c0-29.9 20.6-55.1 48.3-62.1C131.3 21.9 155.1 0 184 0zM328 0c28.9 0 52.6 21.9 55.7 49.9c27.8 7 48.3 32.1 48.3 62.1c0 6-.8 11.9-2.4 17.4c28.8 6.2 50.4 31.9 50.4 62.6c0 15-5.1 28.8-13.8 39.7C493.3 244.5 512 272.1 512 304c0 34.2-21.4 63.4-51.6 74.8c2.3 6.6 3.6 13.8 3.6 21.2c0 35.3-28.7 64-64 64c-5.6 0-11.1-.7-16.3-2.1c-3 28.2-26.8 50.1-55.7 50.1c-30.9 0-56-25.1-56-56V56c0-30.9 25.1-56 56-56z"/></svg>
|
||||
{{ else if (eq . "users" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M144 0a80 80 0 1 1 0 160A80 80 0 1 1 144 0zM512 0a80 80 0 1 1 0 160A80 80 0 1 1 512 0zM0 298.7C0 239.8 47.8 192 106.7 192h42.7c15.9 0 31 3.5 44.6 9.7c-1.3 7.2-1.9 14.7-1.9 22.3c0 38.2 16.8 72.5 43.3 96c-.2 0-.4 0-.7 0H21.3C9.6 320 0 310.4 0 298.7zM405.3 320c-.2 0-.4 0-.7 0c26.6-23.5 43.3-57.8 43.3-96c0-7.6-.7-15-1.9-22.3c13.6-6.3 28.7-9.7 44.6-9.7h42.7C592.2 192 640 239.8 640 298.7c0 11.8-9.6 21.3-21.3 21.3H405.3zM224 224a96 96 0 1 1 192 0 96 96 0 1 1 -192 0zM128 485.3C128 411.7 187.7 352 261.3 352H378.7C452.3 352 512 411.7 512 485.3c0 14.7-11.9 26.7-26.7 26.7H154.7c-14.7 0-26.7-11.9-26.7-26.7z"/></svg>
|
||||
{{ else if (eq . "user" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M224 256A128 128 0 1 0 224 0a128 128 0 1 0 0 256zm-45.7 48C79.8 304 0 383.8 0 482.3C0 498.7 13.3 512 29.7 512H418.3c16.4 0 29.7-13.3 29.7-29.7C448 383.8 368.2 304 269.7 304H178.3z"/></svg>
|
||||
{{ else if (eq . "folder-tree" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M64 32C64 14.3 49.7 0 32 0S0 14.3 0 32v96V384c0 35.3 28.7 64 64 64H256V384H64V160H256V96H64V32zM288 192c0 17.7 14.3 32 32 32H544c17.7 0 32-14.3 32-32V64c0-17.7-14.3-32-32-32H445.3c-8.5 0-16.6-3.4-22.6-9.4L409.4 9.4c-6-6-14.1-9.4-22.6-9.4H320c-17.7 0-32 14.3-32 32V192zm0 288c0 17.7 14.3 32 32 32H544c17.7 0 32-14.3 32-32V352c0-17.7-14.3-32-32-32H445.3c-8.5 0-16.6-3.4-22.6-9.4l-13.3-13.3c-6-6-14.1-9.4-22.6-9.4H320c-17.7 0-32 14.3-32 32V480z"/></svg>
|
||||
{{ else if (eq . "music" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M499.1 6.3c8.1 6 12.9 15.6 12.9 25.7v72V368c0 44.2-43 80-96 80s-96-35.8-96-80s43-80 96-80c11.2 0 22 1.6 32 4.6V147L192 223.8V432c0 44.2-43 80-96 80s-96-35.8-96-80s43-80 96-80c11.2 0 22 1.6 32 4.6V200 128c0-14.1 9.3-26.6 22.8-30.7l320-96c9.7-2.9 20.2-1.1 28.3 5z"/></svg>
|
||||
{{ else if (eq . "rss" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M0 64C0 46.3 14.3 32 32 32c229.8 0 416 186.2 416 416c0 17.7-14.3 32-32 32s-32-14.3-32-32C384 253.6 226.4 96 32 96C14.3 96 0 81.7 0 64zM0 416a64 64 0 1 1 128 0A64 64 0 1 1 0 416zM32 160c159.1 0 288 128.9 288 288c0 17.7-14.3 32-32 32s-32-14.3-32-32c0-123.7-100.3-224-224-224c-17.7 0-32-14.3-32-32s14.3-32 32-32z"/></svg>
|
||||
{{ else if (eq . "radio" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M494.8 47c12.7-3.7 20-17.1 16.3-29.8S494-2.8 481.2 1L51.7 126.9c-9.4 2.7-17.9 7.3-25.1 13.2C10.5 151.7 0 170.6 0 192v4V304 448c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V192c0-35.3-28.7-64-64-64H218.5L494.8 47zM368 240a80 80 0 1 1 0 160 80 80 0 1 1 0-160zM80 256c0-8.8 7.2-16 16-16h96c8.8 0 16 7.2 16 16s-7.2 16-16 16H96c-8.8 0-16-7.2-16-16zM64 320c0-8.8 7.2-16 16-16H208c8.8 0 16 7.2 16 16s-7.2 16-16 16H80c-8.8 0-16-7.2-16-16zm16 64c0-8.8 7.2-16 16-16h96c8.8 0 16 7.2 16 16s-7.2 16-16 16H96c-8.8 0-16-7.2-16-16z"/></svg>
|
||||
{{ else if (eq . "list" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M40 48C26.7 48 16 58.7 16 72v48c0 13.3 10.7 24 24 24H88c13.3 0 24-10.7 24-24V72c0-13.3-10.7-24-24-24H40zM192 64c-17.7 0-32 14.3-32 32s14.3 32 32 32H480c17.7 0 32-14.3 32-32s-14.3-32-32-32H192zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32H480c17.7 0 32-14.3 32-32s-14.3-32-32-32H192zm0 160c-17.7 0-32 14.3-32 32s14.3 32 32 32H480c17.7 0 32-14.3 32-32s-14.3-32-32-32H192zM16 232v48c0 13.3 10.7 24 24 24H88c13.3 0 24-10.7 24-24V232c0-13.3-10.7-24-24-24H40c-13.3 0-24 10.7-24 24zM40 368c-13.3 0-24 10.7-24 24v48c0 13.3 10.7 24 24 24H88c13.3 0 24-10.7 24-24V392c0-13.3-10.7-24-24-24H40z"/></svg>
|
||||
{{ else if (eq . "circle-info" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>
|
||||
{{ else if (eq . "key" ) }}
|
||||
<svg class="fill-current aspect-square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. --><path d="M336 352c97.2 0 176-78.8 176-176S433.2 0 336 0S160 78.8 160 176c0 18.7 2.9 36.8 8.3 53.7L7 391c-4.5 4.5-7 10.6-7 17v80c0 13.3 10.7 24 24 24h80c13.3 0 24-10.7 24-24V448h40c13.3 0 24-10.7 24-24V384h40c6.4 0 12.5-2.5 17-7l33.3-33.3c16.9 5.4 35 8.3 53.7 8.3zM376 96a40 40 0 1 1 0 80 40 40 0 1 1 0-80z"/></svg>
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
@@ -1,25 +0,0 @@
|
||||
{{ component "layout" . }}
|
||||
{{ component "layout_user" . }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "user"
|
||||
"Name" (printf "changing %s's avatar" .SelectedUser.Name)
|
||||
) }}
|
||||
<div class="flex flex-col gap-2 items-end">
|
||||
{{ if ne (len .SelectedUser.Avatar) 0 }}
|
||||
<img class="h-[8rem] w-[8rem] object-cover" src="data:image/jpg;base64,{{ .SelectedUser.Avatar | base64 }}" />
|
||||
<form class="contents" action="{{ printf "/admin/delete_avatar_do?user=%s" .SelectedUser.Name | path }}" method="post">
|
||||
<input type="submit" value="delete avatar">
|
||||
</form>
|
||||
{{ end }}
|
||||
<form enctype="multipart/form-data" action="{{ printf "/admin/change_avatar_do?user=%s" .SelectedUser.Name | path }}" method="post">
|
||||
<div class="relative pointer-events-auto">
|
||||
<input class="auto-submit absolute opacity-0" name="avatar" type="file" accept="image/jpeg image/png image/gif" />
|
||||
<input type="button" value="choose file">
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
@@ -1,16 +0,0 @@
|
||||
{{ component "layout" . }}
|
||||
{{ component "layout_user" . }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "user"
|
||||
"Name" (printf "changing %s's password" .SelectedUser.Name)
|
||||
) }}
|
||||
<form class="flex flex-col gap-2 items-end" action="{{ printf "/admin/change_password_do?user=%s" .SelectedUser.Name | path }}" method="post">
|
||||
<input type="password" id="password_one" name="password_one" placeholder="new password">
|
||||
<input type="password" id="password_two" name="password_two" placeholder="verify new password">
|
||||
<input type="submit" value="change">
|
||||
</form>
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
@@ -1,15 +0,0 @@
|
||||
{{ component "layout" . }}
|
||||
{{ component "layout_user" . }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "user"
|
||||
"Name" (printf "changing %s's username" .SelectedUser.Name)
|
||||
) }}
|
||||
<form class="flex flex-col md:flex-row gap-2 items-end" action="{{ printf "/admin/change_username_do?user=%s" .SelectedUser.Name | path }}" method="post">
|
||||
<input type="text" id="username" name="username" placeholder="new username">
|
||||
<input type="submit" value="change">
|
||||
</form>
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
@@ -1,17 +0,0 @@
|
||||
{{ component "layout" . }}
|
||||
{{ component "layout_user" . }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "user"
|
||||
"Name" "creating new user"
|
||||
) }}
|
||||
<form class="flex flex-col gap-2 items-end" action="{{ path "/admin/create_user_do" }}" method="post">
|
||||
<input type="text" id="username" name="username" placeholder="username">
|
||||
<input type="password" id="password_one" name="password_one" placeholder="password">
|
||||
<input type="password" id="password_two" name="password_two" placeholder="verify password">
|
||||
<input type="submit" value="create">
|
||||
</form>
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
@@ -1,15 +0,0 @@
|
||||
{{ component "layout" . }}
|
||||
{{ component "layout_user" . }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "user"
|
||||
"Name" (printf "deleting user %s" .SelectedUser.Name)
|
||||
"Desc" "are you sure? this will also delete their plays, playlists, starred, rated, etc."
|
||||
) }}
|
||||
<form class="inline-block" action="{{ printf "/admin/delete_user_do?user=%s" .SelectedUser.Name | path }}" method="post">
|
||||
<input type="submit" value="yes">
|
||||
</form>
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
@@ -1,217 +0,0 @@
|
||||
{{ component "layout" . }}
|
||||
{{ component "layout_user" . }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "chart-pie"
|
||||
"Name" "stats"
|
||||
"Desc" "total items found in all watched folders"
|
||||
) }}
|
||||
<div class="grid grid-cols-[auto_min-content] gap-2 gap-x-5 text-right">
|
||||
<div class="text-gray-500">folders</div>
|
||||
<div class="font-bold">{{ .Stats.Folders }}</div>
|
||||
<div class="text-gray-500">albums</div>
|
||||
<div class="font-bold">{{ .Stats.Albums }}</div>
|
||||
<div class="text-gray-500">artists</div>
|
||||
<div class="font-bold">{{ .Stats.Artists }}</div>
|
||||
<div class="text-gray-500">album artists</div>
|
||||
<div class="font-bold">{{ .Stats.AlbumArtists }}</div>
|
||||
<div class="text-gray-500">tracks</div>
|
||||
<div class="font-bold">{{ .Stats.Tracks }}</div>
|
||||
<div class="text-gray-500">internet radio stations</div>
|
||||
<div class="font-bold">{{ .Stats.InternetRadioStations }}</div>
|
||||
<div class="text-gray-500">podcasts</div>
|
||||
<div class="font-bold">{{ .Stats.Podcasts }}</div>
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "users"
|
||||
"Name" "user management"
|
||||
"Desc" "manage user accounts for subsonic api and web interface access"
|
||||
) }}
|
||||
<div class="grid grid-cols-[repeat(3,auto)_max-content] md:grid-cols-[auto_repeat(5,min-content)] gap-2 gap-x-5 items-center text-right">
|
||||
{{ range $user := .AllUsers }}
|
||||
<div class="col-span-3 md:col-auto ellipsis">{{ $user.Name }}</div>
|
||||
<div class="text-gray-500 whitespace-nowrap">{{ $user.CreatedAt | date }}</div>
|
||||
{{ component "link" (props . "To" (printf "/admin/change_username?user=%s" $user.Name | path)) }}username{{ end }}
|
||||
{{ component "link" (props . "To" (printf "/admin/change_password?user=%s" $user.Name | path)) }}password{{ end }}
|
||||
{{ component "link" (props . "To" (printf "/admin/change_avatar?user=%s" $user.Name | path)) }}avatar{{ end }}
|
||||
{{ if $user.IsAdmin }}
|
||||
<div class="text-gray-500">delete<span class="hidden md:inline">…</span></div>
|
||||
{{ else }}
|
||||
{{ component "link" (props . "To" (printf "/admin/delete_user?user=%s" $user.Name | path)) }}delete{{ end }}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
{{ if .User.IsAdmin }}
|
||||
<div class="col-span-full">{{ component "link" (props . "To" (path "/admin/create_user")) }}create new{{ end }}</div>
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "folder-tree"
|
||||
"Name" "recent folders"
|
||||
) }}
|
||||
<div class="grid grid-cols-[1fr,auto] gap-x-3 gap-y-2 items-center justify-items-end">
|
||||
{{ if eq (len .RecentFolders) 0 }}
|
||||
<div class="col-span-full text-gray-500">no folders yet</div>
|
||||
{{ end }}
|
||||
{{ range $folder := .RecentFolders }}
|
||||
<div class="text-left ellipsis">{{ $folder.RightPath }}</div>
|
||||
{{ if not $folder.CreatedAt.IsZero }}
|
||||
<div class="text-gray-500" title="{{ $folder.CreatedAt }}">{{ $folder.CreatedAt | dateHuman }}</div>
|
||||
{{ else }}
|
||||
<span></span>
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
{{ if and (not .IsScanning) (.User.IsAdmin) }}
|
||||
{{ if not .LastScanTime.IsZero }}
|
||||
<p class="col-span-full text-gray-500" title="{{ .LastScanTime }}">scanned {{ .LastScanTime | dateHuman }}</p>
|
||||
{{ end }}
|
||||
<form class="col-span-full" action="{{ path "/admin/start_scan_inc_do" }}" method="post">
|
||||
<input type="submit" title="start a incremental scan. gonic will only scan files that have changed since the last scan. it is usually quite fast" value="scan (i)">
|
||||
</form>
|
||||
<form class="col-span-full" action="{{ path "/admin/start_scan_full_do" }}" method="post">
|
||||
<input type="submit" title="start a slow scan. gonic will not check the timestamps of changed files. you generally shouldn't need this" value="scan slow (i)">
|
||||
</form>
|
||||
{{ end }}
|
||||
{{ if .IsScanning }}<p class="text-green-500 col-span-full">scan in progress...</p>{{ end }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "music"
|
||||
"Name" "transcoding device profiles"
|
||||
"Desc" "you can find your device's client name in the gonic logs. some common client names are <span class='italic text-gray-800'>DSub</span>, <span class='italic text-gray-800'>Jamstash</span>, <span class=\"italic text-gray-800\">Soundwaves</span>, or use <span class=\"italic text-gray-800\">*</span> as fallback rule for any client. see the \"transcoding profiles\" page on the wiki for more info"
|
||||
) }}
|
||||
<div class="grid grid-cols-[1fr_1fr_auto] gap-2 items-center justify-items-end">
|
||||
{{ range $pref := .TranscodePreferences }}
|
||||
{{ $formSuffix := kebabcase $pref.Client }}
|
||||
<div class="ellipsis">{{ $pref.Client }}</div>
|
||||
<div>{{ $pref.Profile }}</div>
|
||||
<form class="contents" action="{{ printf "/admin/delete_transcode_pref_do?client=%s" $pref.Client | path }}" method="post">
|
||||
<input type="submit" value="delete">
|
||||
</form>
|
||||
{{ end }}
|
||||
<form class="contents" action="{{ path "/admin/create_transcode_pref_do" }}" method="post">
|
||||
<input type="text" name="client" placeholder="client name">
|
||||
<select name="profile">
|
||||
{{ range $profile := .TranscodeProfiles }}<option value="{{ $profile }}">{{ $profile }}</option>{{ end }}
|
||||
</select>
|
||||
<input type="submit" value="save">
|
||||
</form>
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "lastfm"
|
||||
"Name" "last.fm"
|
||||
"Desc" "scrobble to last.fm on a per user basis. adding an api key will also help gonic get rich artist info and images for subsonic clients"
|
||||
) }}
|
||||
<div class="flex flex-col gap-2 items-end">
|
||||
{{ if .CurrentLastFMAPIKey }}
|
||||
{{ if .User.LastFMSession }}
|
||||
<p class="text-gray-500">current status <span class="font-bold text-green-500">linked</span></p>
|
||||
<form class="contents" action="{{ path "/admin/unlink_lastfm_do" }}" method="post">
|
||||
<input type="submit" value="unlink">
|
||||
</form>
|
||||
{{ else }}
|
||||
<p class="text-gray-500">current status <span class="font-bold text-red-400">unlinked</span></p>
|
||||
{{ $cbPath := path "/admin/link_lastfm_do" }}
|
||||
{{ $cbURL := printf "%s%s" .RequestRoot $cbPath }}
|
||||
<div>{{ component "link" (props . "To" (printf "https://www.last.fm/api/auth/?api_key=%s&cb=%s" .CurrentLastFMAPIKey $cbURL)) }}link{{ end }}</div>
|
||||
{{ end }}
|
||||
{{ else }}
|
||||
<p class="font-bold">api key not set</p>
|
||||
{{ if not .User.IsAdmin }}
|
||||
<p class="text-gray-500">please ask your admin to set it</p>
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
{{ if .User.IsAdmin }}
|
||||
<p>{{ component "link" (props . "To" (path "/admin/update_lastfm_api_key" )) }}update api key{{ end }}</p>
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ component "block" (props .
|
||||
"Icon" "brain"
|
||||
"Name" "listenbrainz"
|
||||
"Desc" "scrobble to listenbrainz and compatible sites on a per user basis"
|
||||
) }}
|
||||
<div class="grid grid-cols-[1fr_1fr_auto] gap-2 items-center justify-items-end">
|
||||
{{ if .User.ListenBrainzToken }}
|
||||
<p class="text-gray-500 col-span-full">current status <span class="font-bold text-green-500">linked</span></p>
|
||||
<form class="contents" action="{{ path "/admin/unlink_listenbrainz_do" }}" method="post">
|
||||
<input class="col-span-full" type="submit" value="unlink">
|
||||
</form>
|
||||
{{ else }}
|
||||
<p class="text-gray-500 col-span-full">current status <span class="font-bold text-red-400">unlinked</span></p>
|
||||
<form class="contents" action="{{ path "/admin/link_listenbrainz_do" }}" method="post">
|
||||
<input type="text" name="url" placeholder="server addr" value="{{ default .DefaultListenBrainzURL .User.ListenBrainzURL }}">
|
||||
<input type="text" name="token" placeholder="api key" value="{{ .User.ListenBrainzToken }}">
|
||||
<input type="submit" value="update">
|
||||
</form>
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ if .User.IsAdmin }}
|
||||
{{ component "block" (props .
|
||||
"Icon" "rss"
|
||||
"Name" "podcasts"
|
||||
"Desc" "you can add podcasts rss feeds here"
|
||||
) }}
|
||||
<div class="grid grid-cols-[auto_auto_min-content] md:grid-cols-[5fr_3fr_auto_auto] gap-2 items-center justify-items-end">
|
||||
{{ range $pref := .Podcasts }}
|
||||
<div class="ellipsis">{{ $pref.Title }}</div>
|
||||
<form class="contents" action="{{ printf "/admin/update_podcast_do?id=%d" $pref.ID | path }}" method="post">
|
||||
<select class="auto-submit" name="setting">
|
||||
<option value="latest" {{ if eq $pref.AutoDownload "latest" }}selected="selected"{{ end }}>download latest</option>
|
||||
<option value="none" {{ if eq (default "none" $pref.AutoDownload) "none" }}selected="selected"{{ end }}>no auto download</option>
|
||||
</select>
|
||||
</form>
|
||||
<form class="hidden md:contents" action="{{ printf "/admin/download_podcast_do?id=%d" $pref.ID | path }}" method="post">
|
||||
<input type="submit" value="download all">
|
||||
</form>
|
||||
<form class="contents" action="{{ printf "/admin/delete_podcast_do?id=%d" $pref.ID | path }}" method="post">
|
||||
<input type="submit" value="delete">
|
||||
</form>
|
||||
{{ end }}
|
||||
<form class="contents" action="{{ path "/admin/add_podcast_do" }}" method="post">
|
||||
<input class="md:col-start-2 col-span-2" type="text" name="feed" placeholder="rss feed url">
|
||||
<input type="submit" value="add new">
|
||||
</form>
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{ if .User.IsAdmin }}
|
||||
{{ component "block" (props .
|
||||
"Icon" "rss"
|
||||
"Name" "internet radio stations"
|
||||
"Desc" "you can add and update internet radio stations here"
|
||||
) }}
|
||||
<div class="grid grid-cols-[1fr_1fr_min-content_min-content] md:grid-cols-[1fr_1fr_1fr_auto_auto] gap-2 items-center justify-items-end">
|
||||
{{ range $pref := .InternetRadioStations }}
|
||||
<form class="contents" action="{{ printf "/admin/update_internet_radio_station_do?id=%d" $pref.ID | path }}" method="post">
|
||||
<input class="col-span-full md:col-auto" type="text" name="name" value={{ $pref.Name }}>
|
||||
<input type="text" name="streamURL" placeholder="stream url" value={{ $pref.StreamURL }}>
|
||||
<input type="text" name="homepageURL" placeholder="homepage url" value={{ $pref.HomepageURL }}>
|
||||
<input type="submit" value="update">
|
||||
</form>
|
||||
<form class="contents" action="{{ printf "/admin/delete_internet_radio_station_do?id=%d" $pref.ID | path }}" method="post">
|
||||
<input type="submit" value="delete">
|
||||
</form>
|
||||
{{ end }}
|
||||
<form class="contents" action="{{ path "/admin/add_internet_radio_station_do" }}" method="post">
|
||||
<input type="text" name="name" placeholder="name">
|
||||
<input type="text" name="streamURL" placeholder="stream url">
|
||||
<input type="text" name="homepageURL" placeholder="homepage url">
|
||||
<input class="col-auto md:col-span-2" type="submit" value="add">
|
||||
</form>
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ end }}
|
||||