diff --git a/Cargo.lock b/Cargo.lock index bd9a499..e960b85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -664,6 +664,17 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +[[package]] +name = "futures-macro" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "futures-sink" version = "0.3.30" @@ -685,6 +696,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -1467,6 +1479,7 @@ version = "0.2.6" dependencies = [ "chrono", "config", + "futures-util", "log", "md5", "rand", @@ -1477,6 +1490,7 @@ dependencies = [ "sqlx", "thiserror 2.0.17", "tokio", + "tokio-util", "uuid", ] @@ -1658,10 +1672,12 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", + "tokio-util", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", "winreg", ] @@ -2847,6 +2863,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e072d4e72f700fb3443d8fe94a39315df013eef1104903cdb0a2abd322bbecd" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.69" diff --git a/Cargo.toml b/Cargo.toml index d7bc8d9..6bf666a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ description = "Subsonic playlist daemon" rocket = { version = "0.5.0", features = ["json"] } tokio = { version = "1.0", features = ["full"] } sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid", "chrono"] } -reqwest = { version = "0.11", features = ["json"] } +reqwest = { version = "0.11", features = ["json", "stream"] } serde = { version = "1.0", features = ["derive"] } uuid = { version = "1.7", features = ["v4", "serde"] } md5 = "0.8.0" @@ -20,6 +20,8 @@ log = "0.4.21" chrono = { version = "0.4.38", features = ["serde"] } rand = "0.8" serde_json = "1.0" +futures-util = "0.3" +tokio-util = { version = "0.7", features = ["io"] } [package.metadata.deb] depends = "$auto" diff --git a/README.md b/README.md index a8f4b83..181afce 100644 --- a/README.md +++ b/README.md @@ -109,5 +109,50 @@ VALUES (gen_random_uuid(), 'jellywx', 3, 50); | `familiar_ratio` | 0.3 | Share of each mix taken from recently played tracks | | `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres | | `refresh_hours` | 24 | How often to rebuild the mixes | +| `discovery_count`| 15 | New songs (not in your library) to suggest per mix | Set `last_run` to `NULL` to rebuild a rule's mixes on the next daemon tick. + +### Discover UI + +`discover/` is a React app for listening to the genre mixes, alongside new songs that aren't in +your library yet. + +Each time the mixes are rebuilt, playlistd also looks for new songs for each mix: + +* your Listenbrainz recommendations, keeping only recordings you've never listened to, and +* if `listenbrainz.token` is set, an LB Radio playlist for each mix's top genres. + +Every candidate's MusicBrainz genres are compared with each mix's, and it's suggested in the mix +it fits best (if it fits well enough), skipping songs already in your library. + +In the UI, songs from your library stream from Subsonic. New songs are found on YouTube with +[yt-dlp](https://github.com/yt-dlp/yt-dlp) and streamed through playlistd, so yt-dlp needs to be +installed on the server (keep it up to date: YouTube changes often break older versions). You can +like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again. + +Build it with: + +```sh +cd discover +npm install +npm run build +``` + +and set `discover.ui` (or `DISCOVER_UI`) to the `discover/dist` directory to serve it from +playlistd at `/`. For development, `npm run dev` serves the UI with hot reload and forwards API +requests to playlistd on `localhost:8000` (or `PLAYLISTD_URL`). + +The UI uses these endpoints under `/api/discover`: + +| Endpoint | Purpose | +|--------------------------------|------------------------------------------------------| +| `GET /rules` | Cluster mix rules | +| `GET /rules//mixes` | A rule's mixes | +| `GET /mixes/` | A mix's library songs and new song suggestions | +| `GET /rules//liked` | Liked suggestions | +| `PUT /suggestions/` | Set a suggestion's status (`new`, `liked`, `dismissed`) | +| `POST /rules//rebuild` | Rebuild a rule's mixes on the next daemon tick | +| `GET /stream/` | Stream a library song from Subsonic | +| `GET /cover/` | Library cover art from Subsonic | +| `GET /youtube/` | Stream a suggested song from YouTube | diff --git a/discover/.gitignore b/discover/.gitignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/discover/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/discover/index.html b/discover/index.html new file mode 100644 index 0000000..da6a5eb --- /dev/null +++ b/discover/index.html @@ -0,0 +1,13 @@ + + + + + + + Discover + + +
+ + + diff --git a/discover/package-lock.json b/discover/package-lock.json new file mode 100644 index 0000000..47a7bc5 --- /dev/null +++ b/discover/package-lock.json @@ -0,0 +1,1757 @@ +{ + "name": "playlistd-discover", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "playlistd-discover", + "version": "0.1.0", + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "@types/react": "18.3.12", + "@types/react-dom": "18.3.1", + "@vitejs/plugin-react": "4.3.3", + "typescript": "5.6.3", + "vite": "5.4.10" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.14.tgz", + "integrity": "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.14", + "@babel/types": "^7.29.14", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.14.tgz", + "integrity": "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.14.tgz", + "integrity": "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.14", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.14", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.3.tgz", + "integrity": "sha512-mqfypgH/liYjaSCoPI4erckUcROgZtmFUUmyOJ05oyayi/tVqOEYAzWP7ufqCoCT3xB31Fw4XIVO/jX42hYvKA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.3.tgz", + "integrity": "sha512-5tY+GC/1gpt79cKS2DQzu6iD824j6BmI4q5Zb6qftZ4kWqIQmvR3DD4eJ2Gclu6/nVMYDk2IVpqxypWOiAuWJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.3.tgz", + "integrity": "sha512-nDBcQ/o3PMmGxmAzGBJFn+n1rb83Va9WSdFIq1AHmlEF3tuibVsyJ3kG5x13r7VIy6WI8SvzCdHVNSlSDIdj8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.3.tgz", + "integrity": "sha512-dra5zl0QWKkIkaMgNDNPC19gkMlPAfAf41yWlkGztXMIvUQrX9XWZFQRw7abhH3nks+XZGQpybINAxT2pKdFew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.3.tgz", + "integrity": "sha512-xo5xeo/AjEB/ArzQjGn0JRDZuybZicQ5O3VPfko6ocH1li/qNrN4p5+R/WgjavzRz6UwAOaqsau7VvRQA6i6AA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.3.tgz", + "integrity": "sha512-zdckkcxHDEEKyDbC1t21DeaaiKGymxbkBU9c3zyfaaz+8N96ItJw4nmzHhZF+Mukgt906fnf2tsc90pVyStuHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.3.tgz", + "integrity": "sha512-9oXqI7g/ycEz7TyicdGBC4sL6PfWMXAx8u15f/nd7lYkCLJd8U8VdBfbpc4SSnRBU/e7aPALve3mhzasGDeCYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.3.tgz", + "integrity": "sha512-hbgT4NlaOELE3D5UUzSqF+OFgwz4Scvo2SQD9nZJUFjdIsg9Kg3FabQauUxkHKY9N5yjNXfXRRmiKNN4JpLmFA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.3.tgz", + "integrity": "sha512-yECcXZ/Bl+JVRhLFgld42rYrXgPdE0LtySGAmmmH6OtkaJM17A4cWG/eCzDymMVb52/jZjW0R54YrTHj4xXlSA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.3.tgz", + "integrity": "sha512-q4Q4/B7wyqM+TFqY5tJYQlaz5+ksGopcRmMeMdu4q6eaPK7N1PymTjIaH5LL32mMJBqIzpRof7BhlYLim5JgNQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.3.tgz", + "integrity": "sha512-Ich3TGl/7GqhQ6G6jVPzgGQGJjd3E5hECxSVanPYchy6Vwcq+WI8wG/gmEMilHNy+ZYCR6U8EN50EejG3TaIgw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.3.tgz", + "integrity": "sha512-URBmOhwv4Y0Hi5Hhxc3cmqZLtQlx55DOs5PUhhITDC3zu0qwAfhcNAFAIwAhOUdA6NFVEck07CNZX6cBEs1vTg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.3.tgz", + "integrity": "sha512-PTdJXuZplRyaE3ECArlbZubI2LlUHWm0oCipCexnE/8LM+L7qIqUiNbU0piBxt46EB5zxXX+cpmDvHX4Z3WwcQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.3.tgz", + "integrity": "sha512-IlSQPDExSm9YdtrWeZIHj87GPXI9lYygRvHVwQ1o9t91JHIiB2CihrvNIASpc/zI28atqm04jS3proaQuaJMww==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.3.tgz", + "integrity": "sha512-O2ssyDcBTZkH5v2P/9ZaXJreL0hCKvUA5UwuHn0jCKeMLKi4GhspZJ1I5FT5QsHtJ/dPx4pup7pg/Lw0emeY0Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.3.tgz", + "integrity": "sha512-fesqagxcnc87lH2+aBWne/tFCmQVIGH+YezjY1wQwbUODuTBBlhHoyxju6umwn8LnjHVanjpoeaQdLsXP8JQSQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.3.tgz", + "integrity": "sha512-WAjFDtLW3HjJ2RAytKoWdFwlK/hW8rJHrjhRZFw14nR+c9JN//WIlSBkyXUjEYCNOFs2sGLNutOEPQG4iVYHgA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.3.tgz", + "integrity": "sha512-+fZiTeHV/1fy/14dRqE4thjYwUOABL6qQjxElOEQg2oHLkCamO8dxhHphVgD4+pFxtVEUIWxsGVduPtwnAlvbg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.3.tgz", + "integrity": "sha512-pfn4Zd9Ic3lEaSwW3GsQhTIDd7929C+eiEkOutsSCT2IHD6rDLblwmMQkgeGOso0oDo9Jk/ERtFdtFr9ElLs+g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.3.tgz", + "integrity": "sha512-eUXzaeNQbKXKNqseL3g/usUqOPmRu+DbQsvwr9MXMdV+VQFUNb9bcWSNAAs/TRV95PCbFK46kLzHEOhFSzujsg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.3.tgz", + "integrity": "sha512-OiUclE7QDU4H/hr3ACRHhVGKWl+gNx+6Emignfq0hmNmzzTkZnT79wzB9NXKd0QH16S4t/wVqlAFBfC17nkZ5A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.3.tgz", + "integrity": "sha512-s6EclDWmk6zvIfk1yixgYthk7xHNx0xu5cEF5RDpS4IHNTpfswRX6xOXVG5cHF5xWn0B6EpDGARhPQ520KTlsA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.3.tgz", + "integrity": "sha512-G2xnmxGnU8XHLwtjnnXNRcLrub+Af3nm9VQ1QzL2aEiAL7woBdRgTCZBslJl8umA+YMqdEFpUh9kJB/Vyzk2wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.3.tgz", + "integrity": "sha512-Y/4tApNVrMUYWbAHsyRWJgwuuJOfhTNhA2B04Xpa6+G9btkPZ9kU3XagUKzPTwF3hg36NpQk748JsnoTVho67Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.3.tgz", + "integrity": "sha512-i2vH/OA5BcW+TdNg12ZTRC4rn+vILaPMP9CvHqnv+QEpMjBHGGNLo4k4EnEqzjYvTD6x1Xark9WhsQbH4bTzUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.3.tgz", + "integrity": "sha512-ADb1Uz2MNM0sxVpAlMNdQG16Hw4sgW1aqVL7NeqBMpcZeiHb192d7W6shZdMQs33D+w9ihDYBBPsYqqc4MlD8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.9.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.9.0.tgz", + "integrity": "sha512-vuyHg81vvWA1Z1ELfvLko2c8f34gyA0zaic0+Rllc5lbCnbSyuvb2Oxpm6TAUAC/2xZN3QGqxBNggD1nNR2AfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.8" + } + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.12", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.12.tgz", + "integrity": "sha512-D2wOSq/d6Agt28q7rSI3jhU7G6aiuzljDGZ2hTZHIkrTLUI+AF3WMeKkEZ9nN2fkBAlcktT6vcZjDFiIhMYEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-qW1Mfv8taImTthu4KoXgDfLuk4bydU6Q/TkADnDWWHwi4NX4BR+LWfTp2sVmTqRrsHvyDDTelgelxJ+SsejKKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.3.tgz", + "integrity": "sha512-NooDe9GpHGqNns1i8XDERg0Vsg5SSYRhRxxyTGogUdkdNt47jal+fbuYi+Yfq6pzRCKXyoPcWisfxE6RIM3GKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.25.2", + "@babel/plugin-transform-react-jsx-self": "^7.24.7", + "@babel/plugin-transform-react-jsx-source": "^7.24.7", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.14.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.37", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.37.tgz", + "integrity": "sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.485", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.485.tgz", + "integrity": "sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.64", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.64.tgz", + "integrity": "sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", + "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.3.tgz", + "integrity": "sha512-wd2gavj7CEQv52rdcVqfUupO/KPIKcoJKxyFWl4cOqYZGMQEOSijJRkliz0dRa7gpkj/h4TRqyWa+dJJi6T0OA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.3", + "@rollup/rollup-android-arm64": "4.68.3", + "@rollup/rollup-android-x64": "4.68.3", + "@rollup/rollup-darwin-arm64": "4.68.3", + "@rollup/rollup-darwin-x64": "4.68.3", + "@rollup/rollup-freebsd-arm64": "4.68.3", + "@rollup/rollup-freebsd-x64": "4.68.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.3", + "@rollup/rollup-linux-arm-musleabihf": "4.68.3", + "@rollup/rollup-linux-arm64-gnu": "4.68.3", + "@rollup/rollup-linux-arm64-musl": "4.68.3", + "@rollup/rollup-linux-loong64-gnu": "4.68.3", + "@rollup/rollup-linux-loong64-musl": "4.68.3", + "@rollup/rollup-linux-ppc64-gnu": "4.68.3", + "@rollup/rollup-linux-ppc64-musl": "4.68.3", + "@rollup/rollup-linux-riscv64-gnu": "4.68.3", + "@rollup/rollup-linux-riscv64-musl": "4.68.3", + "@rollup/rollup-linux-s390x-gnu": "4.68.3", + "@rollup/rollup-linux-x64-gnu": "4.68.3", + "@rollup/rollup-linux-x64-musl": "4.68.3", + "@rollup/rollup-openbsd-x64": "4.68.3", + "@rollup/rollup-openharmony-arm64": "4.68.3", + "@rollup/rollup-win32-arm64-msvc": "4.68.3", + "@rollup/rollup-win32-ia32-msvc": "4.68.3", + "@rollup/rollup-win32-x64-gnu": "4.68.3", + "@rollup/rollup-win32-x64-msvc": "4.68.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/typescript": { + "version": "5.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", + "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "5.4.10", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.10.tgz", + "integrity": "sha512-1hvaPshuPUtxeQ0hsVH3Mud0ZanOLwVTneA1EgbAM5LhaZEqyPWGRQ7BtaMvUrTDeEaC8pxtj6a6jku3x4z6SQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/discover/package.json b/discover/package.json new file mode 100644 index 0000000..960286c --- /dev/null +++ b/discover/package.json @@ -0,0 +1,23 @@ +{ + "name": "playlistd-discover", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "@types/react": "18.3.12", + "@types/react-dom": "18.3.1", + "@vitejs/plugin-react": "4.3.3", + "typescript": "5.6.3", + "vite": "5.4.10" + } +} diff --git a/discover/src/App.tsx b/discover/src/App.tsx new file mode 100644 index 0000000..5a4e8d7 --- /dev/null +++ b/discover/src/App.tsx @@ -0,0 +1,230 @@ +import { useCallback, useEffect, useState } from "react"; +import { api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api"; +import { usePlayer } from "./usePlayer"; +import { MixView, hue } from "./MixView"; +import { LikedView } from "./LikedView"; +import { PlayerBar } from "./PlayerBar"; +import * as Icon from "./icons"; + +type Route = { view: "mix"; id?: string } | { view: "liked" }; + +function parseHash(): Route { + const [, view, id] = window.location.hash.split("/"); + return view === "liked" ? { view: "liked" } : { view: "mix", id: id || undefined }; +} + +type Toast = { message: string; undo?: () => void }; + +function storedRule() { + try { + return localStorage.getItem("discover.rule"); + } catch { + return null; + } +} + +export function App() { + const [rules, setRules] = useState(null); + const [ruleId, setRuleId] = useState(storedRule); + const [mixes, setMixes] = useState(null); + const [detail, setDetail] = useState(null); + const [liked, setLiked] = useState([]); + const [route, setRoute] = useState(parseHash); + const [error, setError] = useState(null); + const [toast, setToast] = useState(null); + + const player = usePlayer((item) => setToast({ message: `Couldn't play “${item.title}”` })); + const rule = rules?.find((r) => r.id === ruleId) ?? rules?.[0]; + + useEffect(() => { + const onHash = () => setRoute(parseHash()); + window.addEventListener("hashchange", onHash); + return () => window.removeEventListener("hashchange", onHash); + }, []); + + useEffect(() => { + if (!toast) return; + const t = window.setTimeout(() => setToast(null), toast.undo ? 6000 : 3500); + return () => window.clearTimeout(t); + }, [toast]); + + const loadRules = useCallback(() => { + api.rules().then(setRules, (e) => setError(`Couldn't reach playlistd (${e.message})`)); + }, []); + useEffect(loadRules, [loadRules]); + + const loadMixes = useCallback(() => { + if (!rule) return; + api.mixes(rule.id).then(setMixes, (e) => setError(e.message)); + api.liked(rule.id).then(setLiked, () => undefined); + }, [rule?.id]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(loadMixes, [loadMixes]); + + // mixes are built by the daemon; check back while they're pending + const pending = !!rule && (!rule.last_run || mixes?.length === 0); + useEffect(() => { + if (!pending) return; + const t = window.setInterval(() => { + loadRules(); + loadMixes(); + }, 10000); + return () => window.clearInterval(t); + }, [pending, loadRules, loadMixes]); + + const mixId = route.view === "mix" ? route.id ?? mixes?.[0]?.id : undefined; + const loadDetail = useCallback( + (quiet = false) => { + if (!mixId) return; + if (!quiet) setDetail((d) => (d?.id === mixId ? d : null)); + api.mix(mixId).then(setDetail, (e) => !quiet && setError(`Couldn't load mix (${e.message})`)); + }, + [mixId], + ); + useEffect(() => loadDetail(), [loadDetail]); + + // pick up YouTube links once a new song has been found and starts playing + useEffect(() => { + if (player.status === "playing" && player.current?.source === "youtube") { + loadDetail(true); + if (rule) api.liked(rule.id).then(setLiked, () => undefined); + } + }, [player.status, player.current?.key]); // eslint-disable-line react-hooks/exhaustive-deps + + const updateLocal = (id: string, status: SuggestionStatus, previous?: Suggestion) => { + setDetail((d) => { + if (!d) return d; + const suggestions = + status === "dismissed" + ? d.suggestions.filter((s) => s.id !== id) + : d.suggestions.some((s) => s.id === id) + ? d.suggestions.map((s) => (s.id === id ? { ...s, status } : s)) + : previous && previous.mix_id === d.id + ? [...d.suggestions, { ...previous, status }].sort((a, b) => b.score - a.score) + : d.suggestions; + return { ...d, suggestions }; + }); + setLiked((l) => { + const without = l.filter((s) => s.id !== id); + const item = previous ?? l.find((s) => s.id === id); + return status === "liked" && item ? [{ ...item, status }, ...without] : without; + }); + }; + + const onStatus = (s: Suggestion, status: SuggestionStatus) => { + updateLocal(s.id, status, s); + api.setStatus(s.id, status).then( + () => { + loadMixes(); + if (status === "dismissed") { + setToast({ + message: `Hid “${s.title}”`, + undo: () => { + updateLocal(s.id, s.status, s); + api.setStatus(s.id, s.status).then(loadMixes); + setToast(null); + }, + }); + } + }, + () => { + updateLocal(s.id, s.status, s); + setToast({ message: "Couldn't save that, try again" }); + }, + ); + }; + + const rebuild = () => { + if (!rule) return; + api.rebuild(rule.id).then(() => { + setToast({ message: "Rebuilding mixes. This takes a minute or two." }); + loadRules(); + }); + }; + + return ( +
+ + +
+ {error &&
{error}
} + {rules && rules.length === 0 && ( +
+

No mix rules yet

+

Create one, and playlistd will cluster your listens into genre mixes:

+
{`curl -X POST /api/playlist/mix -H 'Content-Type: application/json' \\\n  -d '{"tracking_user": "your-listenbrainz-name"}'`}
+
+ )} + {pending && mixes?.length === 0 && ( +
Building mixes from your recent listens…
+ )} + {route.view === "liked" ? ( + + ) : detail ? ( + + ) : ( + mixId &&
Loading…
+ )} +
+ + + + {toast && ( +
+ {toast.message} + {toast.undo && } +
+ )} +
+ ); +} diff --git a/discover/src/LikedView.tsx b/discover/src/LikedView.tsx new file mode 100644 index 0000000..41e0b71 --- /dev/null +++ b/discover/src/LikedView.tsx @@ -0,0 +1,47 @@ +import { useMemo } from "react"; +import { Suggestion, SuggestionStatus } from "./api"; +import { fromSuggestion } from "./queue"; +import { Player } from "./usePlayer"; +import { TrackRow } from "./TrackRow"; +import { SuggestionActions } from "./MixView"; +import * as Icon from "./icons"; + +type Props = { + liked: Suggestion[]; + player: Player; + onStatus: (s: Suggestion, status: SuggestionStatus) => void; +}; + +export function LikedView({ liked, player, onStatus }: Props) { + const items = useMemo(() => liked.map(fromSuggestion), [liked]); + return ( +
+
+ +
+

Collection

+

Liked new songs

+

Songs you liked that aren't in your library yet: a shopping list.

+
+ +
+
+
+
+ {items.length === 0 ? ( +

Nothing yet. Tap the heart on a new song to keep it here.

+ ) : ( +
    + {liked.map((s, i) => ( + player.playAt(items, i)} + actions={} /> + ))} +
+ )} +
+
+ ); +} diff --git a/discover/src/MixView.tsx b/discover/src/MixView.tsx new file mode 100644 index 0000000..0c50787 --- /dev/null +++ b/discover/src/MixView.tsx @@ -0,0 +1,121 @@ +import { useMemo } from "react"; +import { MixDetail, mixTitle, Suggestion, SuggestionStatus } from "./api"; +import { fromSong, fromSuggestion, interleave, QueueItem } from "./queue"; +import { Player } from "./usePlayer"; +import { TrackRow } from "./TrackRow"; +import * as Icon from "./icons"; + +export function hue(text: string) { + let h = 0; + for (const c of text) h = (h * 31 + c.charCodeAt(0)) % 360; + return h; +} + +export function SuggestionActions({ s, onStatus }: { s: Suggestion; onStatus: (s: Suggestion, status: SuggestionStatus) => void }) { + const liked = s.status === "liked"; + return ( + <> + + {s.youtube_id ? ( + + ) : ( + + )} + {s.status !== "liked" && ( + + )} + + ); +} + +type Props = { + mix: MixDetail; + player: Player; + onStatus: (s: Suggestion, status: SuggestionStatus) => void; +}; + +export function MixView({ mix, player, onStatus }: Props) { + const fresh = useMemo(() => mix.suggestions.map(fromSuggestion), [mix.suggestions]); + const library = useMemo(() => mix.songs.map(fromSong), [mix.songs]); + // clicking a row plays through everything shown, new songs first + const all = useMemo(() => [...fresh, ...library], [fresh, library]); + const title = mixTitle(mix); + const h = hue(mix.tags.join()); + + const play = (items: QueueItem[], at = 0) => items.length && player.playAt(items, at); + const isActive = (item: QueueItem) => player.current?.key === item.key; + + return ( +
+
+ +
+

Mix

+

{title}

+
    + {mix.tags.map((t) =>
  • {t}
  • )} +
+

+ {mix.songs.length} from your library · {mix.suggestions.length} new +

+
+ + +
+
+
+ +
+

New for you

+ {fresh.length === 0 ? ( +

No new songs for this mix yet. They're found when the mixes are rebuilt.

+ ) : ( +
    + {mix.suggestions.map((s, i) => ( + play(all, i)} + meta={{Math.round(s.score * 100)}% match} + actions={} + /> + ))} +
+ )} +
+ +
+

From your library

+
    + {mix.songs.map((song, i) => ( + play(all, fresh.length + i)} + duration={song.duration} + /> + ))} +
+
+
+ ); +} diff --git a/discover/src/PlayerBar.tsx b/discover/src/PlayerBar.tsx new file mode 100644 index 0000000..0be9a1e --- /dev/null +++ b/discover/src/PlayerBar.tsx @@ -0,0 +1,55 @@ +import { Player } from "./usePlayer"; +import { Cover, formatTime } from "./TrackRow"; +import * as Icon from "./icons"; + +export function PlayerBar({ player }: { player: Player }) { + const { current, status, time, duration } = player; + if (!current) return null; + const label = + status === "loading" + ? current.source === "youtube" ? "Finding on YouTube…" : "Loading…" + : status === "error" ? "Couldn't play this one, skipping" : null; + + return ( +
+
+ +
+
{current.title}
+
{current.artist}
+
+ + {current.source === "youtube" ? "YouTube" : "Library"} + +
+
+
+ + + +
+
+ {formatTime(time) || "0:00"} + player.seek(Number(e.target.value))} + aria-label="Seek" + style={{ ["--progress" as string]: `${duration ? (time / duration) * 100 : 0}%` }} + /> + {formatTime(duration)} +
+ {label &&
{label}
} +
+
+ {player.index + 1} / {player.queue.length} +
+
+ ); +} diff --git a/discover/src/TrackRow.tsx b/discover/src/TrackRow.tsx new file mode 100644 index 0000000..5602d2a --- /dev/null +++ b/discover/src/TrackRow.tsx @@ -0,0 +1,56 @@ +import { ReactNode } from "react"; +import { QueueItem } from "./queue"; +import { PlayerStatus } from "./usePlayer"; +import * as Icon from "./icons"; + +export function formatTime(seconds?: number) { + if (!seconds || !Number.isFinite(seconds)) return ""; + const s = Math.floor(seconds); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +} + +export function Cover({ src, label, size = 44 }: { src?: string | null; label: string; size?: number }) { + return ( + + ); +} + +type Props = { + item: QueueItem; + number: number; + active: boolean; + status: PlayerStatus; + onPlay: () => void; + meta?: ReactNode; + actions?: ReactNode; + duration?: number; +}; + +export function TrackRow({ item, number, active, status, onPlay, meta, actions, duration }: Props) { + const loading = active && status === "loading"; + const playing = active && status === "playing"; + return ( +
  • + + +
    +
    {item.title}
    +
    + {item.artist} + {item.album && · {item.album}} +
    +
    + {meta &&
    {meta}
    } +
    {formatTime(duration)}
    + {actions &&
    {actions}
    } +
  • + ); +} diff --git a/discover/src/api.ts b/discover/src/api.ts new file mode 100644 index 0000000..632b95f --- /dev/null +++ b/discover/src/api.ts @@ -0,0 +1,75 @@ +export type Rule = { + id: string; + tracking_user: string; + months: number; + playlist_size: number; + discovery_count: number; + last_run: string | null; +}; + +export type MixSummary = { + id: string; + playlist_id: string; + name: string | null; + tags: string[]; + position: number; + new_count: number; +}; + +export type Song = { + id: string; + title: string; + artist: string; + album: string; + duration?: number; + coverArt?: string; +}; + +export type SuggestionStatus = "new" | "liked" | "dismissed"; + +export type Suggestion = { + id: string; + mix_id: string | null; + recording_mbid: string; + title: string; + artist: string; + release: string | null; + cover_url: string | null; + score: number; + status: SuggestionStatus; + youtube_id: string | null; +}; + +export type MixDetail = MixSummary & { songs: Song[]; suggestions: Suggestion[] }; + +async function request(path: string, init?: RequestInit): Promise { + const response = await fetch(`/api/discover${path}`, init); + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`); + } + return response.json(); +} + +export const api = { + rules: () => request("/rules"), + mixes: (ruleId: string) => request(`/rules/${ruleId}/mixes`), + mix: (mixId: string) => request(`/mixes/${mixId}`), + liked: (ruleId: string) => request(`/rules/${ruleId}/liked`), + setStatus: (id: string, status: SuggestionStatus) => + request(`/suggestions/${id}`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ status }), + }), + rebuild: (ruleId: string) => + fetch(`/api/discover/rules/${ruleId}/rebuild`, { method: "POST" }), +}; + +export const coverUrl = (coverArt: string, size = 120) => + `/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`; +export const streamUrl = (songId: string) => `/api/discover/stream/${encodeURIComponent(songId)}`; +export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${suggestionId}`; + +/** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */ +export const mixTitle = (mix: MixSummary) => + (mix.name ?? mix.tags.join(" / ")).replace(/^mix:\s*/i, ""); diff --git a/discover/src/icons.tsx b/discover/src/icons.tsx new file mode 100644 index 0000000..72ae65e --- /dev/null +++ b/discover/src/icons.tsx @@ -0,0 +1,16 @@ +type P = { size?: number }; +const svg = (path: JSX.Element, size = 18) => ( + +); +export const Play = ({ size }: P) => svg(, size); +export const Pause = ({ size }: P) => svg(<>, size); +export const Next = ({ size }: P) => svg(<>, size); +export const Prev = ({ size }: P) => svg(<>, size); +export const Heart = ({ size, filled }: P & { filled?: boolean }) => svg(, size); +export const Close = ({ size }: P) => svg(, size); +export const External = ({ size }: P) => svg(<>, size); +export const Refresh = ({ size }: P) => svg(<>, size); +export const Sparkle = ({ size }: P) => svg(, size); +export const Library = ({ size }: P) => svg(<>, size); +export const Shuffle = ({ size }: P) => svg(<>, size); diff --git a/discover/src/main.tsx b/discover/src/main.tsx new file mode 100644 index 0000000..71c1087 --- /dev/null +++ b/discover/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App"; +import "./styles.css"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/discover/src/queue.ts b/discover/src/queue.ts new file mode 100644 index 0000000..335abe6 --- /dev/null +++ b/discover/src/queue.ts @@ -0,0 +1,47 @@ +import { coverUrl, Song, streamUrl, Suggestion, youtubeUrl } from "./api"; + +export type QueueItem = { + key: string; + source: "library" | "youtube"; + src: string; + title: string; + artist: string; + album?: string | null; + cover?: string | null; + suggestionId?: string; +}; + +export const fromSong = (song: Song): QueueItem => ({ + key: `song:${song.id}`, + source: "library", + src: streamUrl(song.id), + title: song.title, + artist: song.artist, + album: song.album, + cover: song.coverArt ? coverUrl(song.coverArt, 300) : null, +}); + +export const fromSuggestion = (s: Suggestion): QueueItem => ({ + key: `suggestion:${s.id}`, + source: "youtube", + src: youtubeUrl(s.id), + title: s.title, + artist: s.artist, + album: s.release, + cover: s.cover_url, + suggestionId: s.id, +}); + +/** Spread new songs evenly through the library songs */ +export function interleave(library: QueueItem[], fresh: QueueItem[]): QueueItem[] { + if (fresh.length === 0) return library; + const out: QueueItem[] = []; + const every = Math.max(1, Math.round((library.length + fresh.length) / fresh.length)); + let l = 0; + let f = 0; + for (let i = 0; l < library.length || f < fresh.length; i++) { + const takeFresh = (i % every === every - 1 && f < fresh.length) || l >= library.length; + out.push(takeFresh ? fresh[f++] : library[l++]); + } + return out; +} diff --git a/discover/src/styles.css b/discover/src/styles.css new file mode 100644 index 0000000..cd11e9b --- /dev/null +++ b/discover/src/styles.css @@ -0,0 +1,824 @@ +:root { + --bg: #f6f5f2; + --surface: #ffffff; + --surface-2: #efede8; + --border: #e2dfd8; + --text: #1d1b18; + --muted: #6d675e; + --accent: #5b3df5; + --accent-text: #ffffff; + --youtube: #d4351c; + --library: #2f7d4f; + --heart: #e0245e; + --shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%); + --art-l: 62%; + --art-s: 70%; + --radius: 12px; + font-family: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + font-size: 15px; + line-height: 1.45; + color: var(--text); + background: var(--bg); + -webkit-font-smoothing: antialiased; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #121214; + --surface: #1b1b1f; + --surface-2: #26262b; + --border: #2e2e34; + --text: #f1f0ee; + --muted: #a09d98; + --accent: #8b74ff; + --accent-text: #120d26; + --youtube: #ff6b52; + --library: #5fcf8d; + --heart: #ff5c8a; + --shadow: 0 1px 2px rgb(0 0 0 / 30%), 0 8px 24px rgb(0 0 0 / 30%); + --art-l: 45%; + --art-s: 55%; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--bg); +} + +button, +select, +input { + font: inherit; + color: inherit; +} + +a { + color: inherit; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +/* ---------- layout ---------- */ + +.app { + display: grid; + grid-template-columns: 272px minmax(0, 1fr); + min-height: 100vh; +} + +.sidebar { + position: sticky; + top: 0; + height: 100vh; + overflow-y: auto; + padding: 20px 12px; + border-right: 1px solid var(--border); + background: var(--surface); +} + +.with-player .sidebar { + height: calc(100vh - 84px); +} + +.content { + padding: 28px clamp(16px, 4vw, 48px) 48px; + min-width: 0; +} + +.with-player .content { + padding-bottom: 120px; +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + padding: 0 10px 16px; + font-weight: 700; + font-size: 1.15rem; + letter-spacing: -0.01em; +} + +.brand-mark { + display: grid; + place-items: center; + width: 28px; + height: 28px; + border-radius: 8px; + background: var(--accent); + color: var(--accent-text); +} + +.rule-select { + width: calc(100% - 20px); + margin: 0 10px 8px; + padding: 6px 8px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface-2); +} + +.rule-info { + display: flex; + align-items: center; + justify-content: space-between; + margin: 0 0 8px; + padding: 0 4px 0 10px; + color: var(--muted); + font-size: 0.85rem; +} + +.mix-list { + list-style: none; + margin: 0; + padding: 0; +} + +.mix-list a { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 10px; + border-radius: 8px; + text-decoration: none; + color: var(--text); +} + +.mix-list a:hover { + background: var(--surface-2); +} + +.mix-list a.selected { + background: hsl(var(--hue) var(--art-s) var(--art-l) / 18%); +} + +.mix-dot { + flex: none; + width: 12px; + height: 12px; + border-radius: 4px; + background: linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 12%))); +} + +.mix-dot.heart { + display: grid; + place-items: center; + background: none; + color: var(--heart); +} + +.mix-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 0.93rem; +} + +.count { + flex: none; + min-width: 22px; + padding: 1px 7px; + border-radius: 999px; + background: var(--accent); + color: var(--accent-text); + font-size: 0.75rem; + font-weight: 600; + text-align: center; +} + +.liked-link { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid var(--border); +} + +/* ---------- mix header ---------- */ + +.mix-header { + display: flex; + gap: 28px; + align-items: flex-end; + margin-bottom: 32px; +} + +.mix-art { + flex: none; + display: grid; + place-items: end start; + width: 200px; + height: 200px; + padding: 18px; + border-radius: 16px; + background: + radial-gradient(circle at 80% 15%, hsl(calc(var(--hue) + 60) 90% 75% / 70%), transparent 55%), + linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 18%))); + color: #fff; + box-shadow: var(--shadow); + font-weight: 800; + font-size: 1.5rem; + line-height: 1.1; + letter-spacing: -0.02em; + text-shadow: 0 1px 8px rgb(0 0 0 / 25%); + overflow-wrap: anywhere; +} + +.liked-view .mix-art { + place-items: center; +} + +.mix-info { + min-width: 0; +} + +.eyebrow { + margin: 0 0 4px; + color: var(--muted); + font-size: 0.78rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +h1 { + margin: 0 0 12px; + font-size: clamp(1.6rem, 3.4vw, 2.6rem); + line-height: 1.1; + letter-spacing: -0.025em; +} + +.tags { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0 0 12px; + padding: 0; + list-style: none; +} + +.tags li { + padding: 2px 10px; + border-radius: 999px; + background: hsl(var(--hue) var(--art-s) var(--art-l) / 16%); + font-size: 0.82rem; +} + +.mix-counts { + margin: 0 0 16px; + color: var(--muted); + font-size: 0.9rem; +} + +.mix-buttons { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.mix-buttons button { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 9px 16px; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--surface); + font-weight: 600; + cursor: pointer; +} + +.mix-buttons button.primary { + border-color: transparent; + background: var(--accent); + color: var(--accent-text); +} + +.mix-buttons button:disabled { + opacity: 0.5; + cursor: default; +} + +/* ---------- track lists ---------- */ + +section + section { + margin-top: 32px; +} + +h2 { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 8px; + font-size: 1.05rem; +} + +.empty { + color: var(--muted); +} + +.tracks { + margin: 0; + padding: 0; + list-style: none; +} + +.track { + display: grid; + grid-template-columns: 36px 44px minmax(0, 1fr) auto auto auto; + align-items: center; + gap: 12px; + padding: 6px 8px; + border-radius: 10px; +} + +.track:hover, +.track.active { + background: var(--surface); +} + +.track.active { + box-shadow: inset 3px 0 0 var(--accent); +} + +.track-play { + display: grid; + place-items: center; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + cursor: pointer; +} + +.track-icon { + display: none; +} + +.track:hover .track-number, +.track.active .track-number { + display: none; +} + +.track:hover .track-icon, +.track.active .track-icon, +.track-play:focus-visible .track-icon { + display: grid; + place-items: center; + color: var(--accent); +} + +.track-play:focus-visible .track-number { + display: none; +} + +.track-number { + color: var(--muted); + font-variant-numeric: tabular-nums; + font-size: 0.85rem; +} + +.cover { + position: relative; + display: grid; + place-items: center; + overflow: hidden; + border-radius: 6px; + background: var(--surface-2); + color: var(--muted); + font-weight: 700; +} + +.cover img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; +} + +.track-text { + min-width: 0; +} + +.track-title, +.track-sub { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.track-title { + font-weight: 600; +} + +.track.active .track-title { + color: var(--accent); +} + +.track-sub { + color: var(--muted); + font-size: 0.88rem; +} + +.match { + color: var(--muted); + font-size: 0.82rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.track-duration { + color: var(--muted); + font-size: 0.85rem; + font-variant-numeric: tabular-nums; +} + +.track-actions { + display: flex; + gap: 2px; +} + +.icon-button { + display: inline-grid; + place-items: center; + width: 34px; + height: 34px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + color: var(--muted); + cursor: pointer; +} + +.icon-button.small { + width: 28px; + height: 28px; +} + +.icon-button:hover { + background: var(--surface-2); + color: var(--text); +} + +.icon-button.liked { + color: var(--heart); +} + +/* ---------- player ---------- */ + +.player { + position: fixed; + inset: auto 0 0 0; + z-index: 10; + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr) minmax(0, 1fr); + align-items: center; + gap: 20px; + height: 84px; + padding: 0 20px; + border-top: 1px solid var(--border); + background: color-mix(in srgb, var(--surface) 92%, transparent); + backdrop-filter: blur(12px); +} + +.player-track { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; +} + +.badge { + flex: none; + padding: 1px 8px; + border-radius: 999px; + border: 1px solid currentColor; + font-size: 0.72rem; + font-weight: 600; +} + +.badge.youtube { + color: var(--youtube); +} + +.badge.library { + color: var(--library); +} + +.player-main { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; +} + +.player-buttons { + display: flex; + align-items: center; + gap: 10px; +} + +.play-button { + display: grid; + place-items: center; + width: 40px; + height: 40px; + border: 0; + border-radius: 50%; + background: var(--text); + color: var(--bg); + cursor: pointer; +} + +.player-progress { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + color: var(--muted); + font-size: 0.75rem; + font-variant-numeric: tabular-nums; +} + +.player-progress span { + width: 38px; + text-align: center; +} + +.player-progress input { + flex: 1; + height: 4px; + appearance: none; + border-radius: 2px; + background: linear-gradient(to right, var(--accent) var(--progress), var(--border) var(--progress)); + cursor: pointer; +} + +.player-progress input::-webkit-slider-thumb { + appearance: none; + width: 12px; + height: 12px; + border-radius: 50%; + background: var(--text); +} + +.player-progress input::-moz-range-thumb { + width: 12px; + height: 12px; + border: 0; + border-radius: 50%; + background: var(--text); +} + +.player-status { + position: absolute; + top: -26px; + padding: 2px 10px; + border-radius: 999px; + background: var(--surface-2); + font-size: 0.78rem; + white-space: nowrap; +} + +.player-status.error { + color: var(--youtube); +} + +.player-queue { + justify-self: end; + color: var(--muted); + font-size: 0.85rem; + font-variant-numeric: tabular-nums; +} + +/* ---------- feedback ---------- */ + +.spinner { + display: inline-block; + width: 16px; + height: 16px; + border: 2px solid var(--border); + border-top-color: var(--accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; + vertical-align: middle; +} + +.spinner.light { + border-color: color-mix(in srgb, var(--bg) 35%, transparent); + border-top-color: var(--bg); +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +.bars { + display: flex; + align-items: flex-end; + gap: 2px; + height: 14px; +} + +.bars i { + width: 3px; + background: var(--accent); + animation: bar 0.9s ease-in-out infinite; +} + +.bars i:nth-child(2) { + animation-delay: -0.3s; +} + +.bars i:nth-child(3) { + animation-delay: -0.6s; +} + +@keyframes bar { + 0%, + 100% { + height: 30%; + } + 50% { + height: 100%; + } +} + +@media (prefers-reduced-motion: reduce) { + .bars i, + .spinner { + animation: none; + } +} + +.notice { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 24px; + padding: 16px 20px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.notice.error { + border-color: var(--youtube); + color: var(--youtube); +} + +.notice pre { + overflow-x: auto; + margin: 0; + padding: 12px; + border-radius: 8px; + background: var(--surface-2); + font-size: 0.85rem; +} + +.toast { + position: fixed; + left: 50%; + bottom: 104px; + z-index: 20; + display: flex; + align-items: center; + gap: 14px; + max-width: calc(100vw - 32px); + padding: 10px 16px; + border-radius: 10px; + background: var(--text); + color: var(--bg); + box-shadow: var(--shadow); + transform: translateX(-50%); +} + +.app:not(.with-player) .toast { + bottom: 24px; +} + +.toast button { + border: 0; + background: none; + color: var(--accent); + font-weight: 700; + cursor: pointer; +} + +/* ---------- small screens ---------- */ + +@media (max-width: 800px) { + .app { + grid-template-columns: minmax(0, 1fr); + } + + .sidebar, + .with-player .sidebar { + position: static; + height: auto; + padding: 14px 16px 10px; + border-right: 0; + border-bottom: 1px solid var(--border); + } + + .brand { + padding: 0 0 10px; + } + + .rule-info { + padding: 0; + } + + .mix-list { + display: flex; + gap: 6px; + overflow-x: auto; + margin: 0 -16px; + padding: 0 16px 4px; + scrollbar-width: none; + } + + .mix-list a { + border: 1px solid var(--border); + border-radius: 999px; + padding: 6px 12px; + } + + .mix-name { + overflow: visible; + } + + .liked-link { + margin: 0; + padding: 0; + border: 0; + } + + .content { + padding: 20px 16px 40px; + } + + .mix-header { + flex-direction: column; + align-items: stretch; + gap: 18px; + } + + .mix-art { + width: 100%; + height: 140px; + } + + .track { + grid-template-columns: 32px 40px minmax(0, 1fr) auto; + gap: 10px; + padding: 6px 0; + } + + .track-meta, + .track-duration, + .track-album { + display: none; + } + + .player { + grid-template-columns: minmax(0, 1fr) auto; + height: auto; + padding: 10px 16px; + gap: 12px; + } + + .player-main { + flex-direction: row-reverse; + } + + .player-progress, + .player-queue, + .player .badge { + display: none; + } + + .player-status { + right: 0; + top: -38px; + } + + .with-player .content { + padding-bottom: 110px; + } +} diff --git a/discover/src/usePlayer.ts b/discover/src/usePlayer.ts new file mode 100644 index 0000000..efb5ead --- /dev/null +++ b/discover/src/usePlayer.ts @@ -0,0 +1,124 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { QueueItem } from "./queue"; + +export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error"; + +export type Player = ReturnType; + +export function usePlayer(onError: (item: QueueItem) => void) { + const audio = useRef(null); + if (audio.current === null && typeof Audio !== "undefined") { + audio.current = new Audio(); + audio.current.preload = "auto"; + } + + const [queue, setQueue] = useState([]); + const [index, setIndex] = useState(-1); + const [status, setStatus] = useState("idle"); + const [time, setTime] = useState(0); + const [duration, setDuration] = useState(0); + const current = index >= 0 ? queue[index] : undefined; + + // keep the latest values for the audio element's event handlers + const state = useRef({ queue, index, onError }); + state.current = { queue, index, onError }; + + const playAt = useCallback((items: QueueItem[], at: number) => { + setQueue(items); + setIndex(at); + }, []); + + const next = useCallback(() => { + const { queue, index } = state.current; + if (index + 1 < queue.length) setIndex(index + 1); + else { + audio.current?.pause(); + setStatus("paused"); + } + }, []); + + const previous = useCallback(() => { + const el = audio.current; + if (el && el.currentTime > 3) el.currentTime = 0; + else setIndex((i) => Math.max(0, i - 1)); + }, []); + + const toggle = useCallback(() => { + const el = audio.current; + if (!el || !state.current.queue.length) return; + if (el.paused) void el.play().catch(() => undefined); + else el.pause(); + }, []); + + const seek = useCallback((seconds: number) => { + if (!audio.current) return; + audio.current.currentTime = seconds; + // update now, or the controlled slider snaps back and its change event seeks back too + setTime(seconds); + }, []); + + // load the current item + useEffect(() => { + const el = audio.current; + if (!el || !current) return; + setTime(0); + setDuration(0); + setStatus("loading"); + el.src = current.src; + void el.play().catch(() => undefined); + }, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + const el = audio.current; + if (!el) return; + let errorTimer: number | undefined; + const handlers: Record void> = { + playing: () => setStatus("playing"), + pause: () => setStatus((s) => (s === "error" ? s : "paused")), + waiting: () => setStatus("loading"), + timeupdate: () => setTime(el.currentTime), + durationchange: () => setDuration(Number.isFinite(el.duration) ? el.duration : 0), + ended: () => next(), + error: () => { + if (!el.src) return; + setStatus("error"); + const { queue, index, onError } = state.current; + if (queue[index]) onError(queue[index]); + errorTimer = window.setTimeout(next, 1500); + }, + }; + for (const [event, handler] of Object.entries(handlers)) el.addEventListener(event, handler); + return () => { + window.clearTimeout(errorTimer); + for (const [event, handler] of Object.entries(handlers)) el.removeEventListener(event, handler); + }; + }, [next]); + + // OS media controls and keyboard + useEffect(() => { + if (!("mediaSession" in navigator) || !current) return; + navigator.mediaSession.metadata = new MediaMetadata({ + title: current.title, + artist: current.artist, + album: current.album ?? undefined, + artwork: current.cover ? [{ src: current.cover }] : [], + }); + navigator.mediaSession.setActionHandler("play", toggle); + navigator.mediaSession.setActionHandler("pause", toggle); + navigator.mediaSession.setActionHandler("nexttrack", next); + navigator.mediaSession.setActionHandler("previoustrack", previous); + }, [current, toggle, next, previous]); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + const target = e.target as HTMLElement; + if (e.code !== "Space" || ["INPUT", "TEXTAREA", "BUTTON"].includes(target.tagName)) return; + e.preventDefault(); + toggle(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [toggle]); + + return { queue, index, current, status, time, duration, playAt, next, previous, toggle, seek }; +} diff --git a/discover/tsconfig.json b/discover/tsconfig.json new file mode 100644 index 0000000..4515ae8 --- /dev/null +++ b/discover/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "skipLibCheck": true, + "isolatedModules": true, + "noEmit": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/discover/vite.config.ts b/discover/vite.config.ts new file mode 100644 index 0000000..019b8d4 --- /dev/null +++ b/discover/vite.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; + +// During development, API requests go to playlistd (PLAYLISTD_URL, default localhost:8000) +export default defineConfig({ + plugins: [react()], + server: { + proxy: { + "/api": process.env.PLAYLISTD_URL ?? "http://localhost:8000", + }, + }, +}); diff --git a/etc/playlistd/playlistd.toml b/etc/playlistd/playlistd.toml index 3ce6e9a..6301899 100644 --- a/etc/playlistd/playlistd.toml +++ b/etc/playlistd/playlistd.toml @@ -13,3 +13,17 @@ interval = 240 [database] # URL of database to use url = "postgres:///navidrome-playlists" + +[listenbrainz] +# Your Listenbrainz user token (listenbrainz.org/settings). Optional: lets the discover UI +# find new songs for each mix's genres with LB Radio, on top of your recommendations +# token = "" + +[discover] +# Directory with the built discover UI (discover/dist) to serve at / +# ui = "/usr/share/playlistd/discover" +# yt-dlp binary used to play suggested songs that aren't in your library +# ytdlp = "yt-dlp" +# Format to ask Subsonic to stream in ("raw" = no transcoding), e.g. "mp3" if your +# library has files browsers can't play +# format = "raw" diff --git a/migrations/20261113180000_mix_suggestions.sql b/migrations/20261113180000_mix_suggestions.sql new file mode 100644 index 0000000..c560163 --- /dev/null +++ b/migrations/20261113180000_mix_suggestions.sql @@ -0,0 +1,24 @@ +ALTER TABLE "cluster_mix_rule" + ADD COLUMN discovery_count INT NOT NULL DEFAULT 15; -- New songs to suggest per mix + +ALTER TABLE "cluster_mix_playlist" + ADD COLUMN name VARCHAR(250), -- Name of the playlist in subsonic + ADD COLUMN position INT NOT NULL DEFAULT 0; -- Order of the mix, most listened first + +-- Songs not in the library, recommended by Listenbrainz and matched to a mix by genre +CREATE TABLE "mix_suggestion" +( + id UUID NOT NULL PRIMARY KEY, + rule_id UUID NOT NULL REFERENCES "cluster_mix_rule" (id) ON DELETE CASCADE, + mix_id UUID REFERENCES "cluster_mix_playlist" (id) ON DELETE SET NULL, + recording_mbid VARCHAR(36) NOT NULL, + title VARCHAR(500) NOT NULL, + artist VARCHAR(500) NOT NULL, + release VARCHAR(500), + cover_url TEXT, + score DOUBLE PRECISION NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'new', -- new, liked or dismissed + youtube_id VARCHAR(32), -- Cached YouTube match + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (rule_id, recording_mbid) +); diff --git a/src/daemon/cluster_mixes.rs b/src/daemon/cluster_mixes.rs index d97dfc7..c615f46 100644 --- a/src/daemon/cluster_mixes.rs +++ b/src/daemon/cluster_mixes.rs @@ -1,4 +1,5 @@ use crate::cluster::{self, ClusterOptions, Play}; +use crate::discover::{self, MixTarget}; use crate::listenbrainz; use crate::mix::{self, ListenedTrack, MixOptions, RecentlyPlayed}; use crate::models::{ClusterMixPlaylist, ClusterMixRule}; @@ -8,7 +9,7 @@ use chrono::Utc; use rand::rngs::StdRng; use rand::SeedableRng; use sqlx::postgres::PgPool; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::time::Duration; use tokio::time::{interval, MissedTickBehavior}; use uuid::Uuid; @@ -142,7 +143,7 @@ pub async fn build_mixes( ) .await? { - Some(mix) => mixes.push(mix), + Some(mix) => mixes.push((mix, cluster)), None => println!( "No library genres match cluster {:?}", cluster @@ -157,7 +158,7 @@ pub async fn build_mixes( // two clusters can share their top genres let mut seen_labels: HashMap = HashMap::new(); - for mix in &mut mixes { + for (mix, _) in &mut mixes { let n = seen_labels.entry(mix.label.clone()).or_default(); *n += 1; if *n > 1 { @@ -176,12 +177,17 @@ pub async fn build_mixes( let pairs = mix::match_mixes( &existing.iter().map(|p| p.tags.clone()).collect::>(), - &mixes.iter().map(|m| m.tags.clone()).collect::>(), + &mixes + .iter() + .map(|(m, _)| m.tags.clone()) + .collect::>(), ); let old_for_new: HashMap = pairs.iter().map(|&(o, n)| (n, o)).collect(); - for (n, mix) in mixes.iter().enumerate() { + let mut targets = vec![]; + for (n, (mix, cluster)) in mixes.iter().enumerate() { let name = rule.name_template.replace("{label}", &mix.label); + let position = n as i32; let reused = match old_for_new.get(&n).map(|&o| &existing[o]) { // the playlist may have been deleted by hand since the last run @@ -190,13 +196,15 @@ pub async fn build_mixes( .rename_playlist(&old.playlist_id, &name) .await?; sqlx::query!( - r#"UPDATE "cluster_mix_playlist" SET tags = $1 WHERE id = $2"#, + r#"UPDATE "cluster_mix_playlist" SET tags = $1, name = $2, position = $3 WHERE id = $4"#, &mix.tags, + name, + position, old.id ) .execute(database) .await?; - Some(old.playlist_id.clone()) + Some((old.id, old.playlist_id.clone())) } Some(old) => { sqlx::query!( @@ -210,25 +218,32 @@ pub async fn build_mixes( None => None, }; - let playlist_id = match reused { - Some(id) => id, + let (mix_id, playlist_id) = match reused { + Some(ids) => ids, None => { let playlist = media_client.create_playlist(&name).await?; + let mix_id = Uuid::new_v4(); sqlx::query!( r#" - INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags) - VALUES ($1, $2, $3, $4) + INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags, name, position) + VALUES ($1, $2, $3, $4, $5, $6) "#, - Uuid::new_v4(), + mix_id, rule.id, playlist.id, &mix.tags, + name, + position, ) .execute(database) .await?; - playlist.id + (mix_id, playlist.id) } }; + targets.push(MixTarget { + mix_id, + profile: cluster.profile.clone(), + }); media_client .replace_playlist_songs(&playlist_id, mix.song_ids.clone()) @@ -252,6 +267,17 @@ pub async fn build_mixes( } } + // ---- songs that aren't in the library ---- + // a failure here shouldn't stop the mixes from being marked as built + if let Err(e) = + save_suggestions(media_client, &rule, &targets, &recently_played, database).await + { + println!( + "Could not find new songs for {}: {:?}", + rule.tracking_user, e + ); + } + sqlx::query!( r#"UPDATE "cluster_mix_rule" SET last_run = NOW() WHERE id = $1"#, rule.id @@ -261,3 +287,70 @@ pub async fn build_mixes( Ok(()) } + +async fn save_suggestions( + media_client: &Subsonic, + rule: &ClusterMixRule, + targets: &[MixTarget], + recently_played: &RecentlyPlayed, + database: &PgPool, +) -> Result<(), Box> { + // liked and dismissed suggestions stay as they are + let exclude: HashSet = sqlx::query_scalar!( + r#"SELECT recording_mbid FROM "mix_suggestion" WHERE rule_id = $1 AND status <> 'new'"#, + rule.id + ) + .fetch_all(database) + .await? + .into_iter() + .collect(); + + let suggestions = discover::suggest( + media_client, + &rule.tracking_user, + targets, + recently_played, + &exclude, + rule.discovery_count.max(0) as usize, + ) + .await?; + + for s in &suggestions { + sqlx::query!( + r#" + INSERT INTO "mix_suggestion" (id, rule_id, mix_id, recording_mbid, title, artist, release, cover_url, score) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (rule_id, recording_mbid) DO UPDATE + SET mix_id = EXCLUDED.mix_id, score = EXCLUDED.score, title = EXCLUDED.title, + artist = EXCLUDED.artist, release = EXCLUDED.release, cover_url = EXCLUDED.cover_url + "#, + Uuid::new_v4(), + rule.id, + s.mix_id, + s.mbid, + s.info.title, + s.info.artist, + s.info.release, + s.info.cover_url, + s.score, + ) + .execute(database) + .await?; + } + + // drop untouched suggestions from previous runs + let kept: Vec = suggestions.iter().map(|s| s.mbid.clone()).collect(); + sqlx::query!( + r#" + DELETE FROM "mix_suggestion" + WHERE rule_id = $1 AND status = 'new' AND NOT (recording_mbid = ANY($2)) + "#, + rule.id, + &kept, + ) + .execute(database) + .await?; + + println!(" {} new songs suggested", suggestions.len()); + Ok(()) +} diff --git a/src/discover.rs b/src/discover.rs new file mode 100644 index 0000000..e73efc6 --- /dev/null +++ b/src/discover.rs @@ -0,0 +1,210 @@ +//! Find songs that aren't in the library to suggest alongside each mix. +//! +//! Candidates come from Listenbrainz's collaborative filtering recommendations +//! for the user (filtered to recordings they've never listened to) and, if a +//! Listenbrainz token is configured, an LB Radio prompt built from each mix's +//! top genres. Every candidate's MusicBrainz genres are compared with each +//! mix's genre profile (cosine similarity) and it's assigned to the mix it fits +//! best. Songs already in the library, or played recently, are skipped. + +use crate::listenbrainz::{self, RecordingInfo}; +use crate::mix::{name_key, normalize, RecentlyPlayed}; +use crate::subsonic::Subsonic; +use std::collections::{HashMap, HashSet}; +use uuid::Uuid; + +/// Candidates must fit a mix at least this well (cosine similarity of genres) +const MIN_FIT: f64 = 0.2; +/// Most suggestions per artist in one mix +const PER_ARTIST: usize = 2; +/// Recommendations to request from Listenbrainz +const RECOMMENDATIONS: usize = 1000; +/// Genres per LB Radio prompt +const RADIO_GENRES: usize = 3; + +pub struct MixTarget { + pub mix_id: Uuid, + /// The mix's genres (as in the cluster profile, best first) and their weights + pub profile: Vec<(String, f64)>, +} + +pub struct Suggestion { + pub mix_id: Uuid, + pub mbid: String, + pub info: RecordingInfo, + pub score: f64, +} + +/// Cosine similarity between a recording's genres and a mix profile +fn fit(genres: &HashMap, profile: &HashMap, profile_norm: f64) -> f64 { + let (mut dot, mut norm) = (0.0, 0.0); + for (genre, w) in genres { + norm += w * w; + if let Some(p) = profile.get(&normalize(genre)) { + dot += w * p; + } + } + if norm == 0.0 || profile_norm == 0.0 { + 0.0 + } else { + dot / (norm.sqrt() * profile_norm) + } +} + +pub async fn suggest( + client: &Subsonic, + user: &str, + targets: &[MixTarget], + recently_played: &RecentlyPlayed, + // recordings that already have a suggestion the user acted on + exclude: &HashSet, + per_mix: usize, +) -> Result, Box> { + if targets.is_empty() || per_mix == 0 { + return Ok(vec![]); + } + + // ---- candidates ---- + let mut candidates: Vec = listenbrainz::recommendations(user, RECOMMENDATIONS) + .await? + .into_iter() + .filter(|r| r.latest_listened_at.is_none()) + .map(|r| r.recording_mbid) + .collect(); + + if let Some(token) = listenbrainz::token() { + for target in targets { + let genres: Vec<&str> = target + .profile + .iter() + .take(RADIO_GENRES) + .map(|(g, _)| g.as_str()) + .collect(); + // LB Radio prompts can't contain these + if genres.iter().any(|g| g.contains([',', '(', ')', ':'])) { + continue; + } + let prompt = format!("tag:({})::or", genres.join(", ")); + match listenbrainz::radio(&prompt, "medium", &token).await { + Ok(mbids) => candidates.extend(mbids), + Err(e) => println!("LB Radio failed for {}: {:?}", prompt, e), + } + } + } + + let mut seen = HashSet::new(); + candidates.retain(|m| !exclude.contains(m) && seen.insert(m.clone())); + let metadata = listenbrainz::recording_metadata(&candidates).await?; + + // ---- assign each candidate to the mix it fits best ---- + let profiles: Vec<(HashMap, f64)> = targets + .iter() + .map(|t| { + let mut p: HashMap = HashMap::new(); + for (genre, w) in &t.profile { + *p.entry(normalize(genre)).or_default() += w; + } + let norm = p.values().map(|w| w * w).sum::().sqrt(); + (p, norm) + }) + .collect(); + + let mut per_target: Vec> = vec![vec![]; targets.len()]; + for (mbid, info) in &metadata { + if info.title.is_empty() + || recently_played.contains_recording(Some(mbid), &info.artist, &info.title) + { + continue; + } + let best = profiles + .iter() + .enumerate() + .map(|(i, (p, n))| (i, fit(&info.genres, p, *n))) + .max_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((i, score)) = best { + if score >= MIN_FIT { + per_target[i].push((score, mbid, info)); + } + } + } + + // ---- pick the best per mix, skipping songs already in the library ---- + let mut suggestions = vec![]; + let mut seen_names: HashSet = HashSet::new(); + for (target, mut found) in targets.iter().zip(per_target) { + found.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1))); + let mut artists: HashMap = HashMap::new(); + let mut taken = 0; + + for (score, mbid, info) in found { + if taken >= per_mix { + break; + } + let artist_count = artists.entry(normalize(&info.artist)).or_default(); + if *artist_count >= PER_ARTIST + || seen_names.contains(&name_key(&info.artist, &info.title)) + { + continue; + } + if in_library(client, mbid, info).await? { + continue; + } + + *artist_count += 1; + taken += 1; + seen_names.insert(name_key(&info.artist, &info.title)); + suggestions.push(Suggestion { + mix_id: target.mix_id, + mbid: mbid.clone(), + info: RecordingInfo { + title: info.title.clone(), + artist: info.artist.clone(), + release: info.release.clone(), + cover_url: info.cover_url.clone(), + genres: HashMap::new(), + }, + score, + }); + } + } + + Ok(suggestions) +} + +async fn in_library( + client: &Subsonic, + mbid: &str, + info: &RecordingInfo, +) -> Result> { + if !client.song_search(mbid.to_string()).await?.is_empty() { + return Ok(true); + } + let key = name_key(&info.artist, &info.title); + Ok(client + .song_search(format!("{} {}", info.title, info.artist)) + .await? + .iter() + .any(|s| name_key(&s.artist, &s.title) == key)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fit_prefers_matching_genres() { + let profile: HashMap = + [("mathcore".to_string(), 2.0), ("mathrock".to_string(), 1.0)].into(); + let norm = 5f64.sqrt(); + let math: HashMap = [ + ("Mathcore".to_string(), 1.0), + ("math rock".to_string(), 1.0), + ] + .into(); + let folk: HashMap = [("folk".to_string(), 1.0)].into(); + + assert!(fit(&math, &profile, norm) > 0.9); + assert_eq!(fit(&folk, &profile, norm), 0.0); + assert_eq!(fit(&HashMap::new(), &profile, norm), 0.0); + } +} diff --git a/src/listenbrainz.rs b/src/listenbrainz.rs index 0b0a326..e1cf146 100644 --- a/src/listenbrainz.rs +++ b/src/listenbrainz.rs @@ -239,10 +239,32 @@ pub async fn listens_since(user: impl Display, min_ts: i64) -> Result, + #[serde(default)] + artist: Option, + #[serde(default)] + release: Option, #[serde(default)] tag: Option, } +#[derive(Deserialize, Default)] +struct Named { + #[serde(default)] + name: String, +} + +#[derive(Deserialize, Default)] +struct Release { + #[serde(default)] + name: Option, + #[serde(default)] + caa_id: Option, + #[serde(default)] + caa_release_mbid: Option, +} + #[derive(Deserialize, Default)] struct RecordingTags { #[serde(default)] @@ -263,11 +285,21 @@ struct Tag { genre_mbid: Option, } -/// Weighted MusicBrainz genres for each recording, combining the recording's own genres (most -/// specific) with those of its release group and artists (broadest). Names are lowercased. -pub async fn recording_tags( +pub struct RecordingInfo { + pub title: String, + pub artist: String, + pub release: Option, + /// Front cover from the Cover Art Archive, if there is one + pub cover_url: Option, + /// Weighted MusicBrainz genres, combining the recording's own genres (most specific) with + /// those of its release group and artists (broadest). Names are lowercased. + pub genres: HashMap, +} + +/// Names, cover art and genres of recordings +pub async fn recording_metadata( mbids: &[String], -) -> Result>, reqwest::Error> { +) -> Result, reqwest::Error> { let client = reqwest::Client::new(); let mut out = HashMap::new(); @@ -282,8 +314,8 @@ pub async fn recording_tags( let metadata = send_json::>(request).await?; for (mbid, recording) in metadata { - let mut weights: HashMap = HashMap::new(); - if let Some(tags) = recording.tag { + let mut genres: HashMap = HashMap::new(); + if let Some(tags) = &recording.tag { for (source, weight) in [ (&tags.recording, 3.0), (&tags.release_group, 2.0), @@ -292,15 +324,151 @@ pub async fn recording_tags( for tag in source.iter().filter(|t| t.genre_mbid.is_some()) { let name = tag.tag.trim().to_lowercase(); if !name.is_empty() { - *weights.entry(name).or_default() += + *genres.entry(name).or_default() += weight * (1.0 + tag.count.unwrap_or(1).max(1) as f64).ln(); } } } } - out.insert(mbid, weights); + let release = recording.release.unwrap_or_default(); + let cover_url = match (release.caa_id, &release.caa_release_mbid) { + (Some(id), Some(release_mbid)) => Some(format!( + "https://coverartarchive.org/release/{}/{}-250.jpg", + release_mbid, id + )), + _ => None, + }; + + out.insert( + mbid, + RecordingInfo { + title: recording.recording.unwrap_or_default().name, + artist: recording.artist.unwrap_or_default().name, + release: release.name, + cover_url, + genres, + }, + ); } } Ok(out) } + +/// Weighted MusicBrainz genres for each recording; see [`RecordingInfo::genres`] +pub async fn recording_tags( + mbids: &[String], +) -> Result>, reqwest::Error> { + Ok(recording_metadata(mbids) + .await? + .into_iter() + .map(|(mbid, info)| (mbid, info.genres)) + .collect()) +} + +#[derive(Deserialize)] +struct RecommendationsResponse { + payload: RecommendationsPayload, +} + +#[derive(Deserialize)] +struct RecommendationsPayload { + #[serde(default)] + mbids: Vec, +} + +#[derive(Deserialize, Clone)] +pub struct Recommendation { + pub recording_mbid: String, + /// Set if the user has ever listened to the recording + #[serde(default)] + pub latest_listened_at: Option, +} + +/// Listenbrainz's collaborative filtering recording recommendations for a user +pub async fn recommendations( + user: impl Display, + count: usize, +) -> Result, reqwest::Error> { + let response = reqwest::Client::new() + .get(format!( + "{}/cf/recommendation/user/{}/recording", + BASE, user + )) + .query(&[("count", count)]) + .header(reqwest::header::USER_AGENT, USER_AGENT) + .send() + .await? + .error_for_status()?; + + // 204 when there are no recommendations for the user (yet) + if response.status() == reqwest::StatusCode::NO_CONTENT { + return Ok(vec![]); + } + Ok(response + .json::() + .await? + .payload + .mbids) +} + +/// The user token from the config, needed by some endpoints (e.g. LB Radio) +pub fn token() -> Option { + crate::CONFIG + .get()? + .get::("listenbrainz.token") + .ok() + .filter(|t| !t.is_empty()) +} + +#[derive(Deserialize)] +struct RadioResponse { + payload: RadioPayload, +} + +#[derive(Deserialize)] +struct RadioPayload { + jspf: Jspf, +} + +#[derive(Deserialize)] +struct Jspf { + playlist: JspfPlaylist, +} + +#[derive(Deserialize)] +struct JspfPlaylist { + #[serde(default)] + track: Vec, +} + +#[derive(Deserialize)] +struct JspfTrack { + #[serde(default)] + identifier: Vec, +} + +/// Recording MBIDs from an LB Radio prompt, e.g. `tag:(mathcore, math rock)::or`. +/// `mode` is "easy", "medium" or "hard" (more obscure). Needs a user token. +pub async fn radio(prompt: &str, mode: &str, token: &str) -> Result, reqwest::Error> { + let request = reqwest::Client::new() + .get(format!("{}/explore/lb-radio", BASE)) + .query(&[("prompt", prompt), ("mode", mode)]) + .header(reqwest::header::AUTHORIZATION, format!("Token {}", token)); + + Ok(send_json::(request) + .await? + .payload + .jspf + .playlist + .track + .into_iter() + .flat_map(|t| t.identifier) + .filter_map(|id| { + id.rsplit('/') + .next() + .filter(|m| m.len() == 36) + .map(str::to_string) + }) + .collect()) +} diff --git a/src/main.rs b/src/main.rs index 5985b3c..fce4aa3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,14 @@ mod cluster; mod daemon; +mod discover; mod listenbrainz; mod mix; mod models; mod playlist; mod subsonic; mod track; +mod web; +mod youtube; use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon}; use crate::models::{ @@ -71,9 +74,19 @@ async fn main() -> Result<(), Box> { }); } - rocket::build() + let youtube = youtube::YouTube::new( + CONFIG + .get() + .unwrap() + .get::("discover.ytdlp") + .unwrap_or_else(|_| "yt-dlp".to_string()), + ); + + let mut server = rocket::build() .manage(media_client) .manage(database) + .manage(youtube) + .mount("/api/discover", web::routes()) .mount( "/api/playlist", routes![ @@ -84,9 +97,14 @@ async fn main() -> Result<(), Box> { create_cluster_mix_rule, all_cluster_mix_rules, ], - ) - .launch() - .await?; + ); + + // the discover UI's built files (discover/dist) + if let Ok(ui) = CONFIG.get().unwrap().get::("discover.ui") { + server = server.mount("/", rocket::fs::FileServer::from(ui)); + } + + server.launch().await?; Ok(()) } diff --git a/src/mix.rs b/src/mix.rs index 7b19363..1743a48 100644 --- a/src/mix.rs +++ b/src/mix.rs @@ -27,7 +27,7 @@ pub struct MixOptions { pub struct Mix { pub label: String, - /// Normalised genres describing the mix, best first + /// Library genres describing the mix, best first pub tags: Vec, pub song_ids: Vec, } @@ -67,10 +67,12 @@ impl RecentlyPlayed { } fn contains(&self, song: &Track) -> bool { - song.music_brainz_id - .as_ref() - .is_some_and(|m| self.mbids.contains(m)) - || self.names.contains(&name_key(&song.artist, &song.title)) + self.contains_recording(song.music_brainz_id.as_deref(), &song.artist, &song.title) + } + + pub fn contains_recording(&self, mbid: Option<&str>, artist: &str, title: &str) -> bool { + mbid.is_some_and(|m| self.mbids.contains(m)) + || self.names.contains(&name_key(artist, title)) } } @@ -249,7 +251,11 @@ pub async fn build_mix( Ok(Some(Mix { label, - tags: matched.iter().take(5).map(|(k, _)| k.clone()).collect(), + tags: matched + .iter() + .take(5) + .map(|(k, _)| library_genres[k].clone()) + .collect(), song_ids: chosen.into_iter().map(|s| s.id).collect(), })) } @@ -260,8 +266,8 @@ pub fn match_mixes(old: &[Vec], new: &[Vec]) -> Vec<(usize, usiz let mut pairs: Vec<(f64, usize, usize)> = vec![]; for (i, a) in old.iter().enumerate() { for (j, b) in new.iter().enumerate() { - let a: HashSet<_> = a.iter().collect(); - let b: HashSet<_> = b.iter().collect(); + let a: HashSet = a.iter().map(|t| normalize(t)).collect(); + let b: HashSet = b.iter().map(|t| normalize(t)).collect(); let union = a.union(&b).count(); let jaccard = if union == 0 { 0.0 diff --git a/src/models.rs b/src/models.rs index f306cba..19380d1 100644 --- a/src/models.rs +++ b/src/models.rs @@ -142,6 +142,7 @@ pub struct PartialClusterMixRule { pub familiar_ratio: Option, pub name_template: Option, pub refresh_hours: Option, + pub discovery_count: Option, } impl PartialClusterMixRule { @@ -154,8 +155,8 @@ impl PartialClusterMixRule { sqlx::query!( r#" INSERT INTO "cluster_mix_rule" - (id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours) - VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24)) + (id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours, discovery_count) + VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24), COALESCE($9, 15)) "#, uuid, self.tracking_user, @@ -165,6 +166,7 @@ impl PartialClusterMixRule { self.familiar_ratio, self.name_template, self.refresh_hours, + self.discovery_count, ) .execute(pool) .await?; @@ -184,6 +186,7 @@ pub struct ClusterMixRule { pub name_template: String, pub refresh_hours: i32, pub last_run: Option>, + pub discovery_count: i32, } impl ClusterMixRule { @@ -226,4 +229,22 @@ pub struct ClusterMixPlaylist { pub rule_id: Uuid, pub playlist_id: String, pub tags: Vec, + pub name: Option, + pub position: i32, +} + +#[derive(Serialize)] +pub struct MixSuggestion { + pub id: Uuid, + pub rule_id: Uuid, + pub mix_id: Option, + pub recording_mbid: String, + pub title: String, + pub artist: String, + pub release: Option, + pub cover_url: Option, + pub score: f64, + pub status: String, + pub youtube_id: Option, + pub created_at: DateTime, } diff --git a/src/subsonic.rs b/src/subsonic.rs index b1e2a03..25c0ef8 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -266,6 +266,27 @@ impl Subsonic { serde_json::from_value(response).map_err(SubsonicError::Json) } + /// Request a binary endpoint (e.g. `stream`, `getCoverArt`) and hand back the raw response, + /// forwarding an HTTP Range header if given + pub async fn raw( + &self, + endpoint: &str, + params: &[(&'static str, String)], + range: Option<&str>, + ) -> Result { + let mut query = self.base_params(); + query.extend_from_slice(params); + + let mut request = self + .client + .get(format!("{}/{}", self.base, endpoint)) + .query(&query); + if let Some(range) = range { + request = request.header(reqwest::header::RANGE, range); + } + request.send().await.map_err(SubsonicError::Reqwest) + } + /// All genres in the library pub async fn get_genres(&self) -> Result, SubsonicError> { Ok(self diff --git a/src/track.rs b/src/track.rs index 6c6e41c..866a690 100644 --- a/src/track.rs +++ b/src/track.rs @@ -15,6 +15,11 @@ pub struct Track { pub genres: Vec, #[serde(rename = "musicBrainzId", default)] pub music_brainz_id: Option, + /// Seconds + #[serde(default)] + pub duration: Option, + #[serde(rename = "coverArt", default)] + pub cover_art: Option, } #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/src/web.rs b/src/web.rs new file mode 100644 index 0000000..cde8230 --- /dev/null +++ b/src/web.rs @@ -0,0 +1,375 @@ +//! API for the discover UI: mixes, suggested songs, and audio/cover streaming +//! from Subsonic or YouTube. + +use crate::models::{ClusterMixRule, MixSuggestion}; +use crate::subsonic::Subsonic; +use crate::track::Track; +use crate::youtube::YouTube; +use futures_util::TryStreamExt; +use rocket::http::Status; +use rocket::request::{FromRequest, Outcome}; +use rocket::response::{self, Responder}; +use rocket::serde::json::Json; +use rocket::{get, post, put, routes, Request, Response, Route, State}; +use serde::{Deserialize, Serialize}; +use sqlx::postgres::PgPool; +use std::convert::Infallible; +use std::sync::Arc; +use tokio_util::io::StreamReader; +use uuid::Uuid; + +pub fn routes() -> Vec { + routes![rules, mixes, mix, liked, set_status, rebuild, stream, cover, youtube] +} + +type ApiResult = Result, Status>; + +fn db_error(e: sqlx::Error) -> Status { + match e { + sqlx::Error::RowNotFound => Status::NotFound, + e => { + println!("Database error: {:?}", e); + Status::InternalServerError + } + } +} + +fn parse_id(id: &str) -> Result { + Uuid::parse_str(id).map_err(|_| Status::NotFound) +} + +#[get("/rules")] +async fn rules(pool: &State) -> ApiResult> { + ClusterMixRule::all(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +#[derive(Serialize)] +struct MixSummary { + id: Uuid, + playlist_id: String, + name: Option, + tags: Vec, + position: i32, + new_count: i64, +} + +#[get("/rules//mixes")] +async fn mixes(id: &str, pool: &State) -> ApiResult> { + sqlx::query_as!( + MixSummary, + r#" + SELECT p.id, p.playlist_id, p.name, p.tags, p.position, + COUNT(s.id) FILTER (WHERE s.status = 'new') AS "new_count!" + FROM "cluster_mix_playlist" p + LEFT JOIN "mix_suggestion" s ON s.mix_id = p.id + WHERE p.rule_id = $1 + GROUP BY p.id + ORDER BY p.position + "#, + parse_id(id)? + ) + .fetch_all(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +#[derive(Serialize)] +struct MixDetail { + #[serde(flatten)] + summary: MixSummary, + songs: Vec, + suggestions: Vec, +} + +#[get("/mixes/")] +async fn mix( + id: &str, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + let summary = sqlx::query_as!( + MixSummary, + r#" + SELECT p.id, p.playlist_id, p.name, p.tags, p.position, + COUNT(s.id) FILTER (WHERE s.status = 'new') AS "new_count!" + FROM "cluster_mix_playlist" p + LEFT JOIN "mix_suggestion" s ON s.mix_id = p.id + WHERE p.id = $1 + GROUP BY p.id + "#, + id + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + let songs = media_client + .get_playlist(&summary.playlist_id) + .await + .map_err(|e| { + println!("Could not load playlist {}: {:?}", summary.playlist_id, e); + Status::BadGateway + })? + .entry; + + let suggestions = sqlx::query_as!( + MixSuggestion, + r#" + SELECT * FROM "mix_suggestion" + WHERE mix_id = $1 AND status <> 'dismissed' + ORDER BY score DESC + "#, + id + ) + .fetch_all(pool.inner()) + .await + .map_err(db_error)?; + + Ok(Json(MixDetail { + summary, + songs, + suggestions, + })) +} + +#[get("/rules//liked")] +async fn liked(id: &str, pool: &State) -> ApiResult> { + sqlx::query_as!( + MixSuggestion, + r#" + SELECT * FROM "mix_suggestion" + WHERE rule_id = $1 AND status = 'liked' + ORDER BY created_at DESC + "#, + parse_id(id)? + ) + .fetch_all(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +#[derive(Deserialize)] +struct StatusUpdate { + status: String, +} + +/// Like, dismiss, or reset a suggestion +#[put("/suggestions/", data = "")] +async fn set_status( + id: &str, + update: Json, + pool: &State, +) -> ApiResult { + if !["new", "liked", "dismissed"].contains(&update.status.as_str()) { + return Err(Status::UnprocessableEntity); + } + sqlx::query_as!( + MixSuggestion, + r#"UPDATE "mix_suggestion" SET status = $1 WHERE id = $2 RETURNING *"#, + update.status, + parse_id(id)? + ) + .fetch_one(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +/// Rebuild a rule's mixes on the next daemon tick +#[post("/rules//rebuild")] +async fn rebuild(id: &str, pool: &State) -> Status { + let Ok(id) = parse_id(id) else { + return Status::NotFound; + }; + match sqlx::query!( + r#"UPDATE "cluster_mix_rule" SET last_run = NULL WHERE id = $1"#, + id + ) + .execute(pool.inner()) + .await + { + Ok(r) if r.rows_affected() > 0 => Status::Accepted, + Ok(_) => Status::NotFound, + Err(e) => db_error(e), + } +} + +/// The request's Range header, so audio can be seeked +pub struct Range(Option); + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for Range { + type Error = Infallible; + + async fn from_request(request: &'r Request<'_>) -> Outcome { + Outcome::Success(Range( + request.headers().get_one("Range").map(str::to_string), + )) + } +} + +/// Stream an upstream response through, keeping the headers a media element needs +pub struct Proxied(reqwest::Response); + +impl<'r> Responder<'r, 'static> for Proxied { + fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> { + let upstream = self.0; + let mut response = Response::build(); + response.status(Status::new(upstream.status().as_u16())); + for name in [ + "content-type", + "content-range", + "accept-ranges", + "cache-control", + "last-modified", + "etag", + ] { + if let Some(value) = upstream.headers().get(name).and_then(|v| v.to_str().ok()) { + response.raw_header(name, value.to_string()); + } + } + let size = upstream.content_length(); + let body = StreamReader::new(upstream.bytes_stream().map_err(std::io::Error::other)); + match size { + // a known length lets browsers show durations and seek + Some(size) => response.sized_body(size as usize, LengthReader(body)), + None => response.streamed_body(body), + }; + response.ok() + } +} + +/// Rocket only accepts a known body length for seekable bodies, but never seeks one whose size +/// is given up front. This satisfies the trait for a plain stream. +struct LengthReader(R); + +impl tokio::io::AsyncRead for LengthReader { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.0).poll_read(cx, buf) + } +} + +impl tokio::io::AsyncSeek for LengthReader { + fn start_seek(self: std::pin::Pin<&mut Self>, _: std::io::SeekFrom) -> std::io::Result<()> { + Err(std::io::Error::other("streamed body can't be seeked")) + } + + fn poll_complete( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Err(std::io::Error::other("streamed body can't be seeked"))) + } +} + +/// Stream a song from Subsonic +#[get("/stream/")] +async fn stream( + id: &str, + range: Range, + media_client: &State>, +) -> Result { + let format = crate::CONFIG + .get() + .and_then(|c| c.get::("discover.format").ok()) + .unwrap_or_else(|| "raw".to_string()); + media_client + .raw( + "stream", + &[("id", id.to_string()), ("format", format)], + range.0.as_deref(), + ) + .await + .map(Proxied) + .map_err(|_| Status::BadGateway) +} + +/// Cover art from Subsonic +#[get("/cover/?")] +async fn cover( + id: &str, + size: Option, + media_client: &State>, +) -> Result { + media_client + .raw( + "getCoverArt", + &[ + ("id", id.to_string()), + ("size", size.unwrap_or(300).to_string()), + ], + None, + ) + .await + .map(Proxied) + .map_err(|_| Status::BadGateway) +} + +/// Find a suggested song on YouTube and stream its audio +#[get("/youtube/")] +async fn youtube( + id: &str, + range: Range, + pool: &State, + youtube: &State, +) -> Result { + let suggestion = sqlx::query_as!( + MixSuggestion, + r#"SELECT * FROM "mix_suggestion" WHERE id = $1"#, + parse_id(id)? + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + let video_id = match suggestion.youtube_id { + Some(video_id) => video_id, + None => { + let video_id = youtube + .search(&suggestion.artist, &suggestion.title) + .await + .map_err(|e| { + println!("YouTube search failed: {}", e); + Status::BadGateway + })? + .ok_or(Status::NotFound)?; + sqlx::query!( + r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#, + video_id, + suggestion.id + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + video_id + } + }; + + // a cached URL may have expired; fetch a fresh one once + for refresh in [false, true] { + let url = youtube.audio_url(&video_id, refresh).await.map_err(|e| { + println!("Could not get audio for {}: {}", video_id, e); + Status::BadGateway + })?; + let mut request = youtube.client.get(url); + if let Some(range) = &range.0 { + request = request.header(reqwest::header::RANGE, range); + } + let response = request.send().await.map_err(|_| Status::BadGateway)?; + if !refresh && matches!(response.status().as_u16(), 403 | 404 | 410) { + continue; + } + return Ok(Proxied(response)); + } + Err(Status::BadGateway) +} diff --git a/src/youtube.rs b/src/youtube.rs new file mode 100644 index 0000000..2882048 --- /dev/null +++ b/src/youtube.rs @@ -0,0 +1,133 @@ +//! Find and stream songs from YouTube with yt-dlp. + +use std::collections::HashMap; +use std::process::Stdio; +use std::time::{Duration, Instant}; +use thiserror::Error; +use tokio::process::Command; +use tokio::sync::Mutex; + +/// Search results longer than this are probably full albums or mixes +const MAX_DURATION_SECS: f64 = 15.0 * 60.0; +/// YouTube's media URLs expire after about 6 hours +const URL_TTL: Duration = Duration::from_secs(60 * 60); +const SEARCH_RESULTS: usize = 5; + +#[derive(Debug, Error)] +pub enum YouTubeError { + #[error("couldn't run yt-dlp: {0}")] + Spawn(#[from] std::io::Error), + #[error("yt-dlp failed: {0}")] + Failed(String), + #[error("invalid video id")] + InvalidId, +} + +pub struct YouTube { + binary: String, + urls: Mutex>, + pub client: reqwest::Client, +} + +pub fn valid_video_id(id: &str) -> bool { + id.len() == 11 + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +impl YouTube { + pub fn new(binary: String) -> Self { + Self { + binary, + urls: Mutex::new(HashMap::new()), + client: reqwest::Client::new(), + } + } + + async fn run(&self, args: &[&str]) -> Result { + let output = Command::new(&self.binary) + .args(["--no-warnings", "--no-playlist", "--ignore-config"]) + .args(args) + .stdin(Stdio::null()) + .kill_on_drop(true) + .output() + .await?; + if !output.status.success() { + return Err(YouTubeError::Failed( + String::from_utf8_lossy(&output.stderr).trim().to_string(), + )); + } + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) + } + + /// The ID of the best matching video for a song, skipping very long videos + pub async fn search(&self, artist: &str, title: &str) -> Result, YouTubeError> { + let query = format!("ytsearch{}:{} - {}", SEARCH_RESULTS, artist, title); + let output = self + .run(&["--flat-playlist", "--print", "%(id)s\t%(duration)s", &query]) + .await?; + + let results: Vec<(&str, Option)> = output + .lines() + .filter_map(|line| { + let (id, duration) = line.split_once('\t')?; + valid_video_id(id).then(|| (id, duration.trim().parse::().ok())) + }) + .collect(); + + Ok(results + .iter() + .find(|(_, d)| d.is_some_and(|d| d <= MAX_DURATION_SECS)) + .or(results.first()) + .map(|(id, _)| id.to_string())) + } + + /// A direct URL to the video's audio, preferring m4a since every browser can play it + pub async fn audio_url(&self, video_id: &str, refresh: bool) -> Result { + if !valid_video_id(video_id) { + return Err(YouTubeError::InvalidId); + } + { + let urls = self.urls.lock().await; + if let Some((url, fetched)) = urls.get(video_id) { + if !refresh && fetched.elapsed() < URL_TTL { + return Ok(url.clone()); + } + } + } + + let output = self + .run(&[ + "-f", + "bestaudio[ext=m4a]/bestaudio", + "--get-url", + &format!("https://www.youtube.com/watch?v={}", video_id), + ]) + .await?; + let url = output + .lines() + .next() + .filter(|l| l.starts_with("http")) + .ok_or_else(|| YouTubeError::Failed("no audio URL".to_string()))? + .to_string(); + + let mut urls = self.urls.lock().await; + urls.retain(|_, (_, fetched)| fetched.elapsed() < URL_TTL); + urls.insert(video_id.to_string(), (url.clone(), Instant::now())); + Ok(url) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_video_ids() { + assert!(valid_video_id("dQw4w9WgXcQ")); + assert!(valid_video_id("a-b_c123456")); + assert!(!valid_video_id("--exec=rm -")); + assert!(!valid_video_id("short")); + } +}