diff --git a/.cargo/config.toml b/.cargo/config.toml index 3707b70..a3488cf 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,8 +1,2 @@ -[registries.crates-io] -protocol = "sparse" - -[target.x86_64-pc-windows-gnu] -rustflags = "-C link-args=-lssp" # Does not compile without this line - [target.aarch64-unknown-linux-gnu] -rustflags = "-C linker=aarch64-linux-gnu-gcc" \ No newline at end of file +rustflags = "-C linker=aarch64-linux-gnu-gcc" diff --git a/.dockerignore b/.dockerignore index ade9286..4fd3f7b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,8 @@ -target/ -.env -.gitignore -.dockerignore -Dockerfile \ No newline at end of file +# .dockerignore +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# build and deps +/target + +# env files +.env* \ No newline at end of file diff --git a/.github/workflows/build-push.yml b/.github/workflows/build-push.yml index 8e143c3..093ccda 100644 --- a/.github/workflows/build-push.yml +++ b/.github/workflows/build-push.yml @@ -2,16 +2,16 @@ name: Build and push to registry on: push: - branches: [ "main", "dev" ] - tags: [ "v*.*.*" ] + branches: ["main", "dev"] + tags: ["v*.*.*"] pull_request: - branches: [ "main", "dev" ] + branches: ["main", "dev"] workflow_dispatch: permissions: packages: write contents: read - + jobs: build-and-push: name: Build Docker image and push to registry @@ -53,6 +53,15 @@ jobs: type=semver,pattern={{major}} type=sha + - name: Inject Docker cache + uses: reproducible-containers/buildkit-cache-dance@v3.1.0 + with: + cache-map: | + { + "usr-local-cargo-registry": "/usr/local/cargo/registry", + "app-target": "/app/target" + } + - name: Build image and push to registry uses: docker/build-push-action@v5 with: @@ -62,5 +71,6 @@ jobs: tags: ${{ steps.docker-meta.outputs.tags }} labels: ${{ steps.docker-meta.outputs.labels }} # Some basic caching of the layers... - cache-from: ${{ steps.repo-uri-string.outputs.lowercase }}:latest-cache - cache-to: ${{ steps.repo-uri-string.outputs.lowercase }}:latest-cache + cache-from: type=gha + cache-to: type=gha,mode=max + provenance: false diff --git a/.github/workflows/cargo-clippy.yml b/.github/workflows/cargo-clippy.yml index 50e42d6..b053994 100644 --- a/.github/workflows/cargo-clippy.yml +++ b/.github/workflows/cargo-clippy.yml @@ -10,15 +10,15 @@ jobs: clippy: name: Run Clippy runs-on: ubuntu-latest - + steps: - name: Checkout code uses: actions/checkout@v2 - + - name: Set up Rust uses: actions-rs/toolchain@v1 with: toolchain: stable - + - name: Run Cargo Clippy run: cargo clippy --all-targets --all-features -- -D warnings diff --git a/.gitignore b/.gitignore index 924b3f5..b793bc1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,6 @@ # Rust /target -# SQLite database -*.db -*.sqlite - # Secrets .env diff --git a/.rustfmt.toml b/.rustfmt.toml deleted file mode 100644 index 6f2e075..0000000 --- a/.rustfmt.toml +++ /dev/null @@ -1 +0,0 @@ -tab_spaces = 2 \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8213056..8d266b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,26 +1,43 @@ # Changelog +## 2.2.0 | TBD + +### Changes + +- Rewrote the entire bot (again) +- Updated librespot from v0.4.2 to v0.5.0-dev +- Added `/lyrics`, which provides the user with an auto-updating lyrics embed +- Added `/stop`, which disconnects the bot from Spotify without leaving the call (will still leave after 5 minutes) +- Changed `/playing` to automatically update the embed accordingly +- Removed the Database API, replaced with direct connection to a Postgres database + +**Full Changelog** (good luck): https://github.com/SpoticordMusic/spoticord/compare/v2.1.2..v2.2.0 + ## 2.1.2 | September 28th 2023 ### Changes -* Removed OpenSSL dependency -* Added aarch64 support -* Added cross compilation to Github Actions -* Added `dev` branch to Github Actions -* Removed hardcoded URL in the /join command -* Fixed an issue in /playing where the bot showed it was playing even though it was paused + +- Removed OpenSSL dependency +- Added aarch64 support +- Added cross compilation to Github Actions +- Added `dev` branch to Github Actions +- Removed hardcoded URL in the /join command +- Fixed an issue in /playing where the bot showed it was playing even though it was paused **Full Changelog**: https://github.com/SpoticordMusic/spoticord/compare/v2.1.1...v2.1.2 ## 2.1.1 | September 23rd 2023 + Reduced the amount of CPU that the bot uses from ~15%-25% per user to 1%-2% per user (percentage per core, benched on an AMD Ryzen 9 5950X). ### Changes -* Fixed issue #20 + +- Fixed issue #20 **Full Changelog**: https://github.com/SpoticordMusic/spoticord/compare/v2.1.0...v2.1.1 ## 2.1.0 | September 20th 2023 + So, it's been a while since I worked on this project, and some bugs have since been discovered. The main focus for this version is to stop using multiple processes for every player, and instead do everything in threads. @@ -37,11 +54,12 @@ The main focus for this version is to stop using multiple processes for every pl - Enable autoplay - After skipping a song, you will no longer hear a tiny bit of the previous song after the silence - **Full Changelog**: https://github.com/SpoticordMusic/spoticord/compare/v2.0.0...v2.1.0 ### Issues + - Currently, the CPU usage is much higher than it used to be. I really wanted to push this update out before taking the time to do some optimizations, as the bot and server are still easily able to hold up the limited amount of Spoticord users (and v2.0.0 was just falling apart). Issue is being tracked in #20 ## 2.0.0 | June 8th 2023 -- Initial Release \ No newline at end of file + +- Initial Release diff --git a/COMPILING.md b/COMPILING.md index 2b9c7f8..88d2d5e 100644 --- a/COMPILING.md +++ b/COMPILING.md @@ -1,8 +1,11 @@ # Compiling from source + ## Initial setup + Spoticord is built using [rust](https://www.rust-lang.org/), so you'll need to install that first. It is cross-platform, so it should work on Windows, Linux and MacOS. You can find more info about how to install rust [here](https://www.rust-lang.org/tools/install). ### Rust formatter + Spoticord uses [rustfmt](https://github.com/rust-lang/rustfmt) to format the code, and we ask everyone that contributes to Spoticord to use it as well. You can install it by running the following command in your terminal: ```sh @@ -12,6 +15,7 @@ rustup component add rustfmt If you are using VSCode, you can install the [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer) extension, which will automatically format your code when you save it (if you have `format on save` enabled). Although rust-analyzer is recommended anyway, as it provides a lot of useful features. ## Build dependencies + On Windows you'll need to install the [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019) to be able to compile executables in rust (this will also be explained during the rust installation). If you are on Linux, you can use your package manager to install the following dependencies: @@ -41,6 +45,7 @@ sudo dnf install cmake ``` ## Compiling + Now that you have all the dependencies installed, you can compile Spoticord. To do this, you'll first need to clone the repository: ```sh @@ -76,9 +81,9 @@ cargo run As of now, Spoticord has one optional feature: `stats`. This feature enables collecting a few statistics, total and active servers. These statistics will be sent to a redis server, where they then can be read for whatever purpose. If you want to enable this feature, you can do so by running the following command: ```sh -cargo build [--release] --features metrics +cargo build [--release] --features stats ``` # MSRV -The current minimum supported rust version is `1.67.0`. +The current minimum supported rust version is `1.75.0` _(Checked with `cargo-msrv`)_. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1349a10..2ae87d6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,8 +40,8 @@ We make use of `rustfmt` to format our code. You can install it by running `rust We make use of the pre-commit git hook to run `clippy` before you commit your code. To set up the git hooks you can run the following command: - ```bash - git config core.hooksPath .githooks - ``` +```bash +git config core.hooksPath .githooks +``` -If you want to skip this check, you can use the `--no-verify` flag in your git commit command. Do note however that code that does not pass these checks will not be merged. \ No newline at end of file +If you want to skip this check, you can use the `--no-verify` flag in your git commit command. Do note however that code that does not pass these checks will not be merged. diff --git a/Cargo.lock b/Cargo.lock index 0fe5cb3..a8274f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" dependencies = [ "gimli", ] @@ -19,66 +19,52 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "aead" -version = "0.4.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b613b8e1e3cf911a086f53f03bf286f52fd7a7258e4fa606f0ef220d39d8877" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ + "crypto-common", "generic-array", - "rand_core", ] [[package]] name = "aes" -version = "0.6.0" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "884391ef1066acaa41e766ba8f596341b96e93ce34f9a43e7d24bf0a0eaf0561" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ - "aes-soft", - "aesni", - "cipher 0.2.5", + "cfg-if", + "cipher", + "cpufeatures", ] [[package]] -name = "aes-ctr" -version = "0.6.0" +name = "ahash" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7729c3cde54d67063be556aeac75a81330d802f0259500ca40cb52967f975763" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ - "aes-soft", - "aesni", - "cipher 0.2.5", - "ctr", -] - -[[package]] -name = "aes-soft" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be14c7498ea50828a38d0e24a765ed2effe92a705885b57d029cd67d45744072" -dependencies = [ - "cipher 0.2.5", - "opaque-debug", -] - -[[package]] -name = "aesni" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea2e11f5e94c2f7d386164cc2aa1f97823fed6f259e486940a71c174dd01b0ce" -dependencies = [ - "cipher 0.2.5", - "opaque-debug", + "cfg-if", + "once_cell", + "version_check", + "zerocopy", ] [[package]] name = "aho-corasick" -version = "1.1.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5d730647d4fadd988536d06fecce94b7b4f2a7efdae548f1cf4b63205518ab" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" + [[package]] name = "android-tzdata" version = "0.1.1" @@ -95,54 +81,107 @@ dependencies = [ ] [[package]] -name = "anyhow" -version = "1.0.75" +name = "anstream" +version = "0.6.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" +checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" + +[[package]] +name = "anstyle-parse" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8" +dependencies = [ + "anstyle", + "windows-sys 0.52.0", +] + +[[package]] +name = "anyhow" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "arrayvec" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" +dependencies = [ + "serde", +] [[package]] -name = "async-trait" -version = "0.1.73" +name = "async-stream" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" +checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] -name = "async-tungstenite" -version = "0.17.2" +name = "async-trait" +version = "0.1.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1b71b31561643aa8e7df3effe284fa83ab1a840e52294c5f4bd7bfd8b2becbb" +checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ - "futures-io", - "futures-util", - "log", - "pin-project-lite", - "tokio", - "tokio-rustls 0.23.4", - "tungstenite", - "webpki-roots 0.22.6", + "proc-macro2", + "quote", + "syn 2.0.72", ] [[package]] -name = "atty" -version = "0.2.14" +name = "atomic-waker" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi 0.1.19", - "libc", - "winapi", -] +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "audiopus" @@ -166,15 +205,15 @@ dependencies = [ [[package]] name = "autocfg" -version = "1.1.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "backtrace" -version = "0.3.69" +version = "0.3.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" +checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", "cc", @@ -193,9 +232,21 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.4" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" [[package]] name = "bitflags" @@ -205,18 +256,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "block-buffer" @@ -229,36 +271,70 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.14.0" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "bytecount" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ce89b21cab1437276d2650d57e971f9d548a2d9037cc231abdc0562b97498ce" [[package]] name = "bytemuck" -version = "1.14.0" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "374d28ec25809ee0e23827c2ab573d729e293f281dfe393500e7ad618baa61c6" +checksum = "102087e286b4677862ea56cf8fc58bb2cdfa8725c40ffb80fe3a008eb7f2fc83" [[package]] name = "byteorder" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.5.0" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" +checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50" + +[[package]] +name = "camino" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0ec6b951b160caa93cc0c7b209e5a3bff7aae9062213451ac99493cd844c239" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo-platform" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", +] [[package]] name = "cc" -version = "1.0.83" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] +checksum = "26a5c3fd7bfa1ce3897a3a3501d362b2d87b7f2583ebcb4a949ec25911025cbc" [[package]] name = "cfg-if" @@ -268,34 +344,28 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.31" +version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", - "num-traits 0.2.16", + "num-traits", + "serde", "wasm-bindgen", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] name = "cipher" -version = "0.2.5" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f8e7987cbd042a63249497f41aed09f8e65add917ea6566effbc56578d6801" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "generic-array", -] - -[[package]] -name = "cipher" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" -dependencies = [ - "generic-array", + "crypto-common", + "inout", + "zeroize", ] [[package]] @@ -308,10 +378,16 @@ dependencies = [ ] [[package]] -name = "combine" -version = "4.6.6" +name = "colorchoice" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35ed6e9d84f0b51a7f52daf1c7d71dd136fd7a3f41a8462b8cdb8c78d920fad4" +checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0" + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" dependencies = [ "bytes", "memchr", @@ -319,9 +395,9 @@ dependencies = [ [[package]] name = "command_attr" -version = "0.4.2" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07b787d19b9806dd4c9c34b2b4147d1a61d6120d93ee289521ab9b0294d198e4" +checksum = "88da8d7e9fe6f30d8e3fcf72d0f84102b49de70fece952633e8439e89bdc7631" dependencies = [ "proc-macro2", "quote", @@ -329,38 +405,66 @@ dependencies = [ ] [[package]] -name = "core-foundation-sys" -version = "0.8.4" +name = "const-oid" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" [[package]] name = "cpufeatures" -version = "0.2.9" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" dependencies = [ "libc", ] [[package]] name = "crc32fast" -version = "1.3.2" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" dependencies = [ "cfg-if", ] [[package]] -name = "crossbeam-utils" -version = "0.8.16" +name = "crossbeam-channel" +version = "0.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2" dependencies = [ - "cfg-if", + "crossbeam-utils", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" + [[package]] name = "crypto-common" version = "0.1.6" @@ -368,26 +472,102 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", + "rand_core", "typenum", ] [[package]] -name = "crypto-mac" -version = "0.11.1" +name = "crypto_secretbox" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1d1a86f49236c215f271d40892d5fc950490551400b02ef360692c29815c714" +checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1" dependencies = [ + "aead", + "cipher", "generic-array", + "poly1305", + "salsa20", "subtle", + "zeroize", ] [[package]] name = "ctr" -version = "0.6.0" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb4a30d54f7443bf3d6191dcd486aca19e67cb3c49fa7a06a319966346707e7f" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "cipher 0.2.5", + "cipher", +] + +[[package]] +name = "darling" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858" +dependencies = [ + "darling_core 0.10.2", + "darling_macro 0.10.2", +] + +[[package]] +name = "darling" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" +dependencies = [ + "darling_core 0.20.10", + "darling_macro 0.20.10", +] + +[[package]] +name = "darling_core" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c960ae2da4de88a91b2d920c2a7233b400bc33cb28453a2987822d8392519b" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.9.3", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.11.1", + "syn 2.0.72", +] + +[[package]] +name = "darling_macro" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72" +dependencies = [ + "darling_core 0.10.2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" +dependencies = [ + "darling_core 0.20.10", + "quote", + "syn 2.0.72", ] [[package]] @@ -397,7 +577,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" dependencies = [ "cfg-if", - "hashbrown 0.14.0", + "hashbrown", "lock_api", "once_cell", "parking_lot_core", @@ -405,11 +585,48 @@ dependencies = [ ] [[package]] -name = "deranged" -version = "0.3.8" +name = "data-encoding" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946" +checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" + +[[package]] +name = "deadpool" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "421fe0f90f2ab22016f32a9881be5134fdd71c65298917084b0c7477cbc3856e" dependencies = [ + "async-trait", + "deadpool-runtime", + "num_cpus", + "retain_mut", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + +[[package]] +name = "der" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", "serde", ] @@ -425,12 +642,113 @@ dependencies = [ ] [[package]] -name = "digest" +name = "derive_builder" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +checksum = "a2658621297f2cf68762a6f7dc0bb7e1ff2cfd6583daef8ee0fed6f7ec468ec0" dependencies = [ - "generic-array", + "darling 0.10.2", + "derive_builder_core", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2791ea3e372c8495c0bc2033991d76b512cd799d07491fbd6890124db9458bef" +dependencies = [ + "darling 0.10.2", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_more" +version = "0.99.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.72", +] + +[[package]] +name = "diesel" +version = "2.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff236accb9a5069572099f0b350a92e9560e8e63a9b8d546162f4a5e03026bb2" +dependencies = [ + "bitflags 2.6.0", + "byteorder", + "chrono", + "diesel_derives", + "itoa", +] + +[[package]] +name = "diesel-async" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acada1517534c92d3f382217b485db8a8638f111b0e3f2a2a8e26165050f77be" +dependencies = [ + "async-trait", + "deadpool", + "diesel", + "futures-util", + "scoped-futures", + "tokio", + "tokio-postgres", +] + +[[package]] +name = "diesel_async_migrations" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a700d6b83a17973b94d3065970fd2b36f1036c3fe08adcbdce1c9beb8fb25553" +dependencies = [ + "diesel", + "diesel-async", + "diesel_async_migrations_macros", + "scoped-futures", + "tracing", +] + +[[package]] +name = "diesel_async_migrations_macros" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05de210f31e6ac18162501b03c37f839af9f9fd6dd6de2bb4031ae6691c47679" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "diesel_derives" +version = "2.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14701062d6bed917b5c7103bdffaee1e4609279e240488ad24e7bd979ca6866c" +dependencies = [ + "diesel_table_macro_syntax", + "proc-macro2", + "quote", + "syn 2.0.72", +] + +[[package]] +name = "diesel_table_macro_syntax" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc5557efc453706fed5e4fa85006fe9817c224c3f480a34c7e5959fd700921c5" +dependencies = [ + "syn 2.0.72", ] [[package]] @@ -439,67 +757,76 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer 0.10.4", + "block-buffer", + "const-oid", "crypto-common", + "subtle", ] [[package]] name = "discortp" -version = "0.4.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb66017646a48220b5ea30d63ac18bb5952f647f1a41ed755880895125d26972" +checksum = "5c793408a15d361754613fa68123ffa60424c2617fafdf82127b4bedf37d3f5d" dependencies = [ "pnet_macros", "pnet_macros_support", ] [[package]] -name = "dotenv" -version = "0.15.0" +name = "dotenvy" +version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "encoding_rs" -version = "0.8.33" +version = "0.8.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" +checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" dependencies = [ "cfg-if", ] [[package]] -name = "enum_primitive" -version = "0.1.1" +name = "enum_dispatch" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4551092f4d519593039259a9ed8daedf0da12e5109c5280338073eaeb81180" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" dependencies = [ - "num-traits 0.1.43", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.72", ] [[package]] -name = "env_logger" -version = "0.9.3" +name = "env_filter" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7" +checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab" dependencies = [ - "atty", - "humantime", - "log", - "termcolor", -] - -[[package]] -name = "env_logger" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" -dependencies = [ - "humantime", - "is-terminal", "log", "regex", - "termcolor", +] + +[[package]] +name = "env_logger" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "humantime", + "log", ] [[package]] @@ -510,30 +837,34 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.3" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136526188508e25c6fef639d7927dfb3e0e3084488bf202267829cf7fc23dbdd" +checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ - "errno-dragonfly", "libc", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] -name = "errno-dragonfly" -version = "0.1.2" +name = "error-chain" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" dependencies = [ - "cc", - "libc", + "version_check", ] +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "fixedbitset" @@ -543,24 +874,32 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" [[package]] name = "flate2" -version = "1.0.27" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6c98ee8095e9d1dcbf2fcc6d95acccb90d1c81db1e44725c6a984b1dbdfb010" +checksum = "7f211bbe8e69bbd0cfdea405084f128ae8b4aaa6b0b522fc8f2b009084797920" dependencies = [ "crc32fast", "miniz_oxide", ] [[package]] -name = "flume" -version = "0.10.14" +name = "float-cmp" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1657b4441c3403d9f7b3409e47575237dac27b1b5726df654a6ecbf92f0f7577" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +dependencies = [ + "num-traits", +] + +[[package]] +name = "flume" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ac459de2512911e4b674ce33cf20befaba382d05b62b008afc1c8b57cbf181" dependencies = [ "futures-core", "futures-sink", "nanorand", - "pin-project", "spin 0.9.8", ] @@ -572,18 +911,27 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "form_urlencoded" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ "percent-encoding", ] [[package]] -name = "futures" -version = "0.3.28" +name = "from_map" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" +checksum = "99f31122ab0445ff8cee420b805f24e07683073815de1dd276ee7d588d301700" +dependencies = [ + "hashmap_derive", +] + +[[package]] +name = "futures" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" dependencies = [ "futures-channel", "futures-core", @@ -596,9 +944,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -606,15 +954,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" dependencies = [ "futures-core", "futures-task", @@ -623,38 +971,44 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-macro" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" + +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -668,6 +1022,15 @@ dependencies = [ "slab", ] +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + [[package]] name = "generator" version = "0.7.5" @@ -678,7 +1041,7 @@ dependencies = [ "libc", "log", "rustversion", - "windows", + "windows 0.48.0", ] [[package]] @@ -689,6 +1052,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -702,9 +1066,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.10" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "js-sys", @@ -715,9 +1079,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" [[package]] name = "glob" @@ -726,18 +1090,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] -name = "h2" -version = "0.3.21" +name = "governor" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833" +checksum = "68a7f542ee6b35af73b06abc0dad1c1bae89964e4e253bc4b587b91c9637867b" +dependencies = [ + "cfg-if", + "futures", + "futures-timer", + "no-std-compat 0.4.1", + "nonzero_ext", + "parking_lot", + "portable-atomic", + "rand", + "smallvec", + "spinning_top", +] + +[[package]] +name = "h2" +version = "0.3.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8" dependencies = [ "bytes", "fnv", "futures-core", "futures-sink", "futures-util", - "http", - "indexmap 1.9.3", + "http 0.2.12", + "indexmap", "slab", "tokio", "tokio-util", @@ -745,27 +1127,65 @@ dependencies = [ ] [[package]] -name = "hashbrown" -version = "0.12.3" +name = "h2" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http 1.1.0", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "halfbrown" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8588661a8607108a5ca69cab034063441a0413a0b041c13618a7dd348021ef6f" +dependencies = [ + "hashbrown", + "serde", +] [[package]] name = "hashbrown" -version = "0.14.0" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2", +] + +[[package]] +name = "hashmap_derive" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb30bf173e72cc31b5265dac095423ca14e7789ff7c3b0e6096a37a996f12883" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] [[package]] name = "headers" -version = "0.3.9" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06683b93020a07e3dbcf5f8c0f6d40080d725bea7936fc01ad345c01b97dc270" +checksum = "322106e6bd0cba2d5ead589ddb8150a13d7c4217cf80d7c4f682ca994ccc6aa9" dependencies = [ - "base64 0.21.4", + "base64 0.21.7", "bytes", "headers-core", - "http", + "http 1.1.0", "httpdate", "mime", "sha1", @@ -773,27 +1193,33 @@ dependencies = [ [[package]] name = "headers-core" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" +checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" dependencies = [ - "http", + "http 1.1.0", ] [[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "hermit-abi" +name = "heck" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "hex" @@ -802,13 +1228,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] -name = "hmac" -version = "0.11.0" +name = "hls_m3u8" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a2a2320eb7ec0ebe8da8f744d7812d9fc4cb4d09344ac01898dbcb6a20ae69b" +checksum = "0e2bd2de7f92b5301546ce1ac53a4ae5cf2f6b10751b100ab1efb73c19788fba" dependencies = [ - "crypto-mac", - "digest 0.9.0", + "derive_builder", + "derive_more", + "hex", + "shorthand", + "stable-vec", + "strum 0.17.1", + "thiserror", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" +dependencies = [ + "windows-sys 0.52.0", ] [[package]] @@ -824,9 +1273,20 @@ dependencies = [ [[package]] name = "http" -version = "0.2.9" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" dependencies = [ "bytes", "fnv", @@ -835,20 +1295,43 @@ dependencies = [ [[package]] name = "http-body" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ "bytes", - "http", + "http 0.2.12", + "pin-project-lite", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http 1.1.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http 1.1.0", + "http-body 1.0.1", "pin-project-lite", ] [[package]] name = "httparse" -version = "1.8.0" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" +checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" [[package]] name = "httpdate" @@ -864,22 +1347,22 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "hyper" -version = "0.14.27" +version = "0.14.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" +checksum = "a152ddd61dfaec7273fe8419ab357f33aee0d914c5f4efbf0d96fa749eea5ec9" dependencies = [ "bytes", "futures-channel", "futures-core", "futures-util", - "h2", - "http", - "http-body", + "h2 0.3.26", + "http 0.2.12", + "http-body 0.4.6", "httparse", "httpdate", "itoa", "pin-project-lite", - "socket2 0.4.9", + "socket2", "tokio", "tower-service", "tracing", @@ -887,46 +1370,130 @@ dependencies = [ ] [[package]] -name = "hyper-proxy" -version = "0.9.1" +name = "hyper" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca815a891b24fdfb243fa3239c86154392b0953ee584aa1a2a1f66d20cbe75cc" +checksum = "50dfd22e0e76d0f662d429a5f80fcaf3855009297eab6a0a9f8543834744ba05" dependencies = [ "bytes", - "futures", - "headers", - "http", - "hyper", + "futures-channel", + "futures-util", + "h2 0.4.5", + "http 1.1.0", + "http-body 1.0.1", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-proxy2" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9043b7b23fb0bc4a1c7014c27b50a4fc42cc76206f71d34fc0dfe5b28ddc3faf" +dependencies = [ + "bytes", + "futures-util", + "headers", + "http 1.1.0", + "hyper 1.4.1", + "hyper-rustls 0.26.0", + "hyper-util", + "pin-project-lite", + "rustls-native-certs 0.7.1", + "tokio", + "tokio-rustls 0.25.0", "tower-service", + "webpki", ] [[package]] name = "hyper-rustls" -version = "0.24.1" +version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d78e1e73ec14cf7375674f74d7dde185c8206fd9dea6fb6295e8a98098aaa97" +checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" dependencies = [ "futures-util", - "http", - "hyper", - "rustls 0.21.7", + "http 0.2.12", + "hyper 0.14.30", + "rustls 0.21.12", "tokio", "tokio-rustls 0.24.1", ] [[package]] -name = "iana-time-zone" -version = "0.1.57" +name = "hyper-rustls" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" +checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" +dependencies = [ + "futures-util", + "http 1.1.0", + "hyper 1.4.1", + "hyper-util", + "log", + "rustls 0.22.4", + "rustls-native-certs 0.7.1", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.25.0", + "tower-service", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" +dependencies = [ + "futures-util", + "http 1.1.0", + "hyper 1.4.1", + "hyper-util", + "rustls 0.23.12", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.0", + "tower-service", + "webpki-roots 0.26.3", +] + +[[package]] +name = "hyper-util" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab92f4f49ee4fb4f997c784b7a2e0fa70050211e0b6a287f898c3c9785ca956" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.1.0", + "http-body 1.0.1", + "hyper 1.4.1", + "pin-project-lite", + "socket2", + "tokio", + "tower", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "windows", + "windows-core", ] [[package]] @@ -939,10 +1506,16 @@ dependencies = [ ] [[package]] -name = "idna" -version = "0.4.0" +name = "ident_case" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" dependencies = [ "unicode-bidi", "unicode-normalization", @@ -950,71 +1523,68 @@ dependencies = [ [[package]] name = "if-addrs" -version = "0.7.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbc0fa01ffc752e9dbc72818cdb072cd028b86be5e09dd04c5a643704fe101a9" +checksum = "624c5448ba529e74f594c65b7024f31b2de7b64a9b228b8df26796bbb6e32c36" dependencies = [ "libc", - "winapi", + "windows-sys 0.52.0", ] [[package]] name = "indexmap" -version = "1.9.3" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", -] - -[[package]] -name = "indexmap" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +checksum = "de3fc2e30ba82dd1b3911c8de1ffc143c74a914a14e99514d7637e3099df5ea0" dependencies = [ "equivalent", - "hashbrown 0.14.0", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array", ] [[package]] name = "ipnet" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" +checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" [[package]] -name = "is-terminal" -version = "0.4.9" +name = "is_terminal_polyfill" +version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" -dependencies = [ - "hermit-abi 0.3.3", - "rustix", - "windows-sys", -] +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" [[package]] name = "itoa" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "js-sys" -version = "0.3.64" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" dependencies = [ "wasm-bindgen", ] [[package]] name = "lazy_static" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin 0.9.8", +] [[package]] name = "levenshtein" @@ -1023,33 +1593,86 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760" [[package]] -name = "lewton" -version = "0.10.2" +name = "lexical-core" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "777b48df9aaab155475a83a7df3070395ea1ac6902f5cd062b8f2b028075c030" +checksum = "2cde5de06e8d4c2faabc400238f9ae1c74d5412d03a7bd067645ccbc47070e46" dependencies = [ - "byteorder", - "ogg", - "tinyvec", + "lexical-parse-float", + "lexical-parse-integer", + "lexical-util", + "lexical-write-float", + "lexical-write-integer", +] + +[[package]] +name = "lexical-parse-float" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683b3a5ebd0130b8fb52ba0bdc718cc56815b6a097e28ae5a6997d0ad17dc05f" +dependencies = [ + "lexical-parse-integer", + "lexical-util", + "static_assertions", +] + +[[package]] +name = "lexical-parse-integer" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d0994485ed0c312f6d965766754ea177d07f9c00c9b82a5ee62ed5b47945ee9" +dependencies = [ + "lexical-util", + "static_assertions", +] + +[[package]] +name = "lexical-util" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5255b9ff16ff898710eb9eb63cb39248ea8a5bb036bea8085b1a767ff6c4e3fc" +dependencies = [ + "static_assertions", +] + +[[package]] +name = "lexical-write-float" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accabaa1c4581f05a3923d1b4cfd124c329352288b7b9da09e766b0668116862" +dependencies = [ + "lexical-util", + "lexical-write-integer", + "static_assertions", +] + +[[package]] +name = "lexical-write-integer" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b6f3d1f4422866b68192d62f77bc5c700bee84f3069f2469d7bc8c77852446" +dependencies = [ + "lexical-util", + "static_assertions", ] [[package]] name = "libc" -version = "0.2.148" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libm" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" [[package]] name = "libmdns" -version = "0.7.5" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b04ae6b56b3b19ade26f0e7e7c1360a1713514f326c5ed0797cf2c109c9e010" +checksum = "8ed6677a7ef3e8d47432fc827d0ebf0ee77c3e3bc4a3e632d9b92433ef86f70c" dependencies = [ "byteorder", "futures-util", @@ -1059,7 +1682,7 @@ dependencies = [ "multimap", "nix", "rand", - "socket2 0.4.9", + "socket2", "thiserror", "tokio", "winapi", @@ -1067,16 +1690,13 @@ dependencies = [ [[package]] name = "librespot" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea4c9952ef48968f8184a4a87f8576982426ebe623342d5a28f7d9c4978e4a44" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ - "base64 0.13.1", - "env_logger 0.9.3", + "data-encoding", + "env_logger", "futures-util", "getopts", - "hex", - "hyper", "librespot-audio", "librespot-connect", "librespot-core", @@ -1086,38 +1706,44 @@ dependencies = [ "librespot-protocol", "log", "rpassword", - "sha-1 0.9.8", + "sha1", + "sysinfo", "thiserror", "tokio", "url", + "webpki", ] [[package]] name = "librespot-audio" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c176a31355e1ea8e0b9c4ced19df4947bfe4770661c25c142b6fba2365940d9d" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ - "aes-ctr", + "aes", "byteorder", "bytes", + "ctr", + "futures-core", "futures-util", + "http-body-util", + "hyper 1.4.1", + "hyper-util", "librespot-core", "log", + "parking_lot", "tempfile", + "thiserror", "tokio", ] [[package]] name = "librespot-connect" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ffafb6a443e9445ccb3d5d591573b5b1da3c89a9b8846c63ba2c3710210d3ec" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ "form_urlencoded", "futures-util", "librespot-core", - "librespot-discovery", "librespot-playback", "librespot-protocol", "log", @@ -1125,142 +1751,150 @@ dependencies = [ "rand", "serde", "serde_json", + "thiserror", "tokio", "tokio-stream", ] [[package]] name = "librespot-core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046349f25888e644bf02d9c5de0164b2a493d29aa4ce18e1ad0b756da9b55d6d" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ "aes", - "base64 0.13.1", + "base64 0.22.1", "byteorder", "bytes", + "data-encoding", "form_urlencoded", "futures-core", "futures-util", + "governor", "hmac", - "http", + "http 1.1.0", + "http-body-util", "httparse", - "hyper", - "hyper-proxy", + "hyper 1.4.1", + "hyper-proxy2", + "hyper-rustls 0.26.0", + "hyper-util", "librespot-protocol", "log", + "nonzero_ext", "num-bigint", + "num-derive", "num-integer", - "num-traits 0.2.16", + "num-traits", "once_cell", + "parking_lot", "pbkdf2", "priority-queue", "protobuf", + "quick-xml", "rand", + "rsa", "serde", "serde_json", - "sha-1 0.9.8", + "sha1", "shannon", + "sysinfo", "thiserror", + "time", "tokio", "tokio-stream", + "tokio-tungstenite 0.23.1", "tokio-util", "url", - "uuid 1.4.1", + "uuid", "vergen", ] [[package]] name = "librespot-discovery" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aa877d18f6150364012cb4be5682d62d7c712c88bae2d0d01720fd7c15e2f06" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ - "aes-ctr", - "base64 0.13.1", + "aes", + "base64 0.22.1", + "bytes", + "cfg-if", + "ctr", "form_urlencoded", "futures-core", + "futures-util", "hmac", - "hyper", + "http-body-util", + "hyper 1.4.1", + "hyper-util", "libmdns", "librespot-core", "log", "rand", "serde_json", - "sha-1 0.9.8", + "sha1", "thiserror", "tokio", ] [[package]] name = "librespot-metadata" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b80361fcbcb5092056fd47c08c34d5d51b08385d8efb6941c0d3e46d032c21c" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ "async-trait", "byteorder", + "bytes", "librespot-core", "librespot-protocol", "log", "protobuf", + "serde", + "serde_json", + "thiserror", + "uuid", ] [[package]] name = "librespot-playback" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5190a0b9bcc7f70ee4196a6b4a1c731d405ca130d4a6fcd4c561cfdde8b7cfb7" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ "byteorder", - "futures-executor", "futures-util", - "lewton", "librespot-audio", "librespot-core", "librespot-metadata", "log", - "ogg", "parking_lot", "rand", "rand_distr", "shell-words", + "symphonia", "thiserror", "tokio", - "zerocopy 0.6.4", + "zerocopy", ] [[package]] name = "librespot-protocol" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6d3ac6196ac0ea67bbe039f56d6730a5d8b31502ef9bce0f504ed729dcb39f" +version = "0.5.0-dev" +source = "git+https://github.com/SpoticordMusic/librespot.git#fcd5bcf4c5f046346648883ba27b774489c49bb0" dependencies = [ - "glob", "protobuf", - "protobuf-codegen-pure", -] - -[[package]] -name = "libsamplerate-sys" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28853b399f78f8281cd88d333b54a63170c4275f6faea66726a2bea5cca72e0d" -dependencies = [ - "cmake", + "protobuf-codegen", ] [[package]] name = "linux-raw-sys" -version = "0.4.7" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "lock_api" -version = "0.4.10" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" dependencies = [ "autocfg", "scopeguard", @@ -1268,9 +1902,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.20" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "loom" @@ -1303,16 +1937,37 @@ dependencies = [ ] [[package]] -name = "memchr" -version = "2.6.3" +name = "maybe-async" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f232d6ef707e1956a43342693d2a31e72989554d58299d7a88738cc95b0d35c" +checksum = "5cf92c10c7e361d6b99666ec1c6f9805b0bea2c3bd8c78dc6fe98ac5bd78db11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memoffset" -version = "0.6.5" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" dependencies = [ "autocfg", ] @@ -1325,39 +1980,55 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "mime_guess" -version = "2.0.4" +version = "2.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" dependencies = [ "mime", "unicase", ] [[package]] -name = "miniz_oxide" -version = "0.7.1" +name = "mini-moka" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +checksum = "c325dfab65f261f386debee8b0969da215b3fa0037e74c8a1234db7ba986d803" +dependencies = [ + "crossbeam-channel", + "crossbeam-utils", + "dashmap", + "skeptic", + "smallvec", + "tagptr", + "triomphe", +] + +[[package]] +name = "miniz_oxide" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" dependencies = [ "adler", ] [[package]] name = "mio" -version = "0.8.8" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" +checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4" dependencies = [ + "hermit-abi", "libc", "wasi", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "multimap" -version = "0.8.3" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" +checksum = "e1a5d38b9b352dbd913288736af36af41c48d61b1a8cd34bcecd727561b7d511" dependencies = [ "serde", ] @@ -1373,17 +2044,55 @@ dependencies = [ [[package]] name = "nix" -version = "0.23.2" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f3790c00a0150112de0f4cd161e3d7fc4b2d8a5542ffc35f099a2562aecb35c" +checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" dependencies = [ - "bitflags 1.3.2", - "cc", + "bitflags 2.6.0", "cfg-if", "libc", "memoffset", ] +[[package]] +name = "no-std-compat" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df270209a7f04d62459240d890ecb792714d5db12c92937823574a09930276b4" + +[[package]] +name = "no-std-compat" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c" + +[[package]] +name = "no-std-net" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43794a0ace135be66a25d3ae77d41b91615fb68ae937f904090203e81f755b65" + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nonzero_ext" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21" + +[[package]] +name = "ntapi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a3895c6391c39d7fe7ebc444a87eb2991b2a0bc718fdabd071eec617fc68e4" +dependencies = [ + "winapi", +] + [[package]] name = "nu-ansi-term" version = "0.46.0" @@ -1396,40 +2105,83 @@ dependencies = [ [[package]] name = "num-bigint" -version = "0.4.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" dependencies = [ - "autocfg", "num-integer", - "num-traits 0.2.16", + "num-traits", "rand", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151" +dependencies = [ + "byteorder", + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", +] + [[package]] name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" dependencies = [ "autocfg", - "num-traits 0.2.16", + "num-integer", + "num-traits", ] [[package]] name = "num-traits" -version = "0.1.43" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" -dependencies = [ - "num-traits 0.2.16", -] - -[[package]] -name = "num-traits" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", "libm", @@ -1441,47 +2193,53 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.3.3", + "hermit-abi", + "libc", +] + +[[package]] +name = "num_threads" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +dependencies = [ "libc", ] [[package]] name = "object" -version = "0.32.1" +version = "0.36.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" +checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" dependencies = [ "memchr", ] -[[package]] -name = "ogg" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6951b4e8bf21c8193da321bcce9c9dd2e13c858fe078bf9054a288b419ae5d6e" -dependencies = [ - "byteorder", -] - [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "opaque-debug" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "ordered-float" -version = "2.10.0" +version = "2.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7940cf2ca942593318d07fcf2596cdca60a85c9e7fab408a5e21a4f9dcd40d87" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" dependencies = [ - "num-traits 0.2.16", + "num-traits", ] [[package]] @@ -1492,9 +2250,9 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" [[package]] name = "parking_lot" -version = "0.12.1" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", "parking_lot_core", @@ -1502,71 +2260,107 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.8" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "backtrace", "cfg-if", "libc", "petgraph", - "redox_syscall 0.3.5", + "redox_syscall 0.5.3", "smallvec", "thread-id", - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "patricia_tree" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31f2f4539bffe53fc4b4da301df49d114b845b077bd5727b7fe2bd9d8df2ae68" +dependencies = [ + "bitflags 2.6.0", ] [[package]] name = "pbkdf2" -version = "0.8.0" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95f5254224e617595d2cc3cc73ff0a5eaf2637519e25f03388154e9378b6ffa" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ - "crypto-mac", + "digest", "hmac", ] [[package]] -name = "percent-encoding" -version = "2.3.0" +name = "pem-rfc7468" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "petgraph" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d3afd2628e69da2be385eb6f2fd57c8ac7977ceeff6dc166ff1657b0e386a9" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" dependencies = [ "fixedbitset", - "indexmap 2.0.0", + "indexmap", +] + +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", ] [[package]] name = "pin-project" -version = "1.1.3" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" +checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.3" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" +checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] name = "pin-project-lite" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "pin-utils" @@ -1575,43 +2369,96 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] -name = "pkg-config" -version = "0.3.27" +name = "pkcs1" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "pnet_base" -version = "0.28.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25488cd551a753dcaaa6fffc9f69a7610a412dd8954425bf7ffad5f7d1156fb8" +checksum = "fe4cf6fb3ab38b68d01ab2aea03ed3d1132b4868fa4e06285f29f16da01c5f4c" +dependencies = [ + "no-std-net", +] [[package]] name = "pnet_macros" -version = "0.28.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30490e0852e58402b8fae0d39897b08a24f493023a4d6cf56b2e30f31ed57548" +checksum = "688b17499eee04a0408aca0aa5cba5fc86401d7216de8a63fdf7a4c227871804" dependencies = [ "proc-macro2", "quote", "regex", - "syn 1.0.109", + "syn 2.0.72", ] [[package]] name = "pnet_macros_support" -version = "0.28.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4714e10f30cab023005adce048f2d30dd4ac4f093662abf2220855655ef8f90" +checksum = "eea925b72f4bd37f8eab0f221bbe4c78b63498350c983ffa9dd4bcde7e030f56" dependencies = [ "pnet_base", ] [[package]] -name = "poly1305" -version = "0.7.2" +name = "poise" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "048aeb476be11a4b6ca432ca569e375810de9294ae78f4774e78ea98a9246ede" +checksum = "1819d5a45e3590ef33754abce46432570c54a120798bdbf893112b4211fa09a6" +dependencies = [ + "async-trait", + "derivative", + "futures-util", + "parking_lot", + "poise_macros", + "regex", + "serenity", + "tokio", + "tracing", +] + +[[package]] +name = "poise_macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fa2c123c961e78315cd3deac7663177f12be4460f5440dbf62a7ed37b1effea" +dependencies = [ + "darling 0.20.10", + "proc-macro2", + "quote", + "syn 2.0.72", +] + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" dependencies = [ "cpufeatures", "opaque-debug", @@ -1619,60 +2466,209 @@ dependencies = [ ] [[package]] -name = "ppv-lite86" -version = "0.2.17" +name = "portable-atomic" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +checksum = "da544ee218f0d287a911e9c99a39a8c9bc8fcad3cb8db5959940044ecfc67265" + +[[package]] +name = "postgres-protocol" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acda0ebdebc28befa84bee35e651e4c5f09073d668c7aed4cf7e23c3cda84b23" +dependencies = [ + "base64 0.22.1", + "byteorder", + "bytes", + "fallible-iterator", + "hmac", + "md-5", + "memchr", + "rand", + "sha2", + "stringprep", +] + +[[package]] +name = "postgres-types" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02048d9e032fb3cc3413bbf7b83a15d84a5d419778e2628751896d856498eee9" +dependencies = [ + "bytes", + "fallible-iterator", + "postgres-protocol", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] [[package]] name = "priority-queue" -version = "1.3.2" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fff39edfcaec0d64e8d0da38564fad195d2d51b680940295fcc307366e101e61" +checksum = "70c501afe3a2e25c9bd219aa56ec1e04cdb3fcdd763055be268778c13fa82c1f" dependencies = [ "autocfg", - "indexmap 1.9.3", + "equivalent", + "indexmap", ] [[package]] name = "proc-macro2" -version = "1.0.67" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "protobuf" -version = "2.28.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94" - -[[package]] -name = "protobuf-codegen" -version = "2.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "033460afb75cf755fcfc16dfaed20b86468082a2ea24e05ac35ab4a099a017d6" +checksum = "df67496db1a89596beaced1579212e9b7c53c22dca1d9745de00ead76573d514" dependencies = [ - "protobuf", + "once_cell", + "protobuf-support", + "thiserror", ] [[package]] -name = "protobuf-codegen-pure" -version = "2.28.0" +name = "protobuf-codegen" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95a29399fc94bcd3eeaa951c715f7bea69409b2445356b00519740bcd6ddd865" +checksum = "eab09155fad2d39333d3796f67845d43e29b266eea74f7bc93f153f707f126dc" dependencies = [ + "anyhow", + "once_cell", "protobuf", - "protobuf-codegen", + "protobuf-parse", + "regex", + "tempfile", + "thiserror", +] + +[[package]] +name = "protobuf-parse" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a16027030d4ec33e423385f73bb559821827e9ec18c50e7874e4d6de5a4e96f" +dependencies = [ + "anyhow", + "indexmap", + "log", + "protobuf", + "protobuf-support", + "tempfile", + "thiserror", + "which", +] + +[[package]] +name = "protobuf-support" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e2d30ab1878b2e72d1e2fc23ff5517799c9929e2cf81a8516f9f4dcf2b9cf3" +dependencies = [ + "thiserror", +] + +[[package]] +name = "pulldown-cmark" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57206b407293d2bcd3af849ce869d52068623f19e1b5ff8e8778e3309439682b" +dependencies = [ + "bitflags 2.6.0", + "memchr", + "unicase", +] + +[[package]] +name = "quick-xml" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d3a6e5838b60e0e8fa7a43f22ade549a37d61f8bdbe636d0d7816191de969c2" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quinn" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b22d8e7369034b9a7132bc2008cac12f2013c8132b45e0554e6e20e2617f2156" +dependencies = [ + "bytes", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls 0.23.12", + "socket2", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "quinn-proto" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba92fb39ec7ad06ca2582c0ca834dfeadcaf06ddfc8e635c80aa7e1c05315fdd" +dependencies = [ + "bytes", + "rand", + "ring 0.17.8", + "rustc-hash", + "rustls 0.23.12", + "slab", + "thiserror", + "tinyvec", + "tracing", +] + +[[package]] +name = "quinn-udp" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bffec3605b73c6f1754535084a85229fa8a30f86014e6c81aeec4abb68b0285" +dependencies = [ + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.52.0", ] [[package]] name = "quote" -version = "1.0.33" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -1713,15 +2709,24 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ - "num-traits 0.2.16", + "num-traits", "rand", ] [[package]] -name = "redis" -version = "0.23.3" +name = "realfft" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f49cdc0bb3f412bf8e7d1bd90fe1d9eb10bc5c399ba90973c14662a27b3f8ba" +checksum = "953d9f7e5cdd80963547b456251296efc2626ed4e3cbf36c869d9564e0220571" +dependencies = [ + "rustfft", +] + +[[package]] +name = "redis" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0d7a6955c7511f60f3ba9e86c6d02b3c3f144f8c24b288d1f4e18074ab8bbec" dependencies = [ "combine", "itoa", @@ -1732,32 +2737,52 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.2.16" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "redox_syscall" -version = "0.3.5" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.6.0", +] + +[[package]] +name = "ref-cast" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", ] [[package]] name = "regex" -version = "1.9.5" +version = "1.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47" +checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.3.8", - "regex-syntax 0.7.5", + "regex-automata 0.4.7", + "regex-syntax 0.8.4", ] [[package]] @@ -1771,13 +2796,13 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.3.8" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795" +checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.7.5", + "regex-syntax 0.8.4", ] [[package]] @@ -1788,26 +2813,26 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.7.5" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" +checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" [[package]] name = "reqwest" -version = "0.11.20" +version = "0.11.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1" +checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" dependencies = [ - "base64 0.21.4", + "base64 0.21.7", "bytes", "encoding_rs", "futures-core", "futures-util", - "h2", - "http", - "http-body", - "hyper", - "hyper-rustls", + "h2 0.3.26", + "http 0.2.12", + "http-body 0.4.6", + "hyper 0.14.30", + "hyper-rustls 0.24.2", "ipnet", "js-sys", "log", @@ -1816,11 +2841,13 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls 0.21.7", - "rustls-pemfile", + "rustls 0.21.12", + "rustls-pemfile 1.0.4", "serde", "serde_json", "serde_urlencoded", + "sync_wrapper 0.1.2", + "system-configuration", "tokio", "tokio-rustls 0.24.1", "tokio-util", @@ -1830,10 +2857,59 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", - "webpki-roots 0.25.2", - "winreg", + "webpki-roots 0.25.4", + "winreg 0.50.0", ] +[[package]] +name = "reqwest" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7d6d2a27d57148378eb5e111173f4276ad26340ecc5c49a4a2152167a2d6a37" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http 1.1.0", + "http-body 1.0.1", + "http-body-util", + "hyper 1.4.1", + "hyper-rustls 0.27.2", + "hyper-util", + "ipnet", + "js-sys", + "log", + "mime", + "once_cell", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls 0.23.12", + "rustls-pemfile 2.1.3", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper 1.0.1", + "tokio", + "tokio-rustls 0.26.0", + "tokio-socks", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots 0.26.3", + "winreg 0.52.0", +] + +[[package]] +name = "retain_mut" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4389f1d5789befaf6029ebd9f7dac4af7f7e3d61b69d4f30e2ac02b57e7712b0" + [[package]] name = "ring" version = "0.16.20" @@ -1844,28 +2920,157 @@ dependencies = [ "libc", "once_cell", "spin 0.5.2", - "untrusted", + "untrusted 0.7.1", "web-sys", "winapi", ] [[package]] -name = "rpassword" -version = "6.0.1" +name = "ring" +version = "0.17.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bf099a1888612545b683d2661a1940089f6c2e5a8e38979b2159da876bfd956" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "spin 0.9.8", + "untrusted 0.9.0", + "windows-sys 0.52.0", +] + +[[package]] +name = "ringbuf" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c65e4c865bc3d2e3294493dff0acf7e6c259d066e34e22059fa9c39645c3636" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "rpassword" +version = "7.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80472be3c897911d0137b2d2b9055faf6eeac5b14e324073d83bc17b191d7e3f" dependencies = [ "libc", + "rtoolbox", + "windows-sys 0.48.0", +] + +[[package]] +name = "rsa" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e5124fcb30e76a7e79bfee683a2746db83784b86289f6251b54b7950a0dfc" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rspotify" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b2487556b568b6471cbbdcca0d23e1eff885e993cf057254813dc46c3837922" +dependencies = [ + "async-stream", + "async-trait", + "base64 0.22.1", + "chrono", + "futures", + "getrandom", + "log", + "maybe-async", + "rspotify-http", + "rspotify-macros", + "rspotify-model", "serde", "serde_json", - "winapi", + "sha2", + "thiserror", + "url", +] + +[[package]] +name = "rspotify-http" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9424544350d142db73534967503205030162c4e650b2f17fe1729f5dc5c8edff" +dependencies = [ + "async-trait", + "log", + "maybe-async", + "reqwest 0.12.5", + "serde_json", + "thiserror", +] + +[[package]] +name = "rspotify-macros" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "475cd14f84b46cc8d96389e0c892940cd2bd32a9240d1ba6fefcdfd8432ab9d1" + +[[package]] +name = "rspotify-model" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "496322604d8dfe61c10a37a88bb4ecac955e2d66fdbe148b2c44a844048b1ca2" +dependencies = [ + "chrono", + "enum_dispatch", + "serde", + "serde_json", + "strum 0.26.3", + "thiserror", +] + +[[package]] +name = "rtoolbox" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c247d24e63230cdb56463ae328478bd5eac8b8faa8c69461a77e8e323afac90e" +dependencies = [ + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "rubato" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5d18b486e7d29a408ef3f825bc1327d8f87af091c987ca2f5b734625940e234" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "realfft", ] [[package]] name = "rustc-demangle" -version = "0.1.23" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[package]] +name = "rustc-hash" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152" [[package]] name = "rustc_version" @@ -1877,16 +3082,31 @@ dependencies = [ ] [[package]] -name = "rustix" -version = "0.38.14" +name = "rustfft" +version = "6.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "747c788e9ce8e92b12cd485c49ddf90723550b654b32508f979b71a7b1ecda4f" +checksum = "43806561bc506d0c5d160643ad742e3161049ac01027b5e6d7524091fd401d86" dependencies = [ - "bitflags 2.4.0", + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", + "version_check", +] + +[[package]] +name = "rustix" +version = "0.38.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" +dependencies = [ + "bitflags 2.6.0", "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] @@ -1896,71 +3116,182 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99" dependencies = [ "log", - "ring", + "ring 0.16.20", "sct", "webpki", ] [[package]] name = "rustls" -version = "0.21.7" +version = "0.21.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" dependencies = [ "log", - "ring", - "rustls-webpki", + "ring 0.17.8", + "rustls-webpki 0.101.7", "sct", ] [[package]] -name = "rustls-pemfile" -version = "1.0.3" +name = "rustls" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" dependencies = [ - "base64 0.21.4", -] - -[[package]] -name = "rustls-webpki" -version = "0.101.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe" -dependencies = [ - "ring", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" - -[[package]] -name = "ryu" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" - -[[package]] -name = "salsa20" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0fbb5f676da676c260ba276a8f43a8dc67cf02d1438423aeb1c677a7212686" -dependencies = [ - "cipher 0.3.0", + "log", + "ring 0.17.8", + "rustls-pki-types", + "rustls-webpki 0.102.6", + "subtle", "zeroize", ] [[package]] -name = "samplerate" -version = "0.2.4" +name = "rustls" +version = "0.23.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e032b2b24715c4f982f483ea3abdb3c9ba444d9f63e87b2843d6f998f5ba2698" +checksum = "c58f8c84392efc0a126acce10fa59ff7b3d2ac06ab451a33f2741989b806b044" dependencies = [ - "libsamplerate-sys", + "once_cell", + "ring 0.17.8", + "rustls-pki-types", + "rustls-webpki 0.102.6", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" +dependencies = [ + "openssl-probe", + "rustls-pemfile 1.0.4", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-native-certs" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a88d6d420651b496bdd98684116959239430022a115c1240e6c3993be0b15fba" +dependencies = [ + "openssl-probe", + "rustls-pemfile 2.1.3", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.7", +] + +[[package]] +name = "rustls-pemfile" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "196fe16b00e106300d3e45ecfcb764fa292a535d7326a29a5875c579c7417425" +dependencies = [ + "base64 0.22.1", + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" + +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring 0.17.8", + "untrusted 0.9.0", +] + +[[package]] +name = "rustls-webpki" +version = "0.102.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e6b52d4fda176fd835fdc55a835d4a89b8499cad995885a21149d5ad62f852e" +dependencies = [ + "ring 0.17.8", + "rustls-pki-types", + "untrusted 0.9.0", +] + +[[package]] +name = "rustversion" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" + +[[package]] +name = "rusty_pool" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ed36cdb20de66d89a17ea04b8883fc7a386f2cf877aaedca5005583ce4876ff" +dependencies = [ + "crossbeam-channel", + "futures", + "futures-channel", + "futures-executor", + "num_cpus", +] + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "scoped-futures" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1473e24c637950c9bd38763220bea91ec3e095a89f672bbd7a10d03e77ba467" +dependencies = [ + "cfg-if", + "pin-utils", ] [[package]] @@ -1977,29 +3308,76 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" dependencies = [ - "ring", - "untrusted", + "ring 0.17.8", + "untrusted 0.9.0", +] + +[[package]] +name = "secrecy" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" +dependencies = [ + "serde", + "zeroize", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.6.0", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf" +dependencies = [ + "core-foundation-sys", + "libc", ] [[package]] name = "semver" -version = "1.0.19" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad977052201c6de01a8ef2aa3378c4bd23217a056337d1d6da40468d267a4fb0" +checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" +dependencies = [ + "serde", +] [[package]] name = "serde" -version = "1.0.188" +version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" dependencies = [ "serde_derive", ] +[[package]] +name = "serde-aux" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d2e8bfba469d06512e11e3311d4d051a4a387a5b42d010404fecf3200321c95" +dependencies = [ + "chrono", + "serde", + "serde_json", +] + [[package]] name = "serde-value" version = "0.7.0" @@ -2011,36 +3389,46 @@ dependencies = [ ] [[package]] -name = "serde_derive" -version = "1.0.188" +name = "serde_cow" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "1e7bbbec7196bfde255ab54b65e34087c0849629280028238e67ee25d6a4b7da" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.204" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] name = "serde_json" -version = "1.0.107" +version = "1.0.122" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" +checksum = "784b6203951c57ff748476b126ccb5e8e2959a5c19e5c617ab1956be3dbc68da" dependencies = [ "itoa", + "memchr", "ryu", "serde", ] [[package]] name = "serde_repr" -version = "0.1.16" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" +checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] @@ -2057,75 +3445,54 @@ dependencies = [ [[package]] name = "serenity" -version = "0.11.6" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d007dc45584ecc47e791f2a9a7cf17bf98ac386728106f111159c846d624be3f" +checksum = "880a04106592d0a8f5bdacb1d935889bfbccb4a14f7074984d9cd857235d34ac" dependencies = [ + "arrayvec", "async-trait", - "async-tungstenite", - "base64 0.13.1", - "bitflags 1.3.2", + "base64 0.22.1", + "bitflags 2.6.0", "bytes", - "cfg-if", + "chrono", "command_attr", "dashmap", "flate2", "futures", + "fxhash", "levenshtein", - "mime", "mime_guess", "parking_lot", "percent-encoding", - "reqwest", + "reqwest 0.11.27", + "secrecy", "serde", - "serde-value", + "serde_cow", "serde_json", "static_assertions", "time", "tokio", + "tokio-tungstenite 0.21.0", "tracing", "typemap_rev", + "typesize", "url", "uwl", ] [[package]] name = "serenity-voice-model" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be3aec8849ca2fde1e8a5dfbed96fbd68e9b5f4283fbe277d8694ce811d4952" +checksum = "593682f6155d07c8b331b3d1060f5aab7e6796caca9f2f66bd9e6855c880e06b" dependencies = [ - "bitflags 1.3.2", - "enum_primitive", + "bitflags 2.6.0", + "num-traits", "serde", "serde_json", "serde_repr", ] -[[package]] -name = "sha-1" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if", - "cpufeatures", - "digest 0.9.0", - "opaque-debug", -] - -[[package]] -name = "sha-1" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest 0.10.7", -] - [[package]] name = "sha1" version = "0.10.6" @@ -2134,7 +3501,18 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ "cfg-if", "cpufeatures", - "digest 0.10.7", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", ] [[package]] @@ -2148,9 +3526,9 @@ dependencies = [ [[package]] name = "sharded-slab" -version = "0.1.4" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" dependencies = [ "lazy_static", ] @@ -2162,14 +3540,79 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" [[package]] -name = "signal-hook-registry" -version = "1.4.1" +name = "shorthand" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +checksum = "474f77f985d8212610f170332eaf173e768404c0c1d4deb041f32c297cf18931" +dependencies = [ + "from_map", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "simd-json" +version = "0.13.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "570c430b3d902ea083097e853263ae782dfe40857d93db019a12356c8e8143fa" +dependencies = [ + "getrandom", + "halfbrown", + "lexical-core", + "ref-cast", + "serde", + "serde_json", + "simdutf8", + "value-trait", +] + +[[package]] +name = "simdutf8" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[package]] +name = "skeptic" +version = "0.13.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16d23b015676c90a0f01c197bfdc786c20342c73a0afdda9025adb0bc42940a8" +dependencies = [ + "bytecount", + "cargo_metadata", + "error-chain", + "glob", + "pulldown-cmark", + "tempfile", + "walkdir", +] + [[package]] name = "slab" version = "0.4.9" @@ -2181,61 +3624,65 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.11.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" -version = "0.4.9" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" dependencies = [ "libc", - "winapi", -] - -[[package]] -name = "socket2" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e" -dependencies = [ - "libc", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "songbird" -version = "0.3.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32f686a0fd771939de1da3e43cee45169fafe1595770b94680572cf18bdef288" +checksum = "338dd182f9f084f583c4c0db38588e28a34778ecec288208cf0b61c378ac90d1" dependencies = [ "async-trait", - "async-tungstenite", "audiopus", "byteorder", + "bytes", + "crypto_secretbox", "dashmap", "derivative", "discortp", "flume", "futures", + "nohash-hasher", + "once_cell", "parking_lot", "pin-project", "rand", + "reqwest 0.11.27", + "ringbuf", + "rubato", + "rusty_pool", "serde", + "serde-aux", "serde_json", "serenity", "serenity-voice-model", + "simd-json", + "socket2", + "stream_lib", "streamcatcher", + "symphonia", "symphonia-core", "tokio", + "tokio-tungstenite 0.21.0", + "tokio-util", "tracing", "tracing-futures", + "twilight-gateway", "typemap_rev", "url", - "uuid 0.8.2", - "xsalsa20poly1305", + "uuid", ] [[package]] @@ -2253,28 +3700,136 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spinning_top" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d96d2d1d716fb500937168cc09353ffdc7a012be8475ac7308e1bdf0e3923300" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "spoticord" -version = "2.1.2" +version = "2.2.0" dependencies = [ "anyhow", - "dotenv", - "env_logger 0.10.0", - "hex", - "lazy_static", - "librespot", + "dotenvy", + "env_logger", "log", - "protobuf", - "redis", - "reqwest", - "samplerate", - "serde", - "serde_json", + "poise", "serenity", "songbird", - "thiserror", + "spoticord_config", + "spoticord_database", + "spoticord_player", + "spoticord_session", + "spoticord_stats", + "spoticord_utils", "tokio", - "zerocopy 0.7.5", +] + +[[package]] +name = "spoticord_audio" +version = "2.2.0" +dependencies = [ + "librespot", + "songbird", + "tokio", + "zerocopy", +] + +[[package]] +name = "spoticord_config" +version = "2.2.0" +dependencies = [ + "lazy_static", + "rspotify", + "serenity", +] + +[[package]] +name = "spoticord_database" +version = "2.2.0" +dependencies = [ + "chrono", + "diesel", + "diesel-async", + "diesel_async_migrations", + "rand", + "rspotify", + "spoticord_config", + "thiserror", +] + +[[package]] +name = "spoticord_player" +version = "2.2.0" +dependencies = [ + "anyhow", + "hex", + "librespot", + "log", + "songbird", + "spoticord_audio", + "spoticord_utils", + "symphonia", + "tokio", +] + +[[package]] +name = "spoticord_session" +version = "2.2.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "librespot", + "log", + "poise", + "serenity", + "songbird", + "spoticord_config", + "spoticord_database", + "spoticord_player", + "spoticord_utils", + "tokio", +] + +[[package]] +name = "spoticord_stats" +version = "2.2.0" +dependencies = [ + "redis", +] + +[[package]] +name = "spoticord_utils" +version = "2.2.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "librespot", + "log", + "poise", +] + +[[package]] +name = "stable-vec" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1dff32a2ce087283bec878419027cebd888760d8760b2941ad0843531dc9ec8" +dependencies = [ + "no-std-compat 0.2.0", ] [[package]] @@ -2283,6 +3838,23 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "stream_lib" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa3f10eb5a7054e17abf61d310e4e29108187a847591c63c4c79b6a74898a5a7" +dependencies = [ + "bytes", + "futures-core", + "futures-util", + "hls_m3u8", + "patricia_tree", + "reqwest 0.11.27", + "tokio", + "tracing", + "url", +] + [[package]] name = "streamcatcher" version = "1.0.1" @@ -2295,16 +3867,136 @@ dependencies = [ ] [[package]] -name = "subtle" -version = "2.4.1" +name = "strength_reduce" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "530efb820d53b712f4e347916c5e7ed20deb76a4f0457943b3182fb889b06d2c" +dependencies = [ + "strum_macros 0.17.1", +] + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros 0.26.4", +] + +[[package]] +name = "strum_macros" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6e163a520367c465f59e0a61a23cfae3b10b6546d78b6f672a382be79f7110" +dependencies = [ + "heck 0.3.3", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.72", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symphonia" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "815c942ae7ee74737bb00f965fa5b5a2ac2ce7b6c01c0cc169bbeaf7abd5f5a9" +dependencies = [ + "lazy_static", + "symphonia-bundle-mp3", + "symphonia-codec-pcm", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-ogg", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c01c2aae70f0f1fb096b6f0ff112a930b1fb3626178fba3ae68b09dce71706d4" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f395a67057c2ebc5e84d7bb1be71cce1a7ba99f64e0f0f0e303a03f79116f89b" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a98765fb46a0a6732b007f7e2870c2129b6f78d87db7987e6533c8f164a9f30" +dependencies = [ + "log", + "symphonia-core", + "symphonia-utils-xiph", +] [[package]] name = "symphonia-core" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c73eb88fee79705268cc7b742c7bc93a7b76e092ab751d0833866970754142" +checksum = "798306779e3dc7d5231bd5691f5a813496dc79d3f56bf82e25789f2094e022c3" dependencies = [ "arrayvec", "bitflags 1.3.2", @@ -2313,6 +4005,40 @@ dependencies = [ "log", ] +[[package]] +name = "symphonia-format-ogg" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada3505789516bcf00fc1157c67729eded428b455c27ca370e41f4d785bfa931" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc622b9841a10089c5b18e99eb904f4341615d5aa55bbf4eedde1be721a4023c" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "484472580fa49991afda5f6550ece662237b00c6f562c7d9638d1b086ed010fe" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "syn" version = "1.0.109" @@ -2326,9 +4052,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.37" +version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7303ef2c05cd654186cb250d29049a24840ca25d2747c25c0381c8d9e2f582e8" +checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", @@ -2336,63 +4062,106 @@ dependencies = [ ] [[package]] -name = "tempfile" -version = "3.8.0" +name = "sync_wrapper" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + +[[package]] +name = "sync_wrapper" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" + +[[package]] +name = "sysinfo" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3" dependencies = [ "cfg-if", - "fastrand", - "redox_syscall 0.3.5", - "rustix", - "windows-sys", + "core-foundation-sys", + "libc", + "ntapi", + "once_cell", + "windows 0.52.0", ] [[package]] -name = "termcolor" -version = "1.3.0" +name = "system-configuration" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6093bad37da69aab9d123a8091e4be0aa4a03e4d601ec641c327398315f62b64" +checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" dependencies = [ - "winapi-util", + "bitflags 1.3.2", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tagptr" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" + +[[package]] +name = "tempfile" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fcd239983515c23a32fb82099f97d0b11b8c72f654ed659363a95c3dad7a53" +dependencies = [ + "cfg-if", + "fastrand", + "once_cell", + "rustix", + "windows-sys 0.52.0", ] [[package]] name = "thiserror" -version = "1.0.48" +version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6d7a740b8a666a7e828dd00da9c0dc290dff53154ea77ac109281de90589b7" +checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.48" +version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" +checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] name = "thread-id" -version = "4.2.0" +version = "4.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79474f573561cdc4871a0de34a51c92f7f5a56039113fbb5b9c9f96bdb756669" +checksum = "cfe8f25bbdd100db7e1d34acf7fd2dc59c4bf8f7483f505eaa7d4f12f76cc0ea" dependencies = [ "libc", - "redox_syscall 0.2.16", "winapi", ] [[package]] name = "thread_local" -version = "1.1.7" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" dependencies = [ "cfg-if", "once_cell", @@ -2400,12 +4169,16 @@ dependencies = [ [[package]] name = "time" -version = "0.3.29" +version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "426f806f4089c493dcac0d24c29c01e2c38baf8e30f1b716ee37e83d200b18fe" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", + "libc", + "num-conv", + "num_threads", + "powerfmt", "serde", "time-core", "time-macros", @@ -2419,18 +4192,19 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.15" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ + "num-conv", "time-core", ] [[package]] name = "tinyvec" -version = "1.6.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" dependencies = [ "tinyvec_macros", ] @@ -2443,32 +4217,57 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.32.0" +version = "1.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9" +checksum = "daa4fb1bc778bd6f04cbfc4bb2d06a7396a8f299dc33ea1900cedaa316f467b1" dependencies = [ "backtrace", "bytes", "libc", "mio", - "num_cpus", "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.4", + "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "tokio-macros" -version = "2.1.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", +] + +[[package]] +name = "tokio-postgres" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03adcf0147e203b6032c0b2d30be1415ba03bc348901f3ff1cc0df6a733e60c3" +dependencies = [ + "async-trait", + "byteorder", + "bytes", + "fallible-iterator", + "futures-channel", + "futures-util", + "log", + "parking_lot", + "percent-encoding", + "phf", + "pin-project-lite", + "postgres-protocol", + "postgres-types", + "rand", + "socket2", + "tokio", + "tokio-util", + "whoami", ] [[package]] @@ -2488,15 +4287,49 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls 0.21.7", + "rustls 0.21.12", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls 0.22.4", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" +dependencies = [ + "rustls 0.23.12", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-socks" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d4770b8024672c1101b3f6733eab95b18007dbe0847a8afe341fcf79e06043f" +dependencies = [ + "either", + "futures-util", + "thiserror", "tokio", ] [[package]] name = "tokio-stream" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" +checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af" dependencies = [ "futures-core", "pin-project-lite", @@ -2504,19 +4337,87 @@ dependencies = [ ] [[package]] -name = "tokio-util" -version = "0.7.9" +name = "tokio-tungstenite" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d68074620f57a0b21594d9735eb2e98ab38b17f80d3fcb189fca266771ca60d" +checksum = "54319c93411147bced34cb5609a80e0a8e44c5999c93903a81cd866630ec0bfd" +dependencies = [ + "futures-util", + "log", + "rustls 0.20.9", + "rustls-native-certs 0.6.3", + "tokio", + "tokio-rustls 0.23.4", + "tungstenite 0.18.0", + "webpki", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83b561d025642014097b66e6c1bb422783339e0909e4429cde4749d1990bc38" +dependencies = [ + "futures-util", + "log", + "rustls 0.22.4", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.25.0", + "tungstenite 0.21.0", + "webpki-roots 0.26.3", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6989540ced10490aaf14e6bad2e3d33728a2813310a0c71d1574304c49631cd" +dependencies = [ + "futures-util", + "log", + "rustls 0.23.12", + "rustls-native-certs 0.7.1", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.0", + "tungstenite 0.23.0", +] + +[[package]] +name = "tokio-util" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" dependencies = [ "bytes", "futures-core", "futures-sink", "pin-project-lite", "tokio", - "tracing", ] +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "futures-core", + "futures-util", + "pin-project", + "pin-project-lite", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" + [[package]] name = "tower-service" version = "0.3.2" @@ -2525,11 +4426,10 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.37" +version = "0.1.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ - "cfg-if", "log", "pin-project-lite", "tracing-attributes", @@ -2538,20 +4438,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.26" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] name = "tracing-core" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", "valuable", @@ -2569,20 +4469,20 @@ dependencies = [ [[package]] name = "tracing-log" -version = "0.1.3" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" dependencies = [ - "lazy_static", "log", + "once_cell", "tracing-core", ] [[package]] name = "tracing-subscriber" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30a651bc37f915e81f087d86e62a18eec5f79550c7faff886f7090b4ea757c77" +checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" dependencies = [ "matchers", "nu-ansi-term", @@ -2597,26 +4497,42 @@ dependencies = [ ] [[package]] -name = "try-lock" -version = "0.2.4" +name = "transpose" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + +[[package]] +name = "triomphe" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6631e42e10b40c0690bf92f404ebcfe6e1fdb480391d15f17cc8e96eeed5369" + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tungstenite" -version = "0.17.3" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e27992fd6a8c29ee7eef28fc78349aa244134e10ad447ce3b9f0ac0ed0fa4ce0" +checksum = "30ee6ab729cd4cf0fd55218530c4522ed30b7b6081752839b68fcec8d0960788" dependencies = [ "base64 0.13.1", "byteorder", "bytes", - "http", + "http 0.2.12", "httparse", "log", "rand", "rustls 0.20.9", - "sha-1 0.10.1", + "sha1", "thiserror", "url", "utf-8", @@ -2624,10 +4540,94 @@ dependencies = [ ] [[package]] -name = "typemap_rev" -version = "0.1.5" +name = "tungstenite" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5b74f0a24b5454580a79abb6994393b09adf0ab8070f15827cb666255de155" +checksum = "9ef1a641ea34f399a848dea702823bbecfb4c486f911735368f1f137cb8257e1" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http 1.1.0", + "httparse", + "log", + "rand", + "rustls 0.22.4", + "rustls-pki-types", + "sha1", + "thiserror", + "url", + "utf-8", +] + +[[package]] +name = "tungstenite" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e2ce1e47ed2994fd43b04c8f618008d4cabdd5ee34027cf14f9d918edd9c8" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http 1.1.0", + "httparse", + "log", + "rand", + "rustls 0.23.12", + "rustls-pki-types", + "sha1", + "thiserror", + "utf-8", +] + +[[package]] +name = "twilight-gateway" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30be5c7e2b13b4a59e0f93344c070c23404279a318a324eece1f4384ead47d86" +dependencies = [ + "bitflags 1.3.2", + "futures-util", + "rand", + "rustls 0.20.9", + "rustls-native-certs 0.6.3", + "serde", + "serde_json", + "tokio", + "tokio-tungstenite 0.18.0", + "tracing", + "twilight-gateway-queue", + "twilight-model", +] + +[[package]] +name = "twilight-gateway-queue" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3073747da8e1d09bc5383eed750451c9534021c8206a20092405b9855b3cb35a" +dependencies = [ + "tokio", + "tracing", +] + +[[package]] +name = "twilight-model" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "276bd50f4817b3b421395afac89f5d7b61fdfd0f00a28b2a7db983e4878b4a1a" +dependencies = [ + "bitflags 1.3.2", + "serde", + "serde-value", + "serde_repr", + "time", +] + +[[package]] +name = "typemap_rev" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74b08b0c1257381af16a5c3605254d529d3e7e109f3c62befc5d168968192998" [[package]] name = "typenum" @@ -2635,6 +4635,35 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "typesize" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb704842c709bc76f63e99e704cb208beeccca2abbabd0d9aec02e48ca1cee0f" +dependencies = [ + "chrono", + "dashmap", + "hashbrown", + "mini-moka", + "parking_lot", + "secrecy", + "serde_json", + "time", + "typesize-derive", + "url", +] + +[[package]] +name = "typesize-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "905e88c2a4cc27686bd57e495121d451f027e441388a67f773be729ad4be1ea8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", +] + [[package]] name = "unicase" version = "2.7.0" @@ -2646,9 +4675,9 @@ dependencies = [ [[package]] name = "unicode-bidi" -version = "0.3.13" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-ident" @@ -2658,26 +4687,38 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-normalization" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" dependencies = [ "tinyvec", ] [[package]] -name = "unicode-width" -version = "0.1.11" +name = "unicode-properties" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" +checksum = "e4259d9d4425d9f0661581b804cb85fe66a4c631cadd8f490d1c13a35d5d9291" + +[[package]] +name = "unicode-segmentation" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" + +[[package]] +name = "unicode-width" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" [[package]] name = "universal-hash" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f214e8f697e925001e66ec2c6e37a4ef93f0f78c2eed7814394e10c62025b05" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "generic-array", + "crypto-common", "subtle", ] @@ -2688,10 +4729,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" [[package]] -name = "url" -version = "2.4.1" +name = "untrusted" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" dependencies = [ "form_urlencoded", "idna", @@ -2706,21 +4753,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" [[package]] -name = "uuid" -version = "0.8.2" +name = "utf8parse" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" -dependencies = [ - "getrandom", -] +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.4.1" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" +checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" dependencies = [ "getrandom", + "rand", ] [[package]] @@ -2736,21 +4781,44 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" [[package]] -name = "vergen" -version = "3.2.0" +name = "value-trait" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7141e445af09c8919f1d5f8a20dae0b20c3b57a45dee0d5823c6ed5d237f15a" +checksum = "dad8db98c1e677797df21ba03fca7d3bf9bec3ca38db930954e4fe6e1ea27eb4" dependencies = [ - "bitflags 1.3.2", - "chrono", - "rustc_version", + "float-cmp", + "halfbrown", + "itoa", + "ryu", +] + +[[package]] +name = "vergen" +version = "8.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990d9ea5967266ea0ccf413a4aa5c42a93dbcfda9cb49a97de6931726b12566" +dependencies = [ + "anyhow", + "cfg-if", + "rustversion", + "time", ] [[package]] name = "version_check" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] [[package]] name = "want" @@ -2768,10 +4836,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] -name = "wasm-bindgen" -version = "0.2.87" +name = "wasite" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -2779,24 +4853,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.37" +version = "0.4.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" dependencies = [ "cfg-if", "js-sys", @@ -2806,9 +4880,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2816,28 +4890,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.72", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "wasm-streams" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4609d447824375f43e1ffbc051b50ad8f4b3ae8219680c94452ea05eb240ac7" +checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129" dependencies = [ "futures-util", "js-sys", @@ -2848,9 +4922,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.64" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" dependencies = [ "js-sys", "wasm-bindgen", @@ -2858,28 +4932,51 @@ dependencies = [ [[package]] name = "webpki" -version = "0.22.1" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0e74f82d49d545ad128049b7e88f6576df2da6b02e9ce565c6f533be576957e" +checksum = "ed63aea5ce73d0ff405984102c42de94fc55a6b75765d621c65262469b3c9b53" dependencies = [ - "ring", - "untrusted", + "ring 0.17.8", + "untrusted 0.9.0", ] [[package]] name = "webpki-roots" -version = "0.22.6" +version = "0.25.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c71e40d7d2c34a5106301fb632274ca37242cd0c9d3e64dbece371a40a2d87" -dependencies = [ - "webpki", -] +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" [[package]] name = "webpki-roots" -version = "0.25.2" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14247bb57be4f377dfb94c72830b8ce8fc6beac03cf4bf7b9732eadd414123fc" +checksum = "bd7c23921eeb1713a4e851530e9b9756e4fb0e89978582942612524cf09f01cd" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix", +] + +[[package]] +name = "whoami" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a44ab49fad634e88f55bf8f9bb3abd2f27d7204172a112c7c9987e01c1c94ea9" +dependencies = [ + "redox_syscall 0.4.1", + "wasite", + "web-sys", +] [[package]] name = "winapi" @@ -2899,11 +4996,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.6" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ - "winapi", + "windows-sys 0.59.0", ] [[package]] @@ -2918,7 +5015,26 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets", + "windows-targets 0.48.5", +] + +[[package]] +name = "windows" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +dependencies = [ + "windows-core", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.6", ] [[package]] @@ -2927,7 +5043,25 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets", + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", ] [[package]] @@ -2936,13 +5070,29 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -2951,42 +5101,90 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winreg" version = "0.50.0" @@ -2994,67 +5192,42 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" dependencies = [ "cfg-if", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] -name = "xsalsa20poly1305" -version = "0.8.0" +name = "winreg" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68bcb965d6c650091450b95cea12f07dcd299a01c15e2f9433b0813ea3c0886" +checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" dependencies = [ - "aead", - "poly1305", - "rand_core", - "salsa20", - "subtle", - "zeroize", + "cfg-if", + "windows-sys 0.48.0", ] [[package]] name = "zerocopy" -version = "0.6.4" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20707b61725734c595e840fb3704378a0cd2b9c74cc9e6e20724838fc6a1e2f9" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", - "zerocopy-derive 0.6.4", -] - -[[package]] -name = "zerocopy" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "870cdd4b8b867698aea998d95bcc06c1d75fe566267781ee6f5ae8c9c45a3930" -dependencies = [ - "byteorder", - "zerocopy-derive 0.7.5", + "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.6.4" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56097d5b91d711293a42be9289403896b68654625021732067eac7a4ca388a1f" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", -] - -[[package]] -name = "zerocopy-derive" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9c6f95fa5657518b36c6784ba7cdd89e8bdf9a16e58266085248bfb950860c5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.37", + "syn 2.0.72", ] [[package]] name = "zeroize" -version = "1.3.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4756f7db3f7b5574938c3eb1c117038b8e07f95ee6718c0efad4ac21508f1efd" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" diff --git a/Cargo.toml b/Cargo.toml index 6005d64..7fa4cfb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,36 +1,46 @@ [package] name = "spoticord" -version = "2.1.2" +version = "2.2.0" edition = "2021" -rust-version = "1.65.0" +rust-version = "1.75.0" [[bin]] name = "spoticord" path = "src/main.rs" +[workspace] +members = [ + "spoticord_audio", + "spoticord_config", + "spoticord_database", + "spoticord_player", + "spoticord_session", + "spoticord_utils", + "spoticord_stats", +] + [features] -stats = ["redis"] +default = ["stats"] +stats = ["spoticord_stats"] [dependencies] -anyhow = "1.0.75" -dotenv = "0.15.0" -env_logger = "0.10.0" -hex = "0.4.3" -lazy_static = "1.4.0" -librespot = { version = "0.4.2", default-features = false } -log = "0.4.20" -protobuf = "2.28.0" -redis = { version = "0.23.3", optional = true, default-features = false } -reqwest = { version = "0.11.20", default-features = false } -samplerate = "0.2.4" -serde = "1.0.188" -serde_json = "1.0.107" -serenity = { version = "0.11.6", features = ["framework", "cache", "standard_framework", "rustls_backend", "gateway"], default-features = false } -songbird = { version = "0.3.2", features = ["driver", "serenity-rustls"], default-features = false } -thiserror = "1.0.48" -tokio = { version = "1.32.0", features = ["rt", "full"] } -zerocopy = "0.7.5" +spoticord_config = { path = "./spoticord_config" } +spoticord_database = { path = "./spoticord_database" } +spoticord_player = { path = "./spoticord_player" } +spoticord_session = { path = "./spoticord_session" } +spoticord_utils = { path = "./spoticord_utils" } +spoticord_stats = { path = "./spoticord_stats", optional = true } + +anyhow = "1.0.86" +dotenvy = "0.15.7" +env_logger = "0.11.5" +log = "0.4.22" +poise = "0.6.1" +serenity = "0.12.2" +songbird = { version = "0.4.3", features = ["simd-json"] } +tokio = { version = "1.39.2", features = ["full"] } [profile.release] opt-level = 3 lto = true +strip = true diff --git a/Dockerfile b/Dockerfile index 38e72a2..4346d68 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,44 +1,47 @@ # Builder -FROM --platform=linux/amd64 rust:1.72.1-buster as builder +FROM --platform=linux/amd64 rust:1.79.0-buster AS builder WORKDIR /app # Add extra build dependencies here RUN apt-get update && apt-get install -yqq \ - cmake gcc-aarch64-linux-gnu binutils-aarch64-linux-gnu + cmake gcc-aarch64-linux-gnu binutils-aarch64-linux-gnu COPY . . -RUN rustup target add x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu +RUN rustup target add x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu -# Remove `--features=stats` if you want to deploy without stats collection -RUN cargo build --features=stats --release \ - --target=x86_64-unknown-linux-gnu --target=aarch64-unknown-linux-gnu +# Add `--no-default-features` if you don't want stats collection +RUN --mount=type=cache,target=/usr/local/cargo/registry \ + --mount=type=cache,target=/app/target \ + cargo build --release --target=x86_64-unknown-linux-gnu --target=aarch64-unknown-linux-gnu && \ + # Copy the executables outside of /target as it'll get unmounted after this RUN command + cp /app/target/x86_64-unknown-linux-gnu/release/spoticord /app/x86_64 && \ + cp /app/target/aarch64-unknown-linux-gnu/release/spoticord /app/aarch64 # Runtime FROM debian:buster-slim ARG TARGETPLATFORM -ENV TARGETPLATFORM=$TARGETPLATFORM +ENV TARGETPLATFORM=${TARGETPLATFORM} # Add extra runtime dependencies here -# RUN apt-get update && apt-get install -yqq --no-install-recommends \ -# openssl ca-certificates && rm -rf /var/lib/apt/lists/* +RUN apt update && apt install -y ca-certificates -# Copy spoticord binaries from builder to /tmp +# Copy spoticord binaries from builder to /tmp so we can dynamically use them COPY --from=builder \ - /app/target/x86_64-unknown-linux-gnu/release/spoticord /tmp/x86_64 + /app/x86_64 /tmp/x86_64 COPY --from=builder \ - /app/target/aarch64-unknown-linux-gnu/release/spoticord /tmp/aarch64 + /app/aarch64 /tmp/aarch64 -# Copy appropiate binary for target arch from /tmp -RUN if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \ - cp /tmp/x86_64 /usr/local/bin/spoticord; \ - elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then \ - cp /tmp/aarch64 /usr/local/bin/spoticord; \ +# Copy appropriate binary for target arch from /tmp +RUN if [ "${TARGETPLATFORM}" = "linux/amd64" ]; then \ + cp /tmp/x86_64 /usr/local/bin/spoticord; \ + elif [ "${TARGETPLATFORM}" = "linux/arm64" ]; then \ + cp /tmp/aarch64 /usr/local/bin/spoticord; \ fi # Delete unused binaries RUN rm -rvf /tmp/x86_64 /tmp/aarch64 -ENTRYPOINT [ "/usr/local/bin/spoticord" ] +ENTRYPOINT [ "/usr/local/bin/spoticord" ] \ No newline at end of file diff --git a/LICENSE b/LICENSE index f288702..0ad25db 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies @@ -7,17 +7,15 @@ Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to +our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. +software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you @@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. The precise terms and conditions for copying, distribution and modification follow. @@ -72,7 +60,7 @@ modification follow. 0. Definitions. - "This License" refers to version 3 of the GNU General Public License. + "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. @@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - 13. Use with the GNU Affero General Public License. + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single +under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General +Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published +GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's +versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. @@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + GNU Affero General Public License for more details. - You should have received a copy of the GNU General Public License + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see +For more information on this, and how to apply and follow the GNU AGPL, see . - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/README.md b/README.md index 03eb869..7fb76c4 100644 --- a/README.md +++ b/README.md @@ -5,34 +5,46 @@ Spoticord is built on top of [librespot](https://github.com/librespot-org/libres Being built on top of rust, Spoticord is relatively lightweight and can run on low-spec hardware. ## How to use + ### Official bot + Spoticord is being hosted as an official bot. You can find more info about how to use this bot over at [the Spoticord website](https://spoticord.com/). ### Environment variables + Spoticord uses environment variables to configure itself. The following variables are required: + - `DISCORD_TOKEN`: The Discord bot token used for authenticating with Discord. -- `DATABASE_URL`: The base URL of the database API used for storing user data. This base URL must point to an instance of [the Spoticord Database API](https://github.com/SpoticordMusic/spoticord-database). -- `SPOTICORD_ACCOUNTS_URL`: The base URL of the accounts frontend used for authenticating with Spotify. This base URL must point to an instance of [the Spoticord Accounts frontend](https://github.com/SpoticordMusic/spoticord-accounts). +- `DATABASE_URL`: The URL of the postgres database where spoticord will store user data. Currently only postgresql databases are supported. +- `LINK_URL`: The base URL of the account-linking frontend used for authenticating users with Spotify. This base URL must point to an instance of [the Spoticord Link frontend](https://github.com/SpoticordMusic/spoticord-link). +- `SPOTIFY_CLIENT_ID`: The Spotify Client ID for the Spotify application that is used for Spoticord. This will be used for refreshing tokens. +- `SPOTIFY_CLIENT_SECRET`: The Spotify Client Secret for the Spotify application that is used for Spoticord. This will be used for refreshing tokens. Additionally you can configure the following variables: -- `GUILD_ID`: The ID of the Discord server where this bot will create commands for. This is used during testing to prevent the bot from creating slash commands in other servers, as well as getting the commands quicker. This variable is optional, and if not set, the bot will create commands in all servers it is in (this may take up to 15 minutes). + +- `GUILD_ID`: The ID of the Discord server where this bot will create commands for. This is used during testing to prevent the bot from creating slash commands in other servers, as well as generally being faster than global command propagation. This variable is required when running a debug build, and ignored when running a release build. - `KV_URL`: The connection URL of a redis-server instance used for storing realtime data. This variable is required when compiling with the `stats` feature. #### Providing environment variables + You can provide environment variables in a `.env` file at the root of the working directory of Spoticord. You can also provide environment variables the normal way, e.g. the command line, using `export` (or `set` for Windows) or using docker. Environment variables set this way take precedence over those in the `.env` file (if one exists). # Compiling + For information about how to compile Spoticord from source, check out [COMPILING.md](COMPILING.md). # Contributing + For information about how to contribute to Spoticord, check out [CONTRIBUTING.md](CONTRIBUTING.md). # Contact + ![Discord Shield](https://discordapp.com/api/guilds/779292533053456404/widget.png?style=shield) If you have any questions, feel free to join the [Spoticord Discord server](https://discord.gg/wRCyhVqBZ5)! # License -Spoticord is licensed under the [GNU General Public License v3.0](LICENSE). + +Spoticord is licensed under the [GNU Affero General Public License v3.0](LICENSE). diff --git a/spoticord_audio/Cargo.toml b/spoticord_audio/Cargo.toml new file mode 100644 index 0000000..8f27a75 --- /dev/null +++ b/spoticord_audio/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "spoticord_audio" +version = "2.2.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +librespot = { git = "https://github.com/SpoticordMusic/librespot.git", version = "0.5.0-dev", default-features = false } +songbird = { version = "0.4.3", features = ["simd-json"] } +tokio = { version = "1.39.2", features = ["sync"], default-features = false } +zerocopy = "0.7.35" diff --git a/spoticord_audio/src/lib.rs b/spoticord_audio/src/lib.rs new file mode 100644 index 0000000..d6788e0 --- /dev/null +++ b/spoticord_audio/src/lib.rs @@ -0,0 +1,2 @@ +pub mod sink; +pub mod stream; diff --git a/spoticord_audio/src/sink.rs b/spoticord_audio/src/sink.rs new file mode 100644 index 0000000..23187e9 --- /dev/null +++ b/spoticord_audio/src/sink.rs @@ -0,0 +1,68 @@ +use crate::stream::Stream; +use librespot::playback::audio_backend::{Sink, SinkAsBytes, SinkError, SinkResult}; +use librespot::playback::convert::Converter; +use librespot::playback::decoder::AudioPacket; +use std::io::Write; +use tokio::sync::mpsc::UnboundedSender; + +pub enum SinkEvent { + Start, + Stop, +} + +pub struct StreamSink { + stream: Stream, + sender: UnboundedSender, +} + +impl StreamSink { + pub fn new(stream: Stream, sender: UnboundedSender) -> Self { + Self { stream, sender } + } +} + +impl Sink for StreamSink { + fn start(&mut self) -> SinkResult<()> { + if let Err(_why) = self.sender.send(SinkEvent::Start) { + // WARNING: Returning an error causes librespot-playback to exit the process with status 1 + + // return Err(SinkError::ConnectionRefused(_why.to_string())); + } + + Ok(()) + } + + fn stop(&mut self) -> SinkResult<()> { + if let Err(_why) = self.sender.send(SinkEvent::Stop) { + // WARNING: Returning an error causes librespot-playback to exit the process with status 1 + + // return Err(SinkError::ConnectionRefused(_why.to_string())); + } + + self.stream.flush().ok(); + + Ok(()) + } + + fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> { + use zerocopy::AsBytes; + + let AudioPacket::Samples(samples) = packet else { + return Ok(()); + }; + + self.write_bytes(converter.f64_to_f32(&samples).as_bytes())?; + + Ok(()) + } +} + +impl SinkAsBytes for StreamSink { + fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> { + self.stream + .write_all(data) + .map_err(|why| SinkError::OnWrite(why.to_string()))?; + + Ok(()) + } +} diff --git a/spoticord_audio/src/stream.rs b/spoticord_audio/src/stream.rs new file mode 100644 index 0000000..a60cf01 --- /dev/null +++ b/spoticord_audio/src/stream.rs @@ -0,0 +1,88 @@ +use std::{ + io::{Read, Seek, Write}, + sync::{Arc, Condvar, Mutex}, +}; + +use songbird::input::core::io::MediaSource; + +/// The lower the value, the less latency +/// +/// Too low of a value results in jittery audio +const BUFFER_SIZE: usize = 64 * 1024; + +#[derive(Clone, Default)] +pub struct Stream { + inner: Arc<(Mutex>, Condvar)>, +} + +impl Stream { + pub fn new() -> Self { + Self::default() + } +} + +impl Read for Stream { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let (mutex, condvar) = &*self.inner; + let mut buffer = mutex.lock().expect("Mutex was poisoned"); + + // Prevent Discord jitter by filling buffer with zeroes if we don't have any audio + // (i.e. when you skip too far ahead in a song which hasn't been downloaded yet) + if buffer.is_empty() { + buf.fill(0); + condvar.notify_all(); + + return Ok(buf.len()); + } + + let max_read = usize::min(buf.len(), buffer.len()); + + buf[0..max_read].copy_from_slice(&buffer[0..max_read]); + buffer.drain(0..max_read); + condvar.notify_all(); + + Ok(max_read) + } +} + +impl Write for Stream { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let (mutex, condvar) = &*self.inner; + let mut buffer = mutex.lock().expect("Mutex was poisoned"); + + while buffer.len() + buf.len() > BUFFER_SIZE { + buffer = condvar.wait(buffer).expect("Mutex was poisoned"); + } + + buffer.extend_from_slice(buf); + condvar.notify_all(); + + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + let (mutex, condvar) = &*self.inner; + let mut buffer = mutex.lock().expect("Mutex was poisoned"); + + buffer.clear(); + condvar.notify_all(); + + Ok(()) + } +} + +impl Seek for Stream { + fn seek(&mut self, _: std::io::SeekFrom) -> std::io::Result { + Ok(0) + } +} + +impl MediaSource for Stream { + fn byte_len(&self) -> Option { + None + } + + fn is_seekable(&self) -> bool { + false + } +} diff --git a/spoticord_config/Cargo.toml b/spoticord_config/Cargo.toml new file mode 100644 index 0000000..86879c1 --- /dev/null +++ b/spoticord_config/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "spoticord_config" +version = "2.2.0" +edition = "2021" + +[dependencies] +lazy_static = "1.5.0" +rspotify = { version = "0.13.2", default-features = false, features = [ + "client-reqwest", + "reqwest-rustls-tls", +] } +serenity = "0.12.2" diff --git a/spoticord_config/README.md b/spoticord_config/README.md new file mode 100644 index 0000000..eb8ff65 --- /dev/null +++ b/spoticord_config/README.md @@ -0,0 +1,3 @@ +# Spoticord: Configuration + +This module contains configuration items for spoticord, like environment variables. diff --git a/spoticord_config/src/env.rs b/spoticord_config/src/env.rs new file mode 100644 index 0000000..4aecea4 --- /dev/null +++ b/spoticord_config/src/env.rs @@ -0,0 +1,14 @@ +use lazy_static::lazy_static; + +lazy_static! { + pub static ref DISCORD_TOKEN: String = + std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN environment variable"); + pub static ref DATABASE_URL: String = + std::env::var("DATABASE_URL").expect("missing DATABASE_URL environment variable"); + pub static ref LINK_URL: String = + std::env::var("LINK_URL").expect("missing LINK_URL environment variable"); + pub static ref SPOTIFY_CLIENT_ID: String = + std::env::var("SPOTIFY_CLIENT_ID").expect("missing SPOTIFY_CLIENT_ID environment variable"); + pub static ref SPOTIFY_CLIENT_SECRET: String = std::env::var("SPOTIFY_CLIENT_SECRET") + .expect("missing SPOTIFY_CLIENT_SECRET environment variable"); +} diff --git a/spoticord_config/src/lib.rs b/spoticord_config/src/lib.rs new file mode 100644 index 0000000..e711e0f --- /dev/null +++ b/spoticord_config/src/lib.rs @@ -0,0 +1,44 @@ +mod env; + +use rspotify::{AuthCodeSpotify, Config, Credentials, OAuth, Token}; +use serenity::all::GatewayIntents; + +#[cfg(not(debug_assertions))] +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +#[cfg(debug_assertions)] +pub const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "-dev"); + +/// The "listening to" message that shows up under the Spoticord bot user +pub const MOTD: &str = "some good 'ol music"; + +/// The time it takes (in seconds) for Spoticord to disconnect when no music is being played +pub const DISCONNECT_TIME: u64 = 5 * 60; + +pub fn discord_token() -> &'static str { + &env::DISCORD_TOKEN +} + +pub fn discord_intents() -> GatewayIntents { + GatewayIntents::GUILDS | GatewayIntents::GUILD_VOICE_STATES +} + +pub fn database_url() -> &'static str { + &env::DATABASE_URL +} + +pub fn link_url() -> &'static str { + &env::LINK_URL +} + +pub fn get_spotify(token: Token) -> AuthCodeSpotify { + AuthCodeSpotify::from_token_with_config( + token, + Credentials { + id: env::SPOTIFY_CLIENT_ID.to_string(), + secret: Some(env::SPOTIFY_CLIENT_SECRET.to_string()), + }, + OAuth::default(), + Config::default(), + ) +} diff --git a/spoticord_database/Cargo.toml b/spoticord_database/Cargo.toml new file mode 100644 index 0000000..eeee740 --- /dev/null +++ b/spoticord_database/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "spoticord_database" +version = "2.2.0" +edition = "2021" + +[dependencies] +spoticord_config = { path = "../spoticord_config" } + +diesel = { version = "2.1.6", features = ["chrono"] } +diesel-async = { version = "0.4.1", features = ["deadpool", "postgres"] } +rspotify = { version = "0.13.2", default-features = false, features = [ + "client-reqwest", + "reqwest-rustls-tls", +] } +chrono = "0.4.38" +thiserror = "1.0.63" +rand = "0.8.5" +diesel_async_migrations = "0.12.0" diff --git a/spoticord_database/diesel.toml b/spoticord_database/diesel.toml new file mode 100644 index 0000000..a0d61bf --- /dev/null +++ b/spoticord_database/diesel.toml @@ -0,0 +1,9 @@ +# For documentation on how to configure this file, +# see https://diesel.rs/guides/configuring-diesel-cli + +[print_schema] +file = "src/schema.rs" +custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] + +[migrations_directory] +dir = "migrations" diff --git a/spoticord_database/migrations/.keep b/spoticord_database/migrations/.keep new file mode 100644 index 0000000..e69de29 diff --git a/spoticord_database/migrations/00000000000000_diesel_initial_setup/down.sql b/spoticord_database/migrations/00000000000000_diesel_initial_setup/down.sql new file mode 100644 index 0000000..a9f5260 --- /dev/null +++ b/spoticord_database/migrations/00000000000000_diesel_initial_setup/down.sql @@ -0,0 +1,6 @@ +-- This file was automatically created by Diesel to setup helper functions +-- and other internal bookkeeping. This file is safe to edit, any future +-- changes will be added to existing projects as new migrations. + +DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); +DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/spoticord_database/migrations/00000000000000_diesel_initial_setup/up.sql b/spoticord_database/migrations/00000000000000_diesel_initial_setup/up.sql new file mode 100644 index 0000000..d68895b --- /dev/null +++ b/spoticord_database/migrations/00000000000000_diesel_initial_setup/up.sql @@ -0,0 +1,36 @@ +-- This file was automatically created by Diesel to setup helper functions +-- and other internal bookkeeping. This file is safe to edit, any future +-- changes will be added to existing projects as new migrations. + + + + +-- Sets up a trigger for the given table to automatically set a column called +-- `updated_at` whenever the row is modified (unless `updated_at` was included +-- in the modified columns) +-- +-- # Example +-- +-- ```sql +-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); +-- +-- SELECT diesel_manage_updated_at('users'); +-- ``` +CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ +BEGIN + EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s + FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ +BEGIN + IF ( + NEW IS DISTINCT FROM OLD AND + NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at + ) THEN + NEW.updated_at := current_timestamp; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; diff --git a/spoticord_database/migrations/2024-06-17-090114_initial_setup/down.sql b/spoticord_database/migrations/2024-06-17-090114_initial_setup/down.sql new file mode 100644 index 0000000..ac0e43b --- /dev/null +++ b/spoticord_database/migrations/2024-06-17-090114_initial_setup/down.sql @@ -0,0 +1,9 @@ +-- Tables + +DROP TABLE "account"; +DROP TABLE "link_request"; +DROP TABLE "user"; + +-- Trigger functions + +DROP FUNCTION IF EXISTS update_last_updated_column(); \ No newline at end of file diff --git a/spoticord_database/migrations/2024-06-17-090114_initial_setup/up.sql b/spoticord_database/migrations/2024-06-17-090114_initial_setup/up.sql new file mode 100644 index 0000000..aace681 --- /dev/null +++ b/spoticord_database/migrations/2024-06-17-090114_initial_setup/up.sql @@ -0,0 +1,43 @@ +-- Trigger functions + +CREATE OR REPLACE FUNCTION update_last_updated_column() +RETURNS TRIGGER AS $$ +BEGIN + NEW.last_updated = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Tables + +CREATE TABLE "user" ( + id VARCHAR PRIMARY KEY, + device_name VARCHAR(32) NOT NULL DEFAULT 'Spoticord' +); + +CREATE TABLE "link_request" ( + token TEXT PRIMARY KEY, + user_id TEXT UNIQUE NOT NULL, + expires TIMESTAMP NOT NULL, + + CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES "user" (id) +); + +CREATE TABLE "account" ( + user_id VARCHAR PRIMARY KEY, + username VARCHAR(64) NOT NULL, + access_token VARCHAR(1024) NOT NULL, + refresh_token VARCHAR(1024) NOT NULL, + session_token VARCHAR(1024), + expires TIMESTAMP NOT NULL, + last_updated TIMESTAMP NOT NULL DEFAULT NOW(), + + CONSTRAINT fk_account_user_id FOREIGN KEY (user_id) REFERENCES "user" (id) +); + +-- Triggers + +CREATE TRIGGER update_last_updated_column +BEFORE UPDATE ON "account" +FOR EACH ROW +EXECUTE FUNCTION update_last_updated_column(); \ No newline at end of file diff --git a/spoticord_database/src/error.rs b/spoticord_database/src/error.rs new file mode 100644 index 0000000..c083975 --- /dev/null +++ b/spoticord_database/src/error.rs @@ -0,0 +1,43 @@ +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum DatabaseError { + #[error(transparent)] + Diesel(diesel::result::Error), + + #[error(transparent)] + PoolBuild(#[from] diesel_async::pooled_connection::deadpool::BuildError), + + #[error(transparent)] + Pool(#[from] diesel_async::pooled_connection::deadpool::PoolError), + + #[error("Failed to refresh token")] + RefreshTokenFailure, + + #[error("The requested record was not found")] + NotFound, +} + +impl From for DatabaseError { + fn from(value: diesel::result::Error) -> Self { + match value { + diesel::result::Error::NotFound => Self::NotFound, + other => Self::Diesel(other), + } + } +} + +pub type Result = ::core::result::Result; + +pub trait DatabaseResultExt { + fn optional(self) -> Result>; +} + +impl DatabaseResultExt for Result { + fn optional(self) -> Result> { + match self { + Err(DatabaseError::NotFound) => Ok(None), + other => other.map(Some), + } + } +} diff --git a/spoticord_database/src/lib.rs b/spoticord_database/src/lib.rs new file mode 100644 index 0000000..fc40f2b --- /dev/null +++ b/spoticord_database/src/lib.rs @@ -0,0 +1,234 @@ +pub mod error; + +mod migrations; +mod models; +mod schema; + +use std::sync::Arc; + +use chrono::{Duration, Utc}; +use diesel::prelude::*; +use diesel_async::{ + pooled_connection::{deadpool::Pool, AsyncDieselConnectionManager}, + AsyncPgConnection, RunQueryDsl, +}; +use error::*; +use models::{Account, LinkRequest, User}; +use rand::{distributions::Alphanumeric, Rng}; +use rspotify::{clients::BaseClient, Token}; + +#[derive(Clone)] +pub struct Database(Arc>); + +impl Database { + pub async fn connect() -> Result { + let config = AsyncDieselConnectionManager::::new( + spoticord_config::database_url(), + ); + let pool = Pool::builder(config).build()?; + + let mut conn = pool.get().await?; + migrations::run_migrations(&mut conn).await?; + + Ok(Self(Arc::new(pool))) + } + + // User operations + + pub async fn get_user(&self, user_id: impl AsRef) -> Result { + use schema::user::dsl::*; + + let mut connection = self.0.get().await?; + let result = user + .filter(id.eq(user_id.as_ref())) + .select(User::as_select()) + .first(&mut connection) + .await?; + + Ok(result) + } + + pub async fn create_user(&self, user_id: impl AsRef) -> Result { + use schema::user::dsl::*; + + let mut connection = self.0.get().await?; + let result = diesel::insert_into(user) + .values(id.eq(user_id.as_ref())) + .returning(User::as_returning()) + .get_result(&mut connection) + .await?; + + Ok(result) + } + + pub async fn delete_user(&self, user_id: impl AsRef) -> Result<()> { + use schema::user::dsl::*; + + let mut connection = self.0.get().await?; + diesel::delete(user) + .filter(id.eq(user_id.as_ref())) + .execute(&mut connection) + .await?; + + Ok(()) + } + + pub async fn get_or_create_user(&self, user_id: impl AsRef) -> Result { + match self.get_user(&user_id).await { + Err(DatabaseError::NotFound) => self.create_user(user_id).await, + result => result, + } + } + + pub async fn update_device_name( + &self, + user_id: impl AsRef, + _device_name: impl AsRef, + ) -> Result<()> { + use schema::user::dsl::*; + + let mut connection = self.0.get().await?; + diesel::update(user) + .filter(id.eq(user_id.as_ref())) + .set(device_name.eq(_device_name.as_ref())) + .execute(&mut connection) + .await?; + + Ok(()) + } + + // Account operations + + pub async fn get_account(&self, _user_id: impl AsRef) -> Result { + use schema::account::dsl::*; + + let mut connection = self.0.get().await?; + let result = account + .select(Account::as_select()) + .filter(user_id.eq(_user_id.as_ref())) + .first(&mut connection) + .await?; + + Ok(result) + } + + pub async fn delete_account(&self, _user_id: impl AsRef) -> Result { + use schema::account::dsl::*; + + let mut connection = self.0.get().await?; + let affected = diesel::delete(account) + .filter(user_id.eq(_user_id.as_ref())) + .execute(&mut connection) + .await?; + + Ok(affected) + } + + pub async fn update_session_token( + &self, + _user_id: impl AsRef, + _session_token: impl AsRef, + ) -> Result<()> { + use schema::account::dsl::*; + + let mut connection = self.0.get().await?; + diesel::update(account) + .filter(user_id.eq(_user_id.as_ref())) + .set(session_token.eq(_session_token.as_ref())) + .execute(&mut connection) + .await?; + + Ok(()) + } + + // Request operations + + pub async fn get_request(&self, _user_id: impl AsRef) -> Result { + use schema::link_request::dsl::*; + + let mut connection = self.0.get().await?; + let result = link_request + .select(LinkRequest::as_select()) + .filter(user_id.eq(_user_id.as_ref())) + .first(&mut connection) + .await?; + + Ok(result) + } + + /// Create a new link request that expires after an hour + pub async fn create_request(&self, _user_id: impl AsRef) -> Result { + use schema::link_request::dsl::*; + + let mut connection = self.0.get().await?; + let _token: String = rand::thread_rng() + .sample_iter(&Alphanumeric) + .take(64) + .map(char::from) + .collect(); + let _expires = (Utc::now() + Duration::hours(1)).naive_utc(); + + let request = diesel::insert_into(link_request) + .values(( + user_id.eq(_user_id.as_ref()), + token.eq(&_token), + expires.eq(_expires), + )) + .on_conflict(user_id) + .do_update() + .set((token.eq(&_token), expires.eq(_expires))) + .returning(LinkRequest::as_returning()) + .get_result(&mut connection) + .await?; + + Ok(request) + } + + // Special operations + + /// Retrieve a user's Spotify access token. This token, if expired, will automatically be refreshed + /// using the refresh token stored in the database. If this succeeds, the access token will be updated. + pub async fn get_access_token(&self, _user_id: impl AsRef) -> Result { + use schema::account::dsl::*; + + let mut connection = self.0.get().await?; + let mut result: Account = account + .filter(user_id.eq(_user_id.as_ref())) + .select(Account::as_select()) + .first(&mut connection) + .await?; + + // If the token has expired, refresh it automatically + if result.expired_offset(Duration::minutes(1)) { + let spotify = spoticord_config::get_spotify(Token { + refresh_token: Some(result.refresh_token), + ..Default::default() + }); + + let token = match spotify.refetch_token().await { + Ok(Some(token)) => token, + _ => { + self.delete_account(_user_id.as_ref()).await.ok(); + + return Err(DatabaseError::RefreshTokenFailure); + } + }; + + result = diesel::update(account) + .filter(user_id.eq(_user_id.as_ref())) + .set(( + access_token.eq(&token.access_token), + refresh_token.eq(token.refresh_token.as_deref().unwrap_or("")), + expires.eq(&token + .expires_at + .expect("token expires_at is none, we broke time") + .naive_utc()), + )) + .returning(Account::as_returning()) + .get_result(&mut connection) + .await?; + } + + Ok(result.access_token) + } +} diff --git a/spoticord_database/src/migrations.rs b/spoticord_database/src/migrations.rs new file mode 100644 index 0000000..58cf0b4 --- /dev/null +++ b/spoticord_database/src/migrations.rs @@ -0,0 +1,13 @@ +use diesel_async::AsyncConnection; +use diesel_async_migrations::{embed_migrations, EmbeddedMigrations}; + +pub async fn run_migrations(connection: &mut C) -> Result<(), diesel::result::Error> +where + C: AsyncConnection + 'static + Send, +{ + let migrations: EmbeddedMigrations = embed_migrations!(); + + migrations.run_pending_migrations(connection).await?; + + Ok(()) +} diff --git a/spoticord_database/src/models.rs b/spoticord_database/src/models.rs new file mode 100644 index 0000000..92e20f7 --- /dev/null +++ b/spoticord_database/src/models.rs @@ -0,0 +1,51 @@ +use chrono::Utc; +use diesel::prelude::*; + +#[derive(Queryable, Selectable, Debug)] +#[diesel(table_name = super::schema::user)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct User { + pub id: String, + pub device_name: String, +} + +#[derive(Queryable, Selectable, Debug)] +#[diesel(table_name = super::schema::account)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct Account { + pub user_id: String, + pub username: String, + pub access_token: String, + pub refresh_token: String, + pub session_token: Option, + pub expires: chrono::NaiveDateTime, +} + +impl Account { + pub fn expired(&self) -> bool { + Utc::now().naive_utc() > self.expires + } + + pub fn expired_offset(&self, offset: chrono::Duration) -> bool { + Utc::now().naive_utc() > self.expires - offset + } +} + +#[derive(Queryable, Selectable, Debug)] +#[diesel(table_name = super::schema::link_request)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct LinkRequest { + pub token: String, + pub user_id: String, + pub expires: chrono::NaiveDateTime, +} + +impl LinkRequest { + pub fn expired(&self) -> bool { + Utc::now().naive_utc() > self.expires + } + + pub fn expired_offset(&self, offset: chrono::Duration) -> bool { + Utc::now().naive_utc() > self.expires - offset + } +} diff --git a/spoticord_database/src/schema.rs b/spoticord_database/src/schema.rs new file mode 100644 index 0000000..835fe59 --- /dev/null +++ b/spoticord_database/src/schema.rs @@ -0,0 +1,42 @@ +// @generated automatically by Diesel CLI. + +diesel::table! { + account (user_id) { + user_id -> Varchar, + #[max_length = 64] + username -> Varchar, + #[max_length = 1024] + access_token -> Varchar, + #[max_length = 1024] + refresh_token -> Varchar, + #[max_length = 1024] + session_token -> Nullable, + expires -> Timestamp, + last_updated -> Timestamp, + } +} + +diesel::table! { + link_request (token) { + token -> Text, + user_id -> Text, + expires -> Timestamp, + } +} + +diesel::table! { + user (id) { + id -> Varchar, + #[max_length = 32] + device_name -> Varchar, + } +} + +diesel::joinable!(account -> user (user_id)); +diesel::joinable!(link_request -> user (user_id)); + +diesel::allow_tables_to_appear_in_same_query!( + account, + link_request, + user, +); diff --git a/spoticord_player/Cargo.toml b/spoticord_player/Cargo.toml new file mode 100644 index 0000000..624e910 --- /dev/null +++ b/spoticord_player/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "spoticord_player" +version = "2.2.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +spoticord_audio = { path = "../spoticord_audio" } +spoticord_utils = { path = "../spoticord_utils" } + +librespot = { git = "https://github.com/SpoticordMusic/librespot.git", version = "0.5.0-dev", default-features = false } +songbird = { version = "0.4.3", features = ["simd-json"] } +tokio = { version = "1.39.2", features = ["full"] } +anyhow = "1.0.86" +log = "0.4.22" +symphonia = { version = "0.5.4", default-features = false, features = ["pcm"] } +hex = "0.4.3" diff --git a/spoticord_player/src/info.rs b/spoticord_player/src/info.rs new file mode 100644 index 0000000..62bf692 --- /dev/null +++ b/spoticord_player/src/info.rs @@ -0,0 +1,126 @@ +use std::collections::HashSet; + +use librespot::{ + core::SpotifyId, + metadata::{ + artist::ArtistsWithRole, + audio::{AudioItem, UniqueFields}, + }, +}; + +#[derive(Debug, Clone)] +pub struct PlaybackInfo { + audio_item: AudioItem, + + updated_at: u128, + position: u32, + playing: bool, +} + +impl PlaybackInfo { + pub fn new(audio_item: AudioItem, position: u32, playing: bool) -> Self { + Self { + audio_item, + + updated_at: spoticord_utils::get_time(), + position, + playing, + } + } + + pub fn track_id(&self) -> SpotifyId { + self.audio_item.track_id + } + + pub fn track_id_string(&self) -> String { + self.audio_item + .track_id + .to_base62() + .expect("invalid spotify id") + } + + pub fn name(&self) -> String { + self.audio_item.name.clone() + } + + pub fn artists(&self) -> Option { + let artists = match &self.audio_item.unique_fields { + UniqueFields::Track { artists, .. } => artists.clone().0, + UniqueFields::Episode { .. } => None?, + }; + + let mut seen = HashSet::new(); + let artists = artists + .into_iter() + .filter(|item| seen.insert(item.id)) + .collect(); + + Some(ArtistsWithRole(artists)) + } + + pub fn show_name(&self) -> Option { + match &self.audio_item.unique_fields { + UniqueFields::Episode { show_name, .. } => Some(show_name.to_string()), + UniqueFields::Track { .. } => None, + } + } + + pub fn thumbnail(&self) -> String { + self.audio_item + .covers + .first() + .expect("spotify track missing cover image") + .url + .to_string() + } + + pub fn duration(&self) -> u32 { + self.audio_item.duration_ms + } + + pub fn url(&self) -> String { + match &self.audio_item.unique_fields { + UniqueFields::Episode { .. } => format!( + "https://open.spotify.com/episode/{}", + self.track_id_string() + ), + UniqueFields::Track { .. } => { + format!("https://open.spotify.com/track/{}", self.track_id_string()) + } + } + } + + /// Get the current playback position, which accounts for time that may have passed since this struct was last updated + pub fn current_position(&self) -> u32 { + if self.playing { + let now = spoticord_utils::get_time(); + let diff = now - self.updated_at; + + self.position + diff as u32 + } else { + self.position + } + } + + pub fn playing(&self) -> bool { + self.playing + } + + pub fn update_playback(&mut self, position: u32, playing: bool) { + self.position = position; + self.playing = playing; + self.updated_at = spoticord_utils::get_time(); + } + + pub fn update_track(&mut self, audio_item: AudioItem) { + self.audio_item = audio_item; + } + + pub fn is_episode(&self) -> bool { + matches!(self.audio_item.unique_fields, UniqueFields::Episode { .. }) + } + + pub fn is_track(&self) -> bool { + matches!(self.audio_item.unique_fields, UniqueFields::Track { .. }) + } +} diff --git a/spoticord_player/src/lib.rs b/spoticord_player/src/lib.rs new file mode 100644 index 0000000..8c57bfe --- /dev/null +++ b/spoticord_player/src/lib.rs @@ -0,0 +1,315 @@ +pub mod info; + +use anyhow::Result; +use info::PlaybackInfo; +use librespot::{ + connect::{config::ConnectConfig, spirc::Spirc}, + core::{http_client::HttpClientError, Session as SpotifySession, SessionConfig}, + discovery::Credentials, + metadata::Lyrics, + playback::{ + config::{Bitrate, PlayerConfig, VolumeCtrl}, + mixer::{self, MixerConfig}, + player::{Player as SpotifyPlayer, PlayerEvent as SpotifyPlayerEvent}, + }, +}; +use log::error; +use songbird::{input::RawAdapter, tracks::TrackHandle, Call}; +use spoticord_audio::{ + sink::{SinkEvent, StreamSink}, + stream::Stream, +}; +use std::{io::Write, sync::Arc}; +use tokio::sync::{mpsc, oneshot, Mutex}; + +#[derive(Debug)] +enum PlayerCommand { + NextTrack, + PreviousTrack, + Pause, + Play, + + GetPlaybackInfo(oneshot::Sender>), + GetLyrics(oneshot::Sender>), + + Shutdown, +} + +#[derive(Debug)] +pub enum PlayerEvent { + Pause, + Play, + Stopped, + TrackChanged(Box), +} + +pub struct Player { + session: SpotifySession, + spirc: Spirc, + track: TrackHandle, + stream: Stream, + + playback_info: Option, + + // Communication + events: mpsc::Sender, + + commands: mpsc::Receiver, + spotify_events: mpsc::UnboundedReceiver, + sink_events: mpsc::UnboundedReceiver, +} + +impl Player { + pub async fn create( + credentials: Credentials, + call: Arc>, + device_name: impl Into, + ) -> Result<(PlayerHandle, mpsc::Receiver)> { + let (event_tx, event_rx) = mpsc::channel(16); + + let mut call_lock = call.lock().await; + let stream = Stream::new(); + + // Create songbird audio track + let adapter = RawAdapter::new(stream.clone(), 44100, 2); + let track = call_lock.play_only_input(adapter.into()); + track.pause()?; + + // Free call lock before creating session + drop(call_lock); + + // Create librespot audio streamer + let session = SpotifySession::new(SessionConfig::default(), None); + let mixer = (mixer::find(Some("softvol")).expect("missing softvol mixer"))(MixerConfig { + volume_ctrl: VolumeCtrl::Log(VolumeCtrl::DEFAULT_DB_RANGE), + ..Default::default() + }); + + let (tx_sink, rx_sink) = mpsc::unbounded_channel(); + let player = SpotifyPlayer::new( + PlayerConfig { + // 96kbps causes audio key errors, so enjoy the quality upgrade + bitrate: Bitrate::Bitrate160, + ..Default::default() + }, + session.clone(), + mixer.get_soft_volume(), + { + let stream = stream.clone(); + move || Box::new(StreamSink::new(stream, tx_sink)) + }, + ); + let rx_player = player.get_player_event_channel(); + + let (spirc, spirc_task) = Spirc::new( + ConnectConfig { + name: device_name.into(), + initial_volume: Some((0.75f32 * u16::MAX as f32) as u16), + ..Default::default() + }, + session.clone(), + credentials, + player, + mixer, + ) + .await?; + + let (tx, rx) = mpsc::channel(16); + let player = Self { + session, + spirc, + track, + stream, + + playback_info: None, + + events: event_tx, + + commands: rx, + spotify_events: rx_player, + sink_events: rx_sink, + }; + + // Launch it all! + tokio::spawn(spirc_task); + tokio::spawn(player.run()); + + Ok((PlayerHandle { commands: tx }, event_rx)) + } + + async fn run(mut self) { + loop { + tokio::select! { + opt_command = self.commands.recv() => { + let command = match opt_command { + Some(command) => command, + None => break, + }; + + self.handle_command(command).await; + }, + + Some(event) = self.spotify_events.recv() => { + self.handle_spotify_event(event).await; + }, + + Some(event) = self.sink_events.recv() => { + self.handle_sink_event(event).await; + } + + else => break, + } + } + } + + async fn handle_command(&mut self, command: PlayerCommand) { + match command { + PlayerCommand::NextTrack => _ = self.spirc.next(), + PlayerCommand::PreviousTrack => _ = self.spirc.prev(), + PlayerCommand::Pause => _ = self.spirc.pause(), + PlayerCommand::Play => _ = self.spirc.play(), + + PlayerCommand::GetPlaybackInfo(tx) => _ = tx.send(self.playback_info.clone()), + PlayerCommand::GetLyrics(tx) => self.get_lyrics(tx).await, + + PlayerCommand::Shutdown => self.commands.close(), + }; + } + + async fn handle_spotify_event(&mut self, event: SpotifyPlayerEvent) { + match event { + SpotifyPlayerEvent::PositionCorrection { position_ms, .. } + | SpotifyPlayerEvent::Seeked { position_ms, .. } => { + if let Some(playback_info) = self.playback_info.as_mut() { + playback_info.update_playback(position_ms, true); + } + } + SpotifyPlayerEvent::Playing { position_ms, .. } => { + _ = self.events.send(PlayerEvent::Play).await; + + if let Some(playback_info) = self.playback_info.as_mut() { + playback_info.update_playback(position_ms, true); + } + } + SpotifyPlayerEvent::Paused { position_ms, .. } => { + _ = self.events.send(PlayerEvent::Pause).await; + + if let Some(playback_info) = self.playback_info.as_mut() { + playback_info.update_playback(position_ms, false); + } + } + SpotifyPlayerEvent::Stopped { .. } | SpotifyPlayerEvent::SessionDisconnected { .. } => { + if let Err(why) = self.track.pause() { + error!("Failed to pause songbird track: {why}"); + } + + _ = self.events.send(PlayerEvent::Pause).await; + + self.playback_info = None; + } + SpotifyPlayerEvent::TrackChanged { audio_item } => { + if let Some(playback_info) = self.playback_info.as_mut() { + playback_info.update_track(*audio_item); + } else { + self.playback_info = Some(PlaybackInfo::new(*audio_item, 0, false)); + } + + _ = self + .events + .send(PlayerEvent::TrackChanged(Box::new( + self.playback_info.clone().expect("playback info is None"), + ))) + .await; + } + _ => {} + } + } + + async fn handle_sink_event(&self, event: SinkEvent) { + if let SinkEvent::Start = event { + if let Err(why) = self.track.play() { + error!("Failed to resume songbird track: {why}"); + } + } + } + + /// Grab the lyrics for the current active track from Spotify. + /// + /// This might return None if nothing is being played, or the current song does not have any lyrics. + async fn get_lyrics(&self, tx: oneshot::Sender>) { + let Some(playback_info) = &self.playback_info else { + _ = tx.send(None); + return; + }; + + let lyrics = match Lyrics::get(&self.session, &playback_info.track_id()).await { + Ok(lyrics) => lyrics, + Err(why) => { + // Ignore 404 errors + match why.error.downcast_ref::() { + Some(HttpClientError::StatusCode(code)) if code.as_u16() == 404 => {} + _ => error!("Failed to get lyrics: {why}"), + } + + _ = tx.send(None); + return; + } + }; + + _ = tx.send(Some(lyrics)); + } +} + +impl Drop for Player { + fn drop(&mut self) { + _ = self.spirc.shutdown(); + _ = self.stream.flush(); + } +} + +#[derive(Clone, Debug)] +pub struct PlayerHandle { + commands: mpsc::Sender, +} + +impl PlayerHandle { + pub fn is_valid(&self) -> bool { + !self.commands.is_closed() + } + + pub async fn next_track(&self) { + _ = self.commands.send(PlayerCommand::NextTrack).await; + } + + pub async fn previous_track(&self) { + _ = self.commands.send(PlayerCommand::PreviousTrack).await; + } + + pub async fn pause(&self) { + _ = self.commands.send(PlayerCommand::Pause).await; + } + + pub async fn play(&self) { + _ = self.commands.send(PlayerCommand::Play).await; + } + + pub async fn playback_info(&self) -> Result> { + let (tx, rx) = oneshot::channel(); + self.commands + .send(PlayerCommand::GetPlaybackInfo(tx)) + .await?; + + Ok(rx.await?) + } + + pub async fn get_lyrics(&self) -> Result> { + let (tx, rx) = oneshot::channel(); + self.commands.send(PlayerCommand::GetLyrics(tx)).await?; + + Ok(rx.await?) + } + + pub async fn shutdown(&self) { + _ = self.commands.send(PlayerCommand::Shutdown).await; + } +} diff --git a/spoticord_session/Cargo.toml b/spoticord_session/Cargo.toml new file mode 100644 index 0000000..e13754b --- /dev/null +++ b/spoticord_session/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "spoticord_session" +version = "2.2.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +spoticord_config = { path = "../spoticord_config" } +spoticord_database = { path = "../spoticord_database" } +spoticord_player = { path = "../spoticord_player" } +spoticord_utils = { path = "../spoticord_utils" } + +tokio = { version = "1.39.2", features = ["full"] } +librespot = { git = "https://github.com/SpoticordMusic/librespot.git", version = "0.5.0-dev", default-features = false } +serenity = "0.12.2" +songbird = { version = "0.4.3", features = ["simd-json"] } +anyhow = "1.0.86" +log = "0.4.22" +base64 = "0.22.1" +poise = "0.6.1" diff --git a/spoticord_session/src/lib.rs b/spoticord_session/src/lib.rs new file mode 100644 index 0000000..cafd942 --- /dev/null +++ b/spoticord_session/src/lib.rs @@ -0,0 +1,580 @@ +pub mod lyrics_embed; +pub mod manager; +pub mod playback_embed; + +use anyhow::{anyhow, Result}; +use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; +use librespot::{discovery::Credentials, protocol::authentication::AuthenticationType}; +use log::{debug, error, trace}; +use lyrics_embed::LyricsEmbed; +use manager::{SessionManager, SessionQuery}; +use playback_embed::{PlaybackEmbed, PlaybackEmbedHandle}; +use serenity::{ + all::{ + ChannelId, CommandInteraction, CreateEmbed, CreateMessage, GuildChannel, GuildId, UserId, + }, + async_trait, +}; +use songbird::{model::payload::ClientDisconnect, Call, CoreEvent, Event, EventContext}; +use spoticord_database::Database; +use spoticord_player::{Player, PlayerEvent, PlayerHandle}; +use spoticord_utils::{discord::Colors, spotify}; +use std::{ops::ControlFlow, sync::Arc, time::Duration}; +use tokio::{ + sync::{mpsc, oneshot, Mutex}, + task::JoinHandle, +}; + +#[derive(Debug)] +pub enum SessionCommand { + GetOwner(oneshot::Sender), + GetPlayer(oneshot::Sender), + GetActive(oneshot::Sender), + + CreatePlaybackEmbed(SessionHandle, CommandInteraction), + CreateLyricsEmbed(SessionHandle, CommandInteraction), + + Reactivate(UserId, oneshot::Sender>), + ShutdownPlayer, + Disconnect, + DisconnectTimedOut, +} + +pub struct Session { + session_manager: SessionManager, + context: serenity::all::Context, + + guild_id: GuildId, + text_channel: GuildChannel, + call: Arc>, + player: PlayerHandle, + + owner: UserId, + active: bool, + + timeout_tx: Option>, + + commands: mpsc::Receiver, + events: mpsc::Receiver, + + commands_inner_tx: mpsc::Sender, + commands_inner_rx: mpsc::Receiver, + + playback_embed: Option, + lyrics_embed: Option>, +} + +impl Session { + pub async fn create( + session_manager: SessionManager, + + context: &serenity::all::Context, + guild_id: GuildId, + voice_channel_id: ChannelId, + text_channel_id: ChannelId, + owner: UserId, + ) -> Result { + // Set up communication channel + let (tx, rx) = mpsc::channel(16); + let handle = SessionHandle { + guild: guild_id, + voice_channel: voice_channel_id, + text_channel: text_channel_id, + + commands: tx, + }; + + // Resolve text channel + let text_channel = text_channel_id + .to_channel(&context) + .await? + .guild() + .ok_or(anyhow!("Text channel is not a guild channel"))?; + + // Create channel for internal command communication (timeouts hint hint) + // This uses separate channels as to not cause a cyclic dependency + let (inner_tx, inner_rx) = mpsc::channel(16); + + // Grab user credentials and info before joining call + let credentials = + retrieve_credentials(&session_manager.database(), owner.to_string()).await?; + let device_name = session_manager + .database() + .get_user(owner.to_string()) + .await? + .device_name; + + // Hello Discord I'm here + let call = session_manager + .songbird() + .join(guild_id, voice_channel_id) + .await?; + + // Make sure call guard is dropped or else we can't execute session.run + { + let mut call = call.lock().await; + + // Wasn't able to confirm if this is true, but this might reduce network bandwith by not receiving user voice packets + _ = call.deafen(true).await; + + // Set up call events + call.add_global_event(Event::Core(CoreEvent::DriverDisconnect), handle.clone()); + call.add_global_event(Event::Core(CoreEvent::ClientDisconnect), handle.clone()); + } + + let (player, events) = match Player::create(credentials, call.clone(), device_name).await { + Ok(player) => player, + Err(why) => { + // Leave call on error, otherwise bot will be stuck in call forever until manually disconnected or taken over + _ = call.lock().await.leave().await; + + error!("Failed to create player: {why}"); + + return Err(why); + } + }; + + let mut session = Self { + session_manager, + + context: context.to_owned(), + text_channel, + + call, + player, + + guild_id, + owner, + + active: true, + timeout_tx: None, + + commands: rx, + events, + + commands_inner_tx: inner_tx, + commands_inner_rx: inner_rx, + + playback_embed: None, + lyrics_embed: None, + }; + session.start_timeout(); + + tokio::spawn(session.run()); + + Ok(handle) + } + + pub async fn run(mut self) { + loop { + tokio::select! { + opt_command = self.commands.recv() => { + let Some(command) = opt_command else { + break; + }; + + if self.handle_command(command).await.is_break() { + break; + } + }, + + opt_event = self.events.recv(), if self.active => { + let Some(event) = opt_event else { + self.shutdown_player().await; + continue; + }; + + self.handle_event(event).await; + }, + + // Internal communication channel + Some(command) = self.commands_inner_rx.recv() => { + if self.handle_command(command).await.is_break() { + break; + } + } + + else => break, + } + } + } + + async fn handle_command(&mut self, command: SessionCommand) -> ControlFlow<(), ()> { + trace!("SessionCommand::{command:?}"); + + match command { + SessionCommand::GetOwner(sender) => _ = sender.send(self.owner), + SessionCommand::GetPlayer(sender) => _ = sender.send(self.player.clone()), + SessionCommand::GetActive(sender) => _ = sender.send(self.active), + + SessionCommand::CreatePlaybackEmbed(handle, interaction) => { + match PlaybackEmbed::create(self, handle, interaction).await { + Ok(Some(playback_embed)) => { + self.playback_embed = Some(playback_embed); + } + Ok(None) => {} + Err(why) => { + error!("Failed to create playing embed: {why}"); + } + }; + } + SessionCommand::CreateLyricsEmbed(handle, interaction) => { + match LyricsEmbed::create(self, handle, interaction).await { + Ok(Some(lyrics_embed)) => { + if let Some(current) = self.lyrics_embed.take() { + current.abort(); + } + + self.lyrics_embed = Some(lyrics_embed); + } + Ok(None) => {} + Err(why) => { + error!("Failed to create lyrics embed: {why}"); + } + } + } + + SessionCommand::Reactivate(new_owner, tx) => { + _ = tx.send(self.reactivate(new_owner).await) + } + SessionCommand::ShutdownPlayer => self.shutdown_player().await, + SessionCommand::Disconnect => { + self.disconnect().await; + + return ControlFlow::Break(()); + } + SessionCommand::DisconnectTimedOut => { + self.disconnect().await; + + _ = self + .text_channel + .send_message( + &self.context, + CreateMessage::new().embed( + CreateEmbed::new() + .title("It's a little quiet in here") + .description("The bot has been inactive for too long, and has been disconnected.") + .color(Colors::Warning), + ), + ) + .await; + + return ControlFlow::Break(()); + } + }; + + ControlFlow::Continue(()) + } + + async fn handle_event(&mut self, event: PlayerEvent) { + match event { + PlayerEvent::Play => self.stop_timeout(), + PlayerEvent::Pause => self.start_timeout(), + PlayerEvent::Stopped => self.shutdown_player().await, + PlayerEvent::TrackChanged(_) => {} + } + + if let Some(playback_embed) = &self.playback_embed { + if playback_embed.invoke_update().await.is_err() { + self.playback_embed = None; + } + } + } + + fn start_timeout(&mut self) { + if let Some(tx) = self.timeout_tx.take() { + _ = tx.send(()); + } + + let (tx, rx) = oneshot::channel::<()>(); + self.timeout_tx = Some(tx); + + let inner_tx = self.commands_inner_tx.clone(); + + tokio::spawn(async move { + let mut timer = + tokio::time::interval(Duration::from_secs(spoticord_config::DISCONNECT_TIME)); + + // Ignore immediate tick + timer.tick().await; + + tokio::select! { + _ = rx => return, + _ = timer.tick() => {} + }; + + // Disconnect through inner communication + _ = inner_tx.send(SessionCommand::DisconnectTimedOut).await; + }); + } + + fn stop_timeout(&mut self) { + if let Some(tx) = self.timeout_tx.take() { + _ = tx.send(()); + } + } + + async fn reactivate(&mut self, new_owner: UserId) -> Result<()> { + if self.active { + return Err(anyhow!("Cannot reactivate session that is already active")); + } + + let credentials = + retrieve_credentials(&self.session_manager.database(), new_owner.to_string()).await?; + let device_name = self + .session_manager + .database() + .get_user(new_owner.to_string()) + .await? + .device_name; + + let (player, player_events) = + Player::create(credentials, self.call.clone(), device_name).await?; + + self.owner = new_owner; + self.player = player; + self.events = player_events; + self.active = true; + + Ok(()) + } + + async fn shutdown_player(&mut self) { + self.player.shutdown().await; + self.start_timeout(); + + self.active = false; + + // Remove owner from session manager + self.session_manager + .remove_session(SessionQuery::Owner(self.owner)); + } + + async fn disconnect(&mut self) { + // Kill timeout if one is running + self.stop_timeout(); + + // Force close channels, as handles may otherwise hold this struct hostage + self.commands.close(); + self.events.close(); + + // Leave call, ignore errors + let mut call = self.call.lock().await; + _ = call.leave().await; + } +} + +impl Drop for Session { + fn drop(&mut self) { + // Abort timeout task + if let Some(tx) = self.timeout_tx.take() { + _ = tx.send(()); + } + + // Abort lyrics task + if let Some(lyrics) = self.lyrics_embed.take() { + lyrics.abort(); + } + + // Clean up the session from the session manager + // This is done in Drop::drop to ensure that the session always cleans up after itself + // even if something went wrong + + let session_manager = self.session_manager.clone(); + let guild_id = self.guild_id; + let owner = self.owner; + + session_manager.remove_session(SessionQuery::Guild(guild_id)); + session_manager.remove_session(SessionQuery::Owner(owner)); + } +} + +#[derive(Clone, Debug)] +pub struct SessionHandle { + guild: GuildId, + voice_channel: ChannelId, + text_channel: ChannelId, + + commands: mpsc::Sender, +} + +impl SessionHandle { + /// Check if the session handle is valid + pub fn is_valid(&self) -> bool { + !self.commands.is_closed() + } + + pub fn guild(&self) -> GuildId { + self.guild + } + + pub fn voice_channel(&self) -> ChannelId { + self.voice_channel + } + + pub fn text_channel(&self) -> ChannelId { + self.text_channel + } + + /// Retrieve the current owner of the session + pub async fn owner(&self) -> Result { + let (tx, rx) = oneshot::channel(); + self.commands.send(SessionCommand::GetOwner(tx)).await?; + + let result = rx.await?; + Ok(result) + } + + /// Retrieve the player handle from the session + pub async fn player(&self) -> Result { + let (tx, rx) = oneshot::channel(); + self.commands.send(SessionCommand::GetPlayer(tx)).await?; + + let result = rx.await?; + Ok(result) + } + + pub async fn active(&self) -> Result { + let (tx, rx) = oneshot::channel(); + self.commands.send(SessionCommand::GetActive(tx)).await?; + + let result = rx.await?; + Ok(result) + } + + /// Instruct the session to make another user owner. + /// + /// This will fail if the session still has an active user assigned to it. + pub async fn reactivate(&self, new_owner: UserId) -> Result<()> { + let (tx, rx) = oneshot::channel(); + self.commands + .send(SessionCommand::Reactivate(new_owner, tx)) + .await?; + + rx.await? + } + + /// Create a playback embed as a response to an interaction + /// + /// This playback embed will automatically update when certain events happen + pub async fn create_playback_embed(&self, interaction: CommandInteraction) -> Result<()> { + self.commands + .send(SessionCommand::CreatePlaybackEmbed( + self.clone(), + interaction, + )) + .await?; + + Ok(()) + } + + /// Create a lyrics embed as a response to an interaction + /// + /// This lyrics embed will automatically retrieve the lyrics and update the embed accordingly + pub async fn create_lyrics_embed(&self, interaction: CommandInteraction) -> Result<()> { + self.commands + .send(SessionCommand::CreateLyricsEmbed(self.clone(), interaction)) + .await?; + + Ok(()) + } + + /// Instruct the session to destroy the player (but keep voice call). + /// + /// This is meant to be used for when the session owner leaves the call + /// and allows other users to become owner using the `/join` command. + /// + /// This should also remove the owner from the session manager. + pub async fn shutdown_player(&self) { + if let Err(why) = self.commands.send(SessionCommand::ShutdownPlayer).await { + error!("Failed to send command: {why}"); + } + } + + /// Instruct the session to destroy itself. + /// + /// This should also remove the player and the owner from the session manager. + pub async fn disconnect(&self) { + if let Err(why) = self.commands.send(SessionCommand::Disconnect).await { + error!("Failed to send command: {why}"); + } + } +} + +#[async_trait] +impl songbird::EventHandler for SessionHandle { + async fn act(&self, event: &EventContext<'_>) -> Option { + if !self.is_valid() { + return Some(Event::Cancel); + } + + match event { + EventContext::DriverDisconnect(_) => { + debug!("Bot disconnected from call, cleaning up"); + + self.disconnect().await; + } + + EventContext::ClientDisconnect(ClientDisconnect { user_id }) => { + match self.owner().await { + Ok(id) if id.get() == user_id.0 => { + debug!("Owner of session disconnected, stopping playback"); + + self.shutdown_player().await; + } + _ => {} + } + } + _ => {} + } + + None + } +} + +async fn retrieve_credentials(database: &Database, owner: impl AsRef) -> Result { + let account = database.get_account(&owner).await?; + + let token = if let Some(session_token) = &account.session_token { + match spotify::validate_token(&account.username, session_token).await { + Ok(Some(token)) => { + database + .update_session_token(&account.user_id, &token) + .await?; + + Some(token) + } + Ok(None) => Some(session_token.clone()), + Err(_) => None, + } + } else { + None + }; + + // Request new session token if previous one was invalid or missing + let token = match token { + Some(token) => token, + None => { + let access_token = database.get_access_token(&account.user_id).await?; + let credentials = spotify::request_session_token(Credentials { + username: account.username.clone(), + auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN, + auth_data: access_token.into_bytes(), + }) + .await?; + + let token = BASE64.encode(credentials.auth_data); + database + .update_session_token(&account.user_id, &token) + .await?; + + token + } + }; + + Ok(Credentials { + username: account.username, + auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS, + auth_data: BASE64.decode(token)?, + }) +} diff --git a/spoticord_session/src/lyrics_embed.rs b/spoticord_session/src/lyrics_embed.rs new file mode 100644 index 0000000..4cebf12 --- /dev/null +++ b/spoticord_session/src/lyrics_embed.rs @@ -0,0 +1,447 @@ +use std::{ops::ControlFlow, time::Duration}; + +use anyhow::Result; +use librespot::{ + core::SpotifyId, + metadata::{ + lyrics::{Line, SyncType}, + Lyrics, + }, +}; +use log::error; +use serenity::{ + all::{ + CommandInteraction, ComponentInteraction, ComponentInteractionCollector, Context, + CreateActionRow, CreateButton, CreateEmbed, CreateEmbedFooter, CreateInteractionResponse, + CreateInteractionResponseMessage, EditMessage, Message, + }, + futures::StreamExt, +}; +use spoticord_player::info::PlaybackInfo; +use spoticord_utils::discord::Colors; +use tokio::task::JoinHandle; + +use crate::{Session, SessionHandle}; + +const PAGE_LENGTH: usize = 3000; +const TIME_OFFSET: u32 = 1000; + +pub struct LyricsEmbed { + guild_id: String, + ctx: Context, + session: SessionHandle, + message: Message, + track: SpotifyId, + + lyrics: Option, + page: usize, +} + +impl LyricsEmbed { + pub async fn create( + session: &Session, + handle: SessionHandle, + interaction: CommandInteraction, + ) -> Result>> { + let ctx = session.context.clone(); + + if !session.active { + respond_not_playing(&ctx, interaction).await?; + + return Ok(None); + } + + let Some(playback_info) = session.player.playback_info().await? else { + respond_not_playing(&ctx, interaction).await?; + + return Ok(None); + }; + + let guild_id = interaction + .guild_id + .expect("interaction was outside of a guild") + .to_string(); + let lyrics = session.player.get_lyrics().await?; + + // Send initial message + interaction + .create_response( + &ctx, + CreateInteractionResponse::Message( + CreateInteractionResponseMessage::new() + .embed(lyrics_embed(&lyrics, &playback_info, 0)) + .components(vec![lyrics_buttons(&guild_id, &lyrics, 0)]), + ), + ) + .await?; + + // Retrieve message instead of editing interaction response, as those tokens are only valid for 15 minutes + let message = interaction.get_response(&ctx).await?; + + let this = Self { + guild_id: guild_id.clone(), + ctx: ctx.clone(), + session: handle, + message, + track: playback_info.track_id(), + + lyrics, + page: 0, + }; + + let collector = ComponentInteractionCollector::new(&ctx) + .filter(move |press| { + let parts = press.data.custom_id.split(':').collect::>(); + + matches!(parts.first(), Some(&"lyrics")) + && matches!(parts.last(), Some(id) if id == &guild_id) + }) + .timeout(Duration::from_secs(3600 * 24)); + + let handle = tokio::spawn(this.run(collector)); + + Ok(Some(handle)) + } + + async fn run(mut self, collector: ComponentInteractionCollector) { + let mut stream = collector.stream(); + let mut interval = tokio::time::interval(Duration::from_secs(2)); + + loop { + tokio::select! { + _ = interval.tick() => { + if self.handle_tick().await.is_break() { + break; + } + } + + opt_press = stream.next() => { + let Some(press) = opt_press else { + break; + }; + + // Immediately acknowledge, we don't have to inform the user about the update + _ = press + .create_response(&self.ctx, CreateInteractionResponse::Acknowledge) + .await; + + if self.handle_press(press).await.is_break() { + break; + } + } + } + } + } + + async fn handle_tick(&mut self) -> ControlFlow<(), ()> { + let Ok(player) = self.session.player().await else { + // Failure means that the session is gone, so we quit + return ControlFlow::Break(()); + }; + + if !matches!(self.session.active().await, Ok(true)) { + // If the session is currently not active, just wait until it becomes active again + return ControlFlow::Continue(()); + } + + let Ok(Some(playback_info)) = player.playback_info().await else { + // If we're not playing anything, just wait until we are + return ControlFlow::Continue(()); + }; + + if playback_info.track_id() != self.track { + // We're playing another track, reload the lyrics! + + let lyrics = match player.get_lyrics().await { + Ok(lyrics) => lyrics, + Err(why) => { + error!("Failed to retrieve lyrics: {why}"); + + return ControlFlow::Break(()); + } + }; + + self.lyrics = lyrics; + self.page = 0; + self.track = playback_info.track_id(); + + if let Err(why) = self + .message + .edit( + &self.ctx, + EditMessage::new() + .embed(lyrics_embed(&self.lyrics, &playback_info, self.page)) + .components(vec![lyrics_buttons( + &self.guild_id, + &self.lyrics, + self.page, + )]), + ) + .await + { + error!("Failed to update lyrics: {why}"); + + return ControlFlow::Break(()); + } + + return ControlFlow::Continue(()); + } + + // We're still playing the same song, check if we need to update the page + let Some(lyrics) = &self.lyrics else { + // No lyrics in current song, just continue until we have one with + return ControlFlow::Continue(()); + }; + + if !matches!(lyrics.lyrics.sync_type, SyncType::LineSynced) { + // Only synced lyrics should auto-swap to new pages + return ControlFlow::Continue(()); + } + + let new_page = page_at_position(lyrics, playback_info.current_position()).unwrap_or(0); + + if new_page != self.page { + // We've arrived on a new page: swap em up! + + self.page = new_page; + + if let Err(why) = self + .message + .edit( + &self.ctx, + EditMessage::new() + .embed(lyrics_embed(&self.lyrics, &playback_info, new_page)) + .components(vec![lyrics_buttons(&self.guild_id, &self.lyrics, new_page)]), + ) + .await + { + error!("Failed to update lyrics: {why}"); + + return ControlFlow::Break(()); + } + } + + ControlFlow::Continue(()) + } + + async fn handle_press(&mut self, press: ComponentInteraction) -> ControlFlow<(), ()> { + let next = match press.data.custom_id.split(':').nth(1) { + Some("next") => true, + Some("prev") => false, + _ => return ControlFlow::Continue(()), + }; + + let Some(lyrics) = &self.lyrics else { + return ControlFlow::Continue(()); + }; + + if !matches!(lyrics.lyrics.sync_type, SyncType::Unsynced) { + // Only allow manual swapping if lyrics are unsynced + + return ControlFlow::Continue(()); + } + + let length = lyrics + .lyrics + .lines + .iter() + .fold(0, |acc, line| acc + line.words.len()); + let pages = length / PAGE_LENGTH + if length % PAGE_LENGTH > 0 { 1 } else { 0 }; + + let Ok(player) = self.session.player().await else { + return ControlFlow::Continue(()); + }; + + let Ok(Some(playback_info)) = player.playback_info().await else { + return ControlFlow::Continue(()); + }; + + match next { + true if self.page < pages - 1 => self.page += 1, + false if self.page > 0 => self.page -= 1, + _ => return ControlFlow::Continue(()), + } + + if let Err(why) = self + .message + .edit( + &self.ctx, + EditMessage::new() + .embed(lyrics_embed(&self.lyrics, &playback_info, self.page)) + .components(vec![lyrics_buttons( + &self.guild_id, + &self.lyrics, + self.page, + )]), + ) + .await + { + error!("Failed to update lyrics: {why}"); + + return ControlFlow::Break(()); + } + + ControlFlow::Continue(()) + } +} + +async fn respond_not_playing(context: &Context, interaction: CommandInteraction) -> Result<()> { + interaction + .create_response( + context, + CreateInteractionResponse::Message( + CreateInteractionResponseMessage::new() + .embed(not_playing_embed()) + .ephemeral(true), + ), + ) + .await?; + + Ok(()) +} + +fn not_playing_embed() -> CreateEmbed { + CreateEmbed::new() + .title("Cannot get lyrics") + .description("I'm currently not playing any music in this server.") + .color(Colors::Error) +} + +fn lyrics_embed(lyrics: &Option, playback_info: &PlaybackInfo, page: usize) -> CreateEmbed { + match (lyrics, playback_info.artists()) { + (Some(lyrics), Some(artists)) => { + let length = lyrics + .lyrics + .lines + .iter() + .fold(0, |acc, line| acc + line.words.len()); + + let page = &into_pages(&lyrics.lyrics.lines) + [if page * PAGE_LENGTH > length { 0 } else { page }]; + + let title = format!( + "{} - {}", + playback_info.name(), + artists + .0 + .into_iter() + .map(|artist| artist.name) + .collect::>() + .join(", "), + ); + + let description = page + .iter() + .map(|page| page.words.replace('♪', "\n♪\n")) + .collect::>() + .join("\n"); + + let mut footer = format!("Lyrics provided by {}", lyrics.lyrics.provider_display_name); + + if matches!(lyrics.lyrics.sync_type, SyncType::LineSynced) { + footer.push_str(" | Synced to song"); + } + + CreateEmbed::new() + .title(title) + .description(description) + .footer(CreateEmbedFooter::new(footer)) + .color(Colors::Info) + } + _ => CreateEmbed::new() + .title("No lyrics available") + .description("This current track has no lyrics available. Just enjoy the tunes!") + .color(Colors::Info), + } +} + +fn lyrics_buttons(id: &str, lyrics: &Option, page: usize) -> CreateActionRow { + let (can_prev, can_next) = match lyrics { + Some(lyrics) => match lyrics.lyrics.sync_type { + SyncType::Unsynced => { + // Only unsynced lyrics can have its pages flipped through by the user + + let length = lyrics + .lyrics + .lines + .iter() + .fold(0, |acc, line| acc + line.words.len()); + let pages = length / PAGE_LENGTH + if length % PAGE_LENGTH > 0 { 1 } else { 0 }; + + (page > 0, page < pages - 1) + } + SyncType::LineSynced => (false, false), + }, + None => (false, false), + }; + + CreateActionRow::Buttons(vec![ + CreateButton::new(format!("lyrics:prev:{id}")) + .disabled(!can_prev) + .label("<"), + CreateButton::new(format!("lyrics:next:{id}")) + .disabled(!can_next) + .label(">"), + ]) +} + +fn into_pages(lines: &[Line]) -> Vec> { + let mut result = vec![]; + let mut current = vec![]; + let mut current_position = 0; + + for line in lines { + if current_position + line.words.len() > PAGE_LENGTH { + result.push(current); + current = vec![line.clone()]; + current_position = line.words.len(); + continue; + } + + current.push(line.clone()); + current_position += line.words.len(); + } + + result.push(current); + result +} + +fn page_at_position(lyrics: &Lyrics, position: u32) -> Option { + let pages = into_pages(&lyrics.lyrics.lines); + + for (i, line) in pages.iter().enumerate() { + if let Some(first) = line.first() { + let Ok(time) = first + .start_time_ms + .parse::() + .map(|v| v.saturating_sub(TIME_OFFSET)) + else { + return None; + }; + + if position < time { + return Some(if i == 0 { 0 } else { i - 1 }); + } + } + + if let (Some(first), Some(last)) = (line.first(), line.last()) { + let (Ok(first), Ok(last)) = ( + first + .start_time_ms + .parse::() + .map(|v| v.saturating_sub(TIME_OFFSET)), + last.start_time_ms + .parse::() + .map(|v| v.saturating_sub(TIME_OFFSET)), + ) else { + return None; + }; + + if position >= first && position <= last { + return Some(i); + } + } + } + + Some(pages.len() - 1) +} diff --git a/spoticord_session/src/manager.rs b/spoticord_session/src/manager.rs new file mode 100644 index 0000000..01afb7e --- /dev/null +++ b/spoticord_session/src/manager.rs @@ -0,0 +1,126 @@ +use anyhow::Result; +use serenity::all::{ChannelId, GuildId, UserId}; +use songbird::Songbird; +use spoticord_database::Database; +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; + +use super::{Session, SessionHandle}; + +#[derive(Clone)] +pub struct SessionManager { + songbird: Arc, + database: Database, + + sessions: Arc>>, + owners: Arc>>, +} + +pub enum SessionQuery { + Guild(GuildId), + Owner(UserId), +} + +impl SessionManager { + pub fn new(songbird: Arc, database: Database) -> Self { + Self { + songbird, + database, + + sessions: Arc::new(Mutex::new(HashMap::new())), + owners: Arc::new(Mutex::new(HashMap::new())), + } + } + + pub async fn create_session( + &self, + context: &serenity::all::Context, + guild_id: GuildId, + voice_channel_id: ChannelId, + text_channel_id: ChannelId, + owner: UserId, + ) -> Result { + let handle = Session::create( + self.clone(), + context, + guild_id, + voice_channel_id, + text_channel_id, + owner, + ) + .await?; + + self.sessions + .lock() + .expect("mutex poisoned") + .insert(guild_id, handle.clone()); + self.owners + .lock() + .expect("mutex poisoned") + .insert(owner, handle.clone()); + + Ok(handle) + } + + pub fn get_session(&self, query: SessionQuery) -> Option { + match query { + SessionQuery::Guild(guild) => self + .sessions + .lock() + .expect("mutex poisoned") + .get(&guild) + .cloned(), + SessionQuery::Owner(owner) => self + .owners + .lock() + .expect("mutex poisoned") + .get(&owner) + .cloned(), + } + } + + pub fn remove_session(&self, query: SessionQuery) { + match query { + SessionQuery::Guild(guild) => { + self.sessions.lock().expect("mutex poisoned").remove(&guild) + } + SessionQuery::Owner(owner) => { + self.owners.lock().expect("mutex poisoned").remove(&owner) + } + }; + } + + pub fn get_all_sessions(&self) -> Vec { + self.sessions + .lock() + .expect("mutex poisoned") + .values() + .cloned() + .collect() + } + + /// Disconnects all active sessions and clears out all handles. + /// + /// The session manager can still create new sessions after all sessions have been shut down. + /// Sessions might still be created during shutdown. + pub async fn shutdown_all(&self) { + let sessions = self.get_all_sessions(); + + for session in sessions { + session.disconnect().await; + } + + self.owners.lock().expect("mutex poisoned").clear(); + self.sessions.lock().expect("mutex poisoned").clear(); + } + + pub fn songbird(&self) -> Arc { + self.songbird.clone() + } + + pub fn database(&self) -> Database { + self.database.clone() + } +} diff --git a/spoticord_session/src/playback_embed.rs b/spoticord_session/src/playback_embed.rs new file mode 100644 index 0000000..82bd0d5 --- /dev/null +++ b/spoticord_session/src/playback_embed.rs @@ -0,0 +1,401 @@ +use anyhow::{anyhow, Result}; +use log::{error, trace}; +use serenity::{ + all::{ + ButtonStyle, CommandInteraction, ComponentInteraction, ComponentInteractionCollector, + Context, CreateActionRow, CreateButton, CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter, + CreateInteractionResponse, CreateInteractionResponseFollowup, + CreateInteractionResponseMessage, EditMessage, Message, User, + }, + futures::StreamExt, +}; +use spoticord_player::{info::PlaybackInfo, PlayerHandle}; +use spoticord_utils::discord::Colors; +use std::{ops::ControlFlow, time::Duration}; +use tokio::{sync::mpsc, time::Instant}; + +use crate::{Session, SessionHandle}; + +#[derive(Debug)] +pub enum Command { + InvokeUpdate, +} + +pub struct PlaybackEmbed { + id: u64, + ctx: Context, + session: SessionHandle, + message: Message, + + last_update: Instant, + update_in: Option, + + rx: mpsc::Receiver, +} + +impl PlaybackEmbed { + pub async fn create( + session: &Session, + handle: SessionHandle, + interaction: CommandInteraction, + ) -> Result> { + let ctx = session.context.clone(); + + if !session.active { + respond_not_playing(&ctx, interaction).await?; + + return Ok(None); + } + + let owner = session.owner.to_user(&ctx).await?; + + let Some(playback_info) = session.player.playback_info().await? else { + respond_not_playing(&ctx, interaction).await?; + + return Ok(None); + }; + + let ctx_id = interaction.id.get(); + + // Send initial reply + interaction + .create_response( + &ctx, + CreateInteractionResponse::Message( + CreateInteractionResponseMessage::new() + .embed(build_embed(&playback_info, &owner)) + .components(vec![build_buttons(ctx_id, playback_info.playing())]), + ), + ) + .await?; + + // Retrieve message instead of editing interaction response, as those tokens are only valid for 15 minutes + let message = interaction.get_response(&ctx).await?; + + let collector = ComponentInteractionCollector::new(&ctx) + .filter(move |press| press.data.custom_id.starts_with(&ctx_id.to_string())) + .timeout(Duration::from_secs(3600 * 24)); + + let (tx, rx) = mpsc::channel(16); + let this = Self { + id: ctx_id, + ctx, + session: handle, + message, + last_update: Instant::now(), + update_in: None, + rx, + }; + + tokio::spawn(this.run(collector)); + + Ok(Some(PlaybackEmbedHandle { tx })) + } + + async fn run(mut self, collector: ComponentInteractionCollector) { + let mut stream = collector.stream(); + + loop { + tokio::select! { + opt_command = self.rx.recv() => { + let Some(command) = opt_command else { + break; + }; + + if self.handle_command(command).await.is_break() { + break; + } + }, + + opt_press = stream.next() => { + let Some(press) = opt_press else { + break; + }; + + self.handle_press(press).await; + } + + _ = async { + if let Some(update_in) = self.update_in.take() + { + tokio::time::sleep(update_in).await; + } + }, if self.update_in.is_some() => { + if self.update_embed().await.is_break() { + break; + } + } + } + } + } + + async fn handle_command(&mut self, command: Command) -> ControlFlow<(), ()> { + trace!("Received command: {command:?}"); + + match command { + Command::InvokeUpdate => { + if self.last_update.elapsed() < Duration::from_secs(2) { + if self.update_in.is_some() { + return ControlFlow::Continue(()); + } + + self.update_in = Some(Duration::from_secs(2) - self.last_update.elapsed()); + } else { + self.update_embed().await?; + } + } + } + + ControlFlow::Continue(()) + } + + async fn handle_press(&self, press: ComponentInteraction) { + trace!("Received button press: {press:?}"); + + let Ok((player, playback_info, owner)) = self.get_info().await else { + _ = press + .create_followup( + &self.ctx, + CreateInteractionResponseFollowup::new() + .embed( + CreateEmbed::new() + .title("Cannot perform action") + .description("I'm currently not playing any music in this server"), + ) + .ephemeral(true), + ) + .await; + + return; + }; + + if press.user.id != owner.id { + _ = press + .create_followup( + &self.ctx, + CreateInteractionResponseFollowup::new() + .embed( + CreateEmbed::new() + .title("Cannot perform action") + .description("Only the host may use the media buttons"), + ) + .ephemeral(true), + ) + .await; + + return; + } + + match press.data.custom_id.split('-').last() { + Some("next") => player.next_track().await, + Some("prev") => player.previous_track().await, + Some("pause") => { + if playback_info.playing() { + player.pause().await + } else { + player.play().await + } + } + + _ => {} + } + + _ = press + .create_response(&self.ctx, CreateInteractionResponse::Acknowledge) + .await; + } + + async fn get_info(&self) -> Result<(PlayerHandle, PlaybackInfo, User)> { + let player = self.session.player().await?; + let owner = self.session.owner().await?.to_user(&self.ctx).await?; + let playback_info = player + .playback_info() + .await? + .ok_or_else(|| anyhow!("No playback info present"))?; + + Ok((player, playback_info, owner)) + } + + async fn update_embed(&mut self) -> ControlFlow<(), ()> { + self.update_in = None; + + let Ok(owner) = self.session.owner().await else { + _ = self.update_not_playing().await; + + return ControlFlow::Break(()); + }; + + let Ok(player) = self.session.player().await else { + _ = self.update_not_playing().await; + + return ControlFlow::Break(()); + }; + + let Ok(Some(playback_info)) = player.playback_info().await else { + _ = self.update_not_playing().await; + + return ControlFlow::Break(()); + }; + + let owner = match owner.to_user(&self.ctx).await { + Ok(owner) => owner, + Err(why) => { + error!("Failed to resolve owner: {why}"); + + return ControlFlow::Break(()); + } + }; + + if let Err(why) = self + .message + .edit( + &self.ctx, + EditMessage::new() + .embed(build_embed(&playback_info, &owner)) + .components(vec![build_buttons(self.id, playback_info.playing())]), + ) + .await + { + error!("Failed to update playback embed: {why}"); + + return ControlFlow::Break(()); + }; + + self.last_update = Instant::now(); + + ControlFlow::Continue(()) + } + + async fn update_not_playing(&mut self) -> Result<()> { + self.message + .edit(&self.ctx, EditMessage::new().embed(not_playing_embed())) + .await?; + + Ok(()) + } +} + +pub struct PlaybackEmbedHandle { + tx: mpsc::Sender, +} + +impl PlaybackEmbedHandle { + pub fn is_valid(&self) -> bool { + !self.tx.is_closed() + } + + pub async fn invoke_update(&self) -> Result<()> { + self.tx.send(Command::InvokeUpdate).await?; + + Ok(()) + } +} + +async fn respond_not_playing(context: &Context, interaction: CommandInteraction) -> Result<()> { + interaction + .create_response( + context, + CreateInteractionResponse::Message( + CreateInteractionResponseMessage::new() + .embed(not_playing_embed()) + .ephemeral(true), + ), + ) + .await?; + + Ok(()) +} + +fn not_playing_embed() -> CreateEmbed { + CreateEmbed::new() + .title("Cannot display song details") + .description("I'm currently not playing any music in this server.") + .color(Colors::Error) +} + +fn build_embed(playback_info: &PlaybackInfo, owner: &User) -> CreateEmbed { + let mut description = String::new(); + + description += &format!("## [{}]({})\n", playback_info.name(), playback_info.url()); + + if let Some(artists) = playback_info.artists() { + let artists = artists + .iter() + .map(|artist| { + format!( + "[{}](https://open.spotify.com/artist/{})", + artist.name, + artist.id.to_base62().expect("invalid artist") + ) + }) + .collect::>() + .join(", "); + + description += &format!("By {artists}\n\n"); + } + + if let Some(show_name) = playback_info.show_name() { + description += &format!("On {show_name}\n\n"); + } + + let position = playback_info.current_position(); + let index = position * 20 / playback_info.duration(); + + description.push_str(if playback_info.playing() { + "▶️ " + } else { + "⏸️ " + }); + + for i in 0..20 { + if i == index { + description.push('🔵'); + } else { + description.push('▬'); + } + } + + description.push_str("\n:alarm_clock: "); + description.push_str(&format!( + "{} / {}", + spoticord_utils::time_to_string(position / 1000), + spoticord_utils::time_to_string(playback_info.duration() / 1000) + )); + + CreateEmbed::new() + .author( + CreateEmbedAuthor::new("Currently Playing") + .icon_url("https://spoticord.com/spotify-logo.png"), + ) + .description(description) + .thumbnail(playback_info.thumbnail()) + .footer( + CreateEmbedFooter::new(owner.global_name.as_ref().unwrap_or(&owner.name)) + .icon_url(owner.face()), + ) + .color(Colors::Info) +} + +fn build_buttons(id: u64, playing: bool) -> CreateActionRow { + let prev_button_id = format!("{id}-prev"); + let next_button_id = format!("{id}-next"); + let pause_button_id = format!("{id}-pause"); + + let prev_button = CreateButton::new(prev_button_id) + .style(ButtonStyle::Primary) + .label("<<"); + + let next_button = CreateButton::new(next_button_id) + .style(ButtonStyle::Primary) + .label(">>"); + + let pause_button = CreateButton::new(pause_button_id) + .style(if playing { + ButtonStyle::Danger + } else { + ButtonStyle::Success + }) + .label(if playing { "Pause" } else { "Play" }); + + CreateActionRow::Buttons(vec![prev_button, pause_button, next_button]) +} diff --git a/spoticord_stats/Cargo.toml b/spoticord_stats/Cargo.toml new file mode 100644 index 0000000..c7fa8f1 --- /dev/null +++ b/spoticord_stats/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "spoticord_stats" +version = "2.2.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +redis = { version = "0.25.4", default-features = false } diff --git a/spoticord_stats/src/lib.rs b/spoticord_stats/src/lib.rs new file mode 100644 index 0000000..188da8c --- /dev/null +++ b/spoticord_stats/src/lib.rs @@ -0,0 +1,18 @@ +use redis::{Client, Commands, Connection, RedisResult as Result}; + +pub struct StatsManager { + redis: Connection, +} + +impl StatsManager { + pub fn new(url: impl AsRef) -> Result { + let client = Client::open(url.as_ref())?; + let connection = client.get_connection()?; + + Ok(StatsManager { redis: connection }) + } + + pub fn set_active_count(&mut self, count: usize) -> Result<()> { + self.redis.set("spoticord-active-guilds", count.to_string()) + } +} diff --git a/spoticord_utils/Cargo.toml b/spoticord_utils/Cargo.toml new file mode 100644 index 0000000..336e9fd --- /dev/null +++ b/spoticord_utils/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "spoticord_utils" +version = "2.2.0" +edition = "2021" + +[dependencies] +librespot = { git = "https://github.com/SpoticordMusic/librespot.git", version = "0.5.0-dev", default-features = false } +anyhow = "1.0.86" +base64 = "0.22.1" +log = "0.4.22" +poise = "0.6.1" diff --git a/spoticord_utils/src/discord.rs b/spoticord_utils/src/discord.rs new file mode 100644 index 0000000..bb7a5a0 --- /dev/null +++ b/spoticord_utils/src/discord.rs @@ -0,0 +1,27 @@ +pub enum Colors { + Info = 0x0773D6, + Success = 0x3BD65D, + Warning = 0xF0D932, + Error = 0xFC1F28, + None = 0, +} + +impl From for poise::serenity_prelude::Colour { + fn from(value: Colors) -> Self { + Self(value as u32) + } +} + +pub fn escape(text: impl Into) -> String { + let text: String = text.into(); + + text.replace('\\', "\\\\") + .replace('/', "\\/") + .replace('*', "\\*") + .replace('_', "\\_") + .replace('~', "\\~") + .replace('`', "\\`") + // Prevent markdown links + .replace('[', "\\[") + .replace(']', "\\]") +} diff --git a/spoticord_utils/src/lib.rs b/spoticord_utils/src/lib.rs new file mode 100644 index 0000000..afc59c3 --- /dev/null +++ b/spoticord_utils/src/lib.rs @@ -0,0 +1,29 @@ +pub mod discord; +pub mod spotify; + +use std::time::{SystemTime, UNIX_EPOCH}; + +pub fn get_time() -> u128 { + let now = SystemTime::now(); + let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards"); + + since_the_epoch.as_millis() +} + +pub fn time_to_string(time: u32) -> String { + let hour = 3600; + let min = 60; + + if time / hour >= 1 { + format!( + "{}h{}m{}s", + time / hour, + (time % hour) / min, + (time % hour) % min + ) + } else if time / min >= 1 { + format!("{}m{}s", time / min, time % min) + } else { + format!("{}s", time) + } +} diff --git a/spoticord_utils/src/spotify.rs b/spoticord_utils/src/spotify.rs new file mode 100644 index 0000000..d661122 --- /dev/null +++ b/spoticord_utils/src/spotify.rs @@ -0,0 +1,69 @@ +use anyhow::Result; +use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; +use librespot::{ + core::{connection::AuthenticationError, Session, SessionConfig}, + discovery::Credentials, + protocol::{authentication::AuthenticationType, keyexchange::ErrorCode}, +}; +use log::trace; + +pub async fn validate_token( + username: impl Into, + token: impl Into, +) -> Result> { + let auth_data = BASE64.decode(token.into())?; + + let credentials = Credentials { + username: username.into(), + auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS, + auth_data, + }; + + trace!("Validating session token for {}", credentials.username); + + let new_credentials = request_session_token(credentials.clone()).await?; + + if credentials.auth_data != new_credentials.auth_data { + trace!("New session token retrieved for {}", credentials.username); + + return Ok(Some(BASE64.encode(new_credentials.auth_data))); + } + + Ok(None) +} + +pub async fn request_session_token(credentials: Credentials) -> Result { + trace!("Requesting session token for {}", credentials.username); + + let session = Session::new(SessionConfig::default(), None); + let mut tries = 0; + + Ok(loop { + let (host, port) = session.apresolver().resolve("accesspoint").await?; + let mut transport = librespot::core::connection::connect(&host, port, None).await?; + + match librespot::core::connection::authenticate( + &mut transport, + credentials.clone(), + &session.config().device_id, + ) + .await + { + Ok(creds) => break creds, + Err(e) => { + if let Some(AuthenticationError::LoginFailed(ErrorCode::TryAnotherAP)) = + e.error.downcast_ref::() + { + tries += 1; + if tries > 3 { + return Err(e.into()); + } + + continue; + } else { + return Err(e.into()); + } + } + }; + }) +} diff --git a/src/audio/mod.rs b/src/audio/mod.rs deleted file mode 100644 index b038491..0000000 --- a/src/audio/mod.rs +++ /dev/null @@ -1,85 +0,0 @@ -pub mod stream; - -use self::stream::Stream; - -use librespot::playback::audio_backend::{Sink, SinkAsBytes, SinkError, SinkResult}; -use librespot::playback::convert::Converter; -use librespot::playback::decoder::AudioPacket; -use log::error; -use std::io::Write; -use tokio::sync::mpsc::UnboundedSender; - -pub enum SinkEvent { - Start, - Stop, -} - -pub struct StreamSink { - stream: Stream, - sender: UnboundedSender, -} - -impl StreamSink { - pub fn new(stream: Stream, sender: UnboundedSender) -> Self { - Self { stream, sender } - } -} - -impl Sink for StreamSink { - fn start(&mut self) -> SinkResult<()> { - if let Err(why) = self.sender.send(SinkEvent::Start) { - // WARNING: Returning an error causes librespot-playback to exit the process with status 1 - - error!("Failed to send start playback event: {why}"); - return Err(SinkError::ConnectionRefused(why.to_string())); - } - - Ok(()) - } - - fn stop(&mut self) -> SinkResult<()> { - if let Err(why) = self.sender.send(SinkEvent::Stop) { - // WARNING: Returning an error causes librespot-playback to exit the process with status 1 - - error!("Failed to send start playback event: {why}"); - return Err(SinkError::ConnectionRefused(why.to_string())); - } - - self.stream.flush().ok(); - - Ok(()) - } - - fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> { - use zerocopy::AsBytes; - - let AudioPacket::Samples(samples) = packet else { - return Ok(()); - }; - let samples_f32: &[f32] = &converter.f64_to_f32(&samples); - - let resampled = samplerate::convert( - 44100, - 48000, - 2, - samplerate::ConverterType::Linear, - samples_f32, - ) - .expect("to succeed"); - - self.write_bytes(resampled.as_bytes())?; - - Ok(()) - } -} - -impl SinkAsBytes for StreamSink { - fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> { - self - .stream - .write_all(data) - .map_err(|why| SinkError::OnWrite(why.to_string()))?; - - Ok(()) - } -} diff --git a/src/audio/stream.rs b/src/audio/stream.rs deleted file mode 100644 index f8d2468..0000000 --- a/src/audio/stream.rs +++ /dev/null @@ -1,90 +0,0 @@ -use std::{ - io::{Read, Seek, Write}, - sync::{Arc, Condvar, Mutex}, -}; - -use songbird::input::reader::MediaSource; - -/// The lower the value, the less latency -/// -/// Too low of a value results in unpredictable audio -const MAX_SIZE: usize = 32 * 1024; - -#[derive(Clone)] -pub struct Stream { - inner: Arc<(Mutex>, Condvar)>, -} - -impl Stream { - pub fn new() -> Self { - Self { - inner: Arc::new((Mutex::new(Vec::new()), Condvar::new())), - } - } -} - -impl Read for Stream { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - let (mutex, condvar) = &*self.inner; - let mut buffer = mutex.lock().expect("Mutex was poisoned"); - - // Prevent Discord jitter by filling buffer with zeroes if we don't have any audio - // (i.e. when you skip too far ahead in a song which hasn't been downloaded yet) - if buffer.is_empty() { - buf.fill(0); - condvar.notify_all(); - - return Ok(buf.len()); - } - - let max_read = usize::min(buf.len(), buffer.len()); - - buf[0..max_read].copy_from_slice(&buffer[0..max_read]); - buffer.drain(0..max_read); - condvar.notify_all(); - - Ok(max_read) - } -} - -impl Write for Stream { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - let (mutex, condvar) = &*self.inner; - let mut buffer = mutex.lock().expect("Mutex was poisoned"); - - while buffer.len() + buf.len() > MAX_SIZE { - buffer = condvar.wait(buffer).expect("Mutex was poisoned"); - } - - buffer.extend_from_slice(buf); - condvar.notify_all(); - - Ok(buf.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - let (mutex, condvar) = &*self.inner; - let mut buffer = mutex.lock().expect("Mutex was poisoned"); - - buffer.clear(); - condvar.notify_all(); - - Ok(()) - } -} - -impl Seek for Stream { - fn seek(&mut self, _: std::io::SeekFrom) -> std::io::Result { - Ok(0) - } -} - -impl MediaSource for Stream { - fn byte_len(&self) -> Option { - None - } - - fn is_seekable(&self) -> bool { - false - } -} diff --git a/src/bot.rs b/src/bot.rs new file mode 100644 index 0000000..941486e --- /dev/null +++ b/src/bot.rs @@ -0,0 +1,153 @@ +use std::sync::Arc; + +use anyhow::{anyhow, Result}; +use log::{debug, info}; +use poise::{serenity_prelude, Framework, FrameworkContext, FrameworkOptions}; +use serenity::all::{ActivityData, FullEvent, Ready, ShardManager}; +use spoticord_database::Database; +use spoticord_session::manager::SessionManager; + +use crate::commands; + +#[cfg(feature = "stats")] +use spoticord_stats::StatsManager; + +pub type Context<'a> = poise::Context<'a, Data, anyhow::Error>; +pub type FrameworkError<'a> = poise::FrameworkError<'a, Data, anyhow::Error>; + +type Data = SessionManager; + +// pub struct Data { +// pub database: Database, +// pub session_manager: SessionManager, +// } + +pub fn framework_opts() -> FrameworkOptions { + poise::FrameworkOptions { + commands: vec![ + #[cfg(debug_assertions)] + commands::debug::ping(), + #[cfg(debug_assertions)] + commands::debug::token(), + commands::core::help(), + commands::core::version(), + commands::core::rename(), + commands::core::link(), + commands::core::unlink(), + commands::music::join(), + commands::music::disconnect(), + commands::music::stop(), + commands::music::playing(), + commands::music::lyrics(), + ], + event_handler: |ctx, event, framework, data| { + Box::pin(event_handler(ctx, event, framework, data)) + }, + ..Default::default() + } +} + +pub async fn setup( + ctx: &serenity_prelude::Context, + ready: &Ready, + framework: &Framework, + database: Database, +) -> Result { + info!("Successfully logged in as {}", ready.user.name); + + #[cfg(debug_assertions)] + poise::builtins::register_in_guild( + ctx, + &framework.options().commands, + std::env::var("GUILD_ID")?.parse()?, + ) + .await?; + + #[cfg(not(debug_assertions))] + poise::builtins::register_globally(ctx, &framework.options().commands).await?; + + let songbird = songbird::get(ctx) + .await + .ok_or_else(|| anyhow!("Songbird was not registered during setup"))?; + + let manager = SessionManager::new(songbird, database); + + #[cfg(feature = "stats")] + let stats = StatsManager::new(std::env::var("KV_URL")?)?; + + tokio::spawn(background_loop( + manager.clone(), + framework.shard_manager().clone(), + #[cfg(feature = "stats")] + stats, + )); + + Ok(manager) +} + +async fn event_handler( + ctx: &serenity_prelude::Context, + event: &FullEvent, + _framework: FrameworkContext<'_, Data, anyhow::Error>, + _data: &Data, +) -> Result<()> { + if let FullEvent::Ready { data_about_bot } = event { + if let Some(shard) = data_about_bot.shard { + debug!( + "Shard {} logged in (total shards: {})", + shard.id.0, shard.total + ); + } + + ctx.set_activity(Some(ActivityData::listening(spoticord_config::MOTD))); + } + + Ok(()) +} + +async fn background_loop( + session_manager: SessionManager, + shard_manager: Arc, + #[cfg(feature = "stats")] mut stats_manager: spoticord_stats::StatsManager, +) { + #[cfg(feature = "stats")] + use log::{error, trace}; + + loop { + tokio::select! { + _ = tokio::time::sleep(std::time::Duration::from_secs(60)) => { + #[cfg(feature = "stats")] + { + trace!("Retrieving active sessions count for stats"); + + let mut count = 0; + + for session in session_manager.get_all_sessions() { + if matches!(session.active().await, Ok(true)) { + count += 1; + } + } + + if let Err(why) = stats_manager.set_active_count(count) { + error!("Failed to update active sessions: {why}"); + } else { + trace!("Active session count set to: {count}"); + } + } + } + + _ = tokio::signal::ctrl_c() => { + info!("Received interrupt signal, shutting down..."); + + session_manager.shutdown_all().await; + shard_manager.shutdown_all().await; + + #[cfg(feature = "stats")] + stats_manager.set_active_count(0).ok(); + + + break; + } + } + } +} diff --git a/src/bot/commands/core/help.rs b/src/bot/commands/core/help.rs deleted file mode 100644 index 531da30..0000000 --- a/src/bot/commands/core/help.rs +++ /dev/null @@ -1,40 +0,0 @@ -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::interaction::application_command::ApplicationCommandInteraction, - prelude::Context, -}; - -use crate::{ - bot::commands::{respond_message, CommandOutput}, - utils::embed::{EmbedBuilder, Status}, -}; - -pub const NAME: &str = "help"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Spoticord Help") - .icon_url("https://spoticord.com/logo-standard.webp") - .description("**Welcome to Spoticord** - It seems you have requested some help. Not to worry, we can help you out.\n - **Not sure how the bot works?** - **[Click here](https://spoticord.com/#how-to)** for a quick overview about how to set up Spoticord and how to use it.\n - **Which commands are there?** - You can find all **[the commands](https://spoticord.com/#commands)** on the website. You may also just type `/` in Discord and see which commands are available there.\n - **Need more help?** - If you still need some help, whether you are having issues with the bot or you just want to give us some feedback, you can join our **[Discord server](https://discord.gg/wRCyhVqBZ5)**.".to_string()) - .status(Status::Info) - .build(), - false, - ) - .await; - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command.name(NAME).description("Shows the help message") -} diff --git a/src/bot/commands/core/link.rs b/src/bot/commands/core/link.rs deleted file mode 100644 index bf606d6..0000000 --- a/src/bot/commands/core/link.rs +++ /dev/null @@ -1,159 +0,0 @@ -use log::error; -use reqwest::StatusCode; -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::interaction::application_command::ApplicationCommandInteraction, - prelude::Context, -}; - -use crate::{ - bot::commands::{respond_message, CommandOutput}, - consts::SPOTICORD_ACCOUNTS_URL, - database::{Database, DatabaseError}, - utils::embed::{EmbedBuilder, Status}, -}; - -pub const NAME: &str = "link"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - let data = ctx.data.read().await; - let database = data.get::().expect("to contain a value"); - - if database - .get_user_account(command.user.id.to_string()) - .await - .is_ok() - { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("You have already linked your Spotify account.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - - if let Ok(request) = database.get_user_request(command.user.id.to_string()).await { - let link = format!( - "{}/spotify/{}", - SPOTICORD_ACCOUNTS_URL.as_str(), - request.token - ); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Link your Spotify account") - .title_url(&link) - .icon_url("https://spoticord.com/spotify-logo.png") - .description(format!( - "Go to [this link]({}) to connect your Spotify account.", - link - )) - .status(Status::Info) - .build(), - true, - ) - .await; - - return; - } - - // Check if user exists, if not, create them - if let Err(why) = database.get_user(command.user.id.to_string()).await { - match why { - DatabaseError::InvalidStatusCode(StatusCode::NOT_FOUND) => { - if let Err(why) = database.create_user(command.user.id.to_string()).await { - error!("Error creating user: {:?}", why); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("Something went wrong while trying to link your Spotify account.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - } - - _ => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("Something went wrong while trying to link your Spotify account.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - } - } - - match database - .create_user_request(command.user.id.to_string()) - .await - { - Ok(request) => { - let link = format!( - "{}/spotify/{}", - SPOTICORD_ACCOUNTS_URL.as_str(), - request.token - ); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Link your Spotify account") - .title_url(&link) - .icon_url("https://spoticord.com/spotify-logo.png") - .description(format!( - "Go to [this link]({}) to connect your Spotify account.", - link - )) - .status(Status::Info) - .build(), - true, - ) - .await; - } - - Err(why) => { - error!("Error creating user request: {:?}", why); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("An error occurred while serving your request. Please try again later.") - .status(Status::Error) - .build(), - true, - ) - .await; - } - }; - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name(NAME) - .description("Link your Spotify account to Spoticord") -} diff --git a/src/bot/commands/core/mod.rs b/src/bot/commands/core/mod.rs deleted file mode 100644 index 39aa8fd..0000000 --- a/src/bot/commands/core/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub mod help; -pub mod link; -pub mod rename; -pub mod unlink; -pub mod version; diff --git a/src/bot/commands/core/rename.rs b/src/bot/commands/core/rename.rs deleted file mode 100644 index 36f1d5a..0000000 --- a/src/bot/commands/core/rename.rs +++ /dev/null @@ -1,165 +0,0 @@ -use log::error; -use reqwest::StatusCode; -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::{ - command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction, - }, - prelude::Context, -}; - -use crate::{ - bot::commands::{respond_message, CommandOutput}, - database::{Database, DatabaseError}, - utils::{ - self, - embed::{EmbedBuilder, Status}, - }, -}; - -pub const NAME: &str = "rename"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - let data = ctx.data.read().await; - let database = data.get::().expect("to contain a value"); - - // Check if user exists, if not, create them - if let Err(why) = database.get_user(command.user.id.to_string()).await { - match why { - DatabaseError::InvalidStatusCode(StatusCode::NOT_FOUND) => { - if let Err(why) = database.create_user(command.user.id.to_string()).await { - error!("Error creating user: {:?}", why); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("Something went wrong while trying to rename your Spoticord device.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - } - - _ => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("Something went wrong while trying to rename your Spoticord device.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - } - } - - let device_name = match command.data.options.get(0) { - Some(option) => match option.value { - Some(ref value) => value.as_str().expect("to be a string").to_string(), - None => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("You need to provide a name for your Spoticord device.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }, - None => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("You need to provide a name for your Spoticord device.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }; - - if let Err(why) = database - .update_user_device_name(command.user.id.to_string(), &device_name) - .await - { - if let DatabaseError::InvalidInputBody(_) = why { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description( - "Your device name must not exceed 16 characters and be at least 1 character long.", - ) - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - - error!("Error updating user device name: {:?}", why); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("Something went wrong while trying to rename your Spoticord device.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description(format!( - "Successfully changed the Spotify device name to **{}**", - utils::discord::escape(device_name) - )) - .status(Status::Success) - .build(), - true, - ) - .await; - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name(NAME) - .description("Set a new device name that is displayed in Spotify") - .create_option(|option| { - option - .name("name") - .description("The new device name") - .kind(CommandOptionType::String) - .max_length(16) - .required(true) - }) -} diff --git a/src/bot/commands/core/unlink.rs b/src/bot/commands/core/unlink.rs deleted file mode 100644 index 99362d2..0000000 --- a/src/bot/commands/core/unlink.rs +++ /dev/null @@ -1,83 +0,0 @@ -use log::error; -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::interaction::application_command::ApplicationCommandInteraction, - prelude::Context, -}; - -use crate::{ - bot::commands::{respond_message, CommandOutput}, - database::{Database, DatabaseError}, - session::manager::SessionManager, - utils::embed::{EmbedBuilder, Status}, -}; - -pub const NAME: &str = "unlink"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - let data = ctx.data.read().await; - let database = data.get::().expect("to contain a value"); - let session_manager = data.get::().expect("to contain a value"); - - // Disconnect session if user has any - if let Some(session) = session_manager.find(command.user.id).await { - session.disconnect().await; - } - - // Check if user exists in the first place - if let Err(why) = database - .delete_user_account(command.user.id.to_string()) - .await - { - if let DatabaseError::InvalidStatusCode(status) = why { - if status == 404 { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("You cannot unlink your Spotify account if you haven't linked one.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - } - - error!("Error deleting user account: {:?}", why); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("An unexpected error has occured while trying to unlink your account. Please try again later.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("Successfully unlinked your Spotify account from Spoticord") - .status(Status::Success) - .build(), - true, - ) - .await; - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name(NAME) - .description("Unlink your Spotify account from Spoticord") -} diff --git a/src/bot/commands/core/version.rs b/src/bot/commands/core/version.rs deleted file mode 100644 index 8292870..0000000 --- a/src/bot/commands/core/version.rs +++ /dev/null @@ -1,46 +0,0 @@ -use log::error; -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::interaction::{ - application_command::ApplicationCommandInteraction, InteractionResponseType, - }, - prelude::Context, -}; - -use crate::{bot::commands::CommandOutput, consts::VERSION, utils::embed::Status}; - -pub const NAME: &str = "version"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - if let Err(why) = command - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message.embed(|embed| { - embed - .title("Spoticord Version") - .author(|author| { - author - .name("Maintained by: RoDaBaFilms") - .url("https://rodabafilms.com/") - .icon_url("https://cdn.discordapp.com/avatars/389786424142200835/6bfe3840b0aa6a1baf432bb251b70c9f.webp?size=128") - }) - .description(format!("Current version: {}\n\nSpoticord is open source, check out [our GitHub](https://github.com/SpoticordMusic)", VERSION)) - .color(Status::Info as u64) - }) - }) - }) - .await - { - error!("Error sending message: {:?}", why); - } - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name(NAME) - .description("Shows the current running version of Spoticord") -} diff --git a/src/bot/commands/mod.rs b/src/bot/commands/mod.rs deleted file mode 100644 index d065a0f..0000000 --- a/src/bot/commands/mod.rs +++ /dev/null @@ -1,309 +0,0 @@ -use std::{collections::HashMap, future::Future, pin::Pin}; - -use log::{debug, error}; -use serenity::{ - builder::{CreateApplicationCommand, CreateApplicationCommands}, - model::application::command::Command, - model::prelude::{ - interaction::{ - application_command::ApplicationCommandInteraction, - message_component::MessageComponentInteraction, InteractionResponseType, - }, - GuildId, - }, - prelude::{Context, TypeMapKey}, -}; - -use crate::utils::embed::{make_embed_message, EmbedMessageOptions}; - -mod core; -mod music; - -#[cfg(debug_assertions)] -mod ping; - -#[cfg(debug_assertions)] -mod token; - -pub async fn respond_message( - ctx: &Context, - command: &ApplicationCommandInteraction, - options: EmbedMessageOptions, - ephemeral: bool, -) { - if let Err(why) = command - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message - .embed(|embed| make_embed_message(embed, options)) - .ephemeral(ephemeral) - }) - }) - .await - { - error!("Error sending message: {:?}", why); - } -} - -pub async fn respond_component_message( - ctx: &Context, - component: &MessageComponentInteraction, - options: EmbedMessageOptions, - ephemeral: bool, -) { - if let Err(why) = component - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message - .embed(|embed| make_embed_message(embed, options)) - .ephemeral(ephemeral) - }) - }) - .await - { - error!("Error sending message: {:?}", why); - } -} - -pub async fn update_message( - ctx: &Context, - command: &ApplicationCommandInteraction, - options: EmbedMessageOptions, -) { - if let Err(why) = command - .edit_original_interaction_response(&ctx.http, |message| { - message.embed(|embed| make_embed_message(embed, options)) - }) - .await - { - error!("Error sending message: {:?}", why); - } -} - -pub async fn defer_message( - ctx: &Context, - command: &ApplicationCommandInteraction, - ephemeral: bool, -) { - if let Err(why) = command - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::DeferredChannelMessageWithSource) - .interaction_response_data(|message| message.ephemeral(ephemeral)) - }) - .await - { - error!("Error deferring message: {:?}", why); - } -} - -pub type CommandOutput = Pin + Send>>; -pub type CommandExecutor = fn(Context, ApplicationCommandInteraction) -> CommandOutput; -pub type ComponentExecutor = fn(Context, MessageComponentInteraction) -> CommandOutput; - -#[derive(Clone)] -pub struct CommandManager { - commands: HashMap, -} - -#[derive(Clone)] -pub struct CommandInfo { - pub name: String, - pub command_executor: CommandExecutor, - pub component_executor: Option, - pub register: fn(&mut CreateApplicationCommand) -> &mut CreateApplicationCommand, -} - -impl CommandManager { - pub fn new() -> Self { - let mut instance = Self { - commands: HashMap::new(), - }; - - // Debug-only commands - #[cfg(debug_assertions)] - { - instance.insert(ping::NAME, ping::register, ping::command, None); - instance.insert(token::NAME, token::register, token::command, None); - } - - // Core commands - instance.insert( - core::help::NAME, - core::help::register, - core::help::command, - None, - ); - instance.insert( - core::version::NAME, - core::version::register, - core::version::command, - None, - ); - instance.insert( - core::link::NAME, - core::link::register, - core::link::command, - None, - ); - instance.insert( - core::unlink::NAME, - core::unlink::register, - core::unlink::command, - None, - ); - instance.insert( - core::rename::NAME, - core::rename::register, - core::rename::command, - None, - ); - - // Music commands - instance.insert( - music::join::NAME, - music::join::register, - music::join::command, - None, - ); - instance.insert( - music::leave::NAME, - music::leave::register, - music::leave::command, - None, - ); - instance.insert( - music::playing::NAME, - music::playing::register, - music::playing::command, - Some(music::playing::component), - ); - - instance - } - - pub fn insert( - &mut self, - name: impl Into, - register: fn(&mut CreateApplicationCommand) -> &mut CreateApplicationCommand, - command_executor: CommandExecutor, - component_executor: Option, - ) { - let name = name.into(); - - self.commands.insert( - name.clone(), - CommandInfo { - name, - register, - command_executor, - component_executor, - }, - ); - } - - pub async fn register(&self, ctx: &Context) { - let cmds = &self.commands; - - debug!( - "Registering {} command{}", - cmds.len(), - if cmds.len() == 1 { "" } else { "s" } - ); - - fn _register_commands<'a>( - cmds: &HashMap, - mut commands: &'a mut CreateApplicationCommands, - ) -> &'a mut CreateApplicationCommands { - for command_info in cmds.values() { - commands = commands.create_application_command(|command| (command_info.register)(command)); - } - - commands - } - - if let Ok(guild_id) = std::env::var("GUILD_ID") { - if let Ok(guild_id) = guild_id.parse::() { - let guild_id = GuildId(guild_id); - guild_id - .set_application_commands(&ctx.http, |command| _register_commands(cmds, command)) - .await - .expect("Failed to create guild commands"); - - return; - } - } - - Command::set_global_application_commands(&ctx.http, |command| { - _register_commands(cmds, command) - }) - .await - .expect("Failed to create global commands"); - } - - // On slash command interaction - pub async fn execute_command(&self, ctx: &Context, interaction: ApplicationCommandInteraction) { - let command = self.commands.get(&interaction.data.name); - - if let Some(command) = command { - (command.command_executor)(ctx.clone(), interaction.clone()).await; - } else { - // Command does not exist - if let Err(why) = interaction - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message - .content("Woops, that command doesn't exist") - .ephemeral(true) - }) - }) - .await - { - error!("Failed to respond to command: {}", why); - } - } - } - - // On message component interaction (e.g. button) - pub async fn execute_component(&self, ctx: &Context, interaction: MessageComponentInteraction) { - let command = match interaction.data.custom_id.split("::").next() { - Some(command) => command, - None => return, - }; - - let command = self.commands.get(command); - - if let Some(command) = command { - if let Some(executor) = command.component_executor { - executor(ctx.clone(), interaction.clone()).await; - - return; - } - } - - if let Err(why) = interaction - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message - .content("Woops, that interaction doesn't exist") - .ephemeral(true) - }) - }) - .await - { - error!("Failed to respond to interaction: {}", why); - } - } -} - -impl TypeMapKey for CommandManager { - type Value = CommandManager; -} diff --git a/src/bot/commands/music/join.rs b/src/bot/commands/music/join.rs deleted file mode 100644 index 8c5cf5f..0000000 --- a/src/bot/commands/music/join.rs +++ /dev/null @@ -1,339 +0,0 @@ -use log::error; -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::{interaction::application_command::ApplicationCommandInteraction, Channel}, - prelude::Context, -}; - -use crate::{ - bot::commands::{defer_message, respond_message, update_message, CommandOutput}, - consts::SPOTICORD_ACCOUNTS_URL, - session::manager::{SessionCreateError, SessionManager}, - utils::embed::{EmbedBuilder, Status}, -}; - -pub const NAME: &str = "join"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - let guild = ctx - .cache - .guild(command.guild_id.expect("to contain a value")) - .expect("to be present"); - - // Get the voice channel id of the calling user - let channel_id = match guild - .voice_states - .get(&command.user.id) - .and_then(|state| state.channel_id) - { - Some(channel_id) => channel_id, - None => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description("You need to connect to a voice channel") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }; - - // Check for Voice Channel permissions - { - let channel = match channel_id.to_channel(&ctx).await { - Ok(channel) => match channel { - Channel::Guild(channel) => channel, - _ => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description("The voice channel you are in is not supported") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }, - Err(why) => { - error!("Failed to get channel: {}", why); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description("The voice channel you are in is not available.\nI might not the permission to see this channel.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }; - - if let Ok(permissions) = channel.permissions_for_user(&ctx.cache, ctx.cache.current_user_id()) - { - if !permissions.view_channel() || !permissions.connect() || !permissions.speak() { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description("I do not have the permissions to connect to that voice channel") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - } - } - - // Check for Text Channel permissions - { - let channel = match command.channel_id.to_channel(&ctx).await { - Ok(channel) => match channel { - Channel::Guild(channel) => channel, - _ => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description("The text channel you are in is not supported") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }, - Err(why) => { - error!("Failed to get channel: {}", why); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description("The text channel you are in is not available.\nI might not have the permission to see this channel.") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }; - - if let Ok(permissions) = channel.permissions_for_user(&ctx.cache, ctx.cache.current_user_id()) - { - if !permissions.view_channel() || !permissions.send_messages() || !permissions.embed_links() - { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description( - "I do not have the permissions to send messages / links in this text channel", - ) - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - } - } - - let data = ctx.data.read().await; - let session_manager = data - .get::() - .expect("to contain a value") - .clone(); - - // Check if another session is already active in this server - let mut session_opt = session_manager.get_session(guild.id).await; - - if let Some(session) = &session_opt { - if let Some(owner) = session.owner().await { - let msg = if owner == command.user.id { - "You are already controlling the bot" - } else { - "The bot is currently being controlled by someone else" - }; - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description(msg) - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }; - - // Prevent duplicate Spotify sessions - if let Some(session) = session_manager.find(command.user.id).await { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description( - format!( - "You are already playing music in another server ({}).\nStop playing in that server first before joining this one.", - ctx.cache.guild(session.guild_id().await).expect("to be present").name - )).status(Status::Error).build(), - true, - ) - .await; - - return; - } - - defer_message(&ctx, &command, false).await; - - if let Some(session) = &session_opt { - if session.channel_id().await != channel_id { - session.disconnect().await; - session_opt = None; - - // Give serenity/songbird some time to register the disconnect - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - } - } - - macro_rules! report_error { - ($why:ident) => { - match $why { - // User has not linked their account - SessionCreateError::NoSpotify => { - update_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description(format!("You need to link your Spotify account. Use or go to [the accounts website]({}) to get started.", SPOTICORD_ACCOUNTS_URL.as_str())) - .status(Status::Error) - .build(), - ) - .await; - } - - // Spotify credentials have expired or are invalid - SessionCreateError::SpotifyExpired => { - update_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description(format!("Spoticord no longer has access to your Spotify account. Use or go to [the accounts website]({}) to relink your Spotify account.", SPOTICORD_ACCOUNTS_URL.as_str())) - .status(Status::Error) - .build(), - ).await; - } - - // Songbird error - SessionCreateError::JoinError(why) => { - update_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description(format!( - "An error occured while joining the channel. Please try running again.\n\nError details: `{why}`" - )) - .status(Status::Error) - .build(), - ) - .await; - } - - // Any other error - _ => { - update_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot join voice channel") - .description("An error occured while joining the channel. Please try again later.") - .status(Status::Error) - .build(), - ) - .await; - } - } - - return; - }; - } - - if let Some(session) = session_opt.as_mut() { - if let Err(why) = session.update_owner(&ctx, command.user.id).await { - report_error!(why); - } - } else { - // Create the session, and handle potential errors - if let Err(why) = session_manager - .create_session( - &ctx, - guild.id, - channel_id, - command.channel_id, - command.user.id, - ) - .await - { - report_error!(why); - }; - } - - update_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Connected to voice channel") - .icon_url("https://spoticord.com/speaker.png") - .description(format!("Come listen along in <#{}>", channel_id)) - .footer("You must manually go to Spotify and select your device") - .status(Status::Info) - .build(), - ) - .await; - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name(NAME) - .description("Request the bot to join the current voice channel") -} diff --git a/src/bot/commands/music/leave.rs b/src/bot/commands/music/leave.rs deleted file mode 100644 index ba8098b..0000000 --- a/src/bot/commands/music/leave.rs +++ /dev/null @@ -1,82 +0,0 @@ -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::interaction::application_command::ApplicationCommandInteraction, - prelude::Context, -}; - -use crate::{ - bot::commands::{respond_message, CommandOutput}, - session::manager::SessionManager, - utils::embed::{EmbedBuilder, Status}, -}; - -pub const NAME: &str = "leave"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - let data = ctx.data.read().await; - let session_manager = data - .get::() - .expect("to contain a value") - .clone(); - - let session = match session_manager - .get_session(command.guild_id.expect("to contain a value")) - .await - { - Some(session) => session, - None => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot disconnect bot") - .description("I'm currently not connected to any voice channel") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - } - }; - - if let Some(owner) = session.owner().await { - if owner != command.user.id { - // This message was generated by AI, and I love it. - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("You are not the one who summoned me") - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - }; - } - - session.disconnect().await; - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .description("I have left the voice channel, goodbye for now") - .status(Status::Info) - .build(), - false, - ) - .await; - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name(NAME) - .description("Request the bot to leave the current voice channel") -} diff --git a/src/bot/commands/music/mod.rs b/src/bot/commands/music/mod.rs deleted file mode 100644 index 88ecafd..0000000 --- a/src/bot/commands/music/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod join; -pub mod leave; -pub mod playing; diff --git a/src/bot/commands/music/playing.rs b/src/bot/commands/music/playing.rs deleted file mode 100644 index f0aae85..0000000 --- a/src/bot/commands/music/playing.rs +++ /dev/null @@ -1,461 +0,0 @@ -use std::time::Duration; - -use librespot::core::spotify_id::SpotifyId; -use log::error; -use serenity::{ - builder::{CreateApplicationCommand, CreateButton, CreateComponents, CreateEmbed}, - model::{ - prelude::{ - component::ButtonStyle, - interaction::{ - application_command::ApplicationCommandInteraction, - message_component::MessageComponentInteraction, InteractionResponseType, - }, - }, - user::User, - }, - prelude::Context, -}; - -use crate::{ - bot::commands::{respond_component_message, respond_message, CommandOutput}, - session::{manager::SessionManager, pbi::PlaybackInfo}, - utils::{ - self, - embed::{EmbedBuilder, Status}, - }, -}; - -pub const NAME: &str = "playing"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - macro_rules! not_playing { - () => { - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("Cannot get track info") - .icon_url("https://spoticord.com/forbidden.png") - .description("I'm currently not playing any music in this server") - .status(Status::Error) - .build(), - true, - ) - .await; - }; - } - - let data = ctx.data.read().await; - let session_manager = data - .get::() - .expect("to contain a value") - .clone(); - - let Some(session) = session_manager - .get_session(command.guild_id.expect("to contain a value")) - .await - else { - not_playing!(); - - return; - }; - - let Some(owner) = session.owner().await else { - not_playing!(); - - return; - }; - - // Get Playback Info from session - let Some(pbi) = session.playback_info().await else { - not_playing!(); - - return; - }; - - // Get owner of session - let Some(owner) = utils::discord::get_user(&ctx, owner).await else { - // This shouldn't happen - - error!("Could not find user with ID: {owner}"); - - respond_message( - &ctx, - &command, - EmbedBuilder::new() - .title("[INTERNAL ERROR] Cannot get track info") - .description(format!( - "Could not find user with ID `{}`\nThis is an issue with the bot!", - owner - )) - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - }; - - // Get metadata - let (title, description, thumbnail) = get_metadata(&pbi); - - if let Err(why) = command - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message - .set_embed(build_playing_embed( - title, - pbi.get_type(), - pbi.spotify_id, - description, - owner, - thumbnail, - )) - .components(|components| create_button(components, pbi.is_playing)) - }) - }) - .await - { - error!("Error sending message: {why:?}"); - } - }) -} - -pub fn component(ctx: Context, mut interaction: MessageComponentInteraction) -> CommandOutput { - Box::pin(async move { - let error_message = |title: &'static str, description: &'static str| async { - respond_component_message( - &ctx, - &interaction, - EmbedBuilder::new() - .title(title.to_string()) - .icon_url("https://spoticord.com/forbidden.png") - .description(description.to_string()) - .status(Status::Error) - .build(), - true, - ) - .await; - }; - - let error_edit = |title: &'static str, description: &'static str| { - let mut interaction = interaction.clone(); - let ctx = ctx.clone(); - - async move { - interaction.defer(&ctx.http).await.ok(); - - if let Err(why) = interaction - .message - .edit(&ctx, |message| { - message.embed(|embed| { - embed - .description(description) - .author(|author| { - author - .name(title) - .icon_url("https://spoticord.com/forbidden.png") - }) - .color(Status::Error) - }) - }) - .await - { - error!("Failed to update playing message: {why}"); - } - } - }; - - let data = ctx.data.read().await; - let session_manager = data - .get::() - .expect("to contain a value") - .clone(); - - // Check if session still exists - let Some(mut session) = session_manager - .get_session(interaction.guild_id.expect("to contain a value")) - .await - else { - error_edit( - "Cannot perform action", - "I'm currently not playing any music in this server", - ) - .await; - - return; - }; - - // Check if the session contains an owner - let Some(owner) = session.owner().await else { - error_edit( - "Cannot change playback state", - "I'm currently not playing any music in this server", - ) - .await; - - return; - }; - - // Get Playback Info from session - let Some(pbi) = session.playback_info().await else { - error_edit( - "Cannot change playback state", - "I'm currently not playing any music in this server", - ) - .await; - - return; - }; - - // Check if the user is the owner of the session - if owner != interaction.user.id { - error_message( - "Cannot change playback state", - "You must be the host to use the media buttons", - ) - .await; - - return; - } - - // Get owner of session - let Some(owner) = utils::discord::get_user(&ctx, owner).await else { - // This shouldn't happen - - error!("Could not find user with ID: {owner}"); - - respond_component_message( - &ctx, - &interaction, - EmbedBuilder::new() - .title("[INTERNAL ERROR] Cannot get track info") - .description(format!( - "Could not find user with ID `{}`\nThis is an issue with the bot!", - owner - )) - .status(Status::Error) - .build(), - true, - ) - .await; - - return; - }; - - // Send the desired command to the session - match interaction.data.custom_id.as_str() { - "playing::btn_pause_play" => { - if pbi.is_playing { - session.pause().await - } else { - session.resume().await - } - } - - "playing::btn_previous_track" => session.previous().await, - - "playing::btn_next_track" => session.next().await, - - _ => { - error!("Unknown custom_id: {}", interaction.data.custom_id); - } - }; - - interaction.defer(&ctx.http).await.ok(); - tokio::time::sleep(Duration::from_millis( - if interaction.data.custom_id == "playing::btn_pause_play" { - 0 - } else { - 2500 - }, - )) - .await; - update_embed(&mut interaction, &ctx, owner).await; - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name(NAME) - .description("Display which song is currently being played") -} - -fn create_button(components: &mut CreateComponents, playing: bool) -> &mut CreateComponents { - let mut prev_btn = CreateButton::default(); - prev_btn - .style(ButtonStyle::Primary) - .label("<<") - .custom_id("playing::btn_previous_track"); - - let mut toggle_btn = CreateButton::default(); - toggle_btn - .style(ButtonStyle::Secondary) - .label(if playing { "Pause" } else { "Play" }) - .custom_id("playing::btn_pause_play"); - - let mut next_btn = CreateButton::default(); - next_btn - .style(ButtonStyle::Primary) - .label(">>") - .custom_id("playing::btn_next_track"); - - components.create_action_row(|ar| { - ar.add_button(prev_btn) - .add_button(toggle_btn) - .add_button(next_btn) - }) -} - -async fn update_embed(interaction: &mut MessageComponentInteraction, ctx: &Context, owner: User) { - let error_edit = |title: &'static str, description: &'static str| { - let mut interaction = interaction.clone(); - let ctx = ctx.clone(); - - async move { - interaction.defer(&ctx.http).await.ok(); - - if let Err(why) = interaction - .message - .edit(&ctx, |message| { - message.embed(|embed| { - embed - .description(description) - .author(|author| { - author - .name(title) - .icon_url("https://spoticord.com/forbidden.png") - }) - .color(Status::Error) - }) - }) - .await - { - error!("Failed to update playing message: {why}"); - } - } - }; - - let data = ctx.data.read().await; - let session_manager = data - .get::() - .expect("to contain a value") - .clone(); - - // Check if session still exists - let Some(session) = session_manager - .get_session(interaction.guild_id.expect("to contain a value")) - .await - else { - error_edit( - "Cannot perform action", - "I'm currently not playing any music in this server", - ) - .await; - - return; - }; - - // Get Playback Info from session - let Some(pbi) = session.playback_info().await else { - error_edit( - "Cannot change playback state", - "I'm currently not playing any music in this server", - ) - .await; - - return; - }; - - let (title, description, thumbnail) = get_metadata(&pbi); - - if let Err(why) = interaction - .message - .edit(&ctx, |message| { - message - .set_embed(build_playing_embed( - title, - pbi.get_type(), - pbi.spotify_id, - description, - owner, - thumbnail, - )) - .components(|components| create_button(components, pbi.is_playing)); - - message - }) - .await - { - error!("Failed to update playing message: {why}"); - } -} - -fn build_playing_embed( - title: impl Into, - audio_type: impl Into, - spotify_id: SpotifyId, - description: impl Into, - owner: User, - thumbnail: impl Into, -) -> CreateEmbed { - let mut embed = CreateEmbed::default(); - embed - .author(|author| { - author - .name("Currently Playing") - .icon_url("https://spoticord.com/spotify-logo.png") - }) - .title(title.into()) - .url(format!( - "https://open.spotify.com/{}/{}", - audio_type.into(), - spotify_id - .to_base62() - .expect("to be able to convert to base62") - )) - .description(description.into()) - .footer(|footer| footer.text(&owner.name).icon_url(owner.face())) - .thumbnail(thumbnail.into()) - .color(Status::Info); - - embed -} - -fn get_metadata(pbi: &PlaybackInfo) -> (String, String, String) { - // Create title - let title = format!("{} - {}", pbi.get_artists(), pbi.get_name()); - - // Create description - let mut description = String::new(); - - let position = pbi.get_position(); - let spot = position * 20 / pbi.duration_ms; - - description.push_str(if pbi.is_playing { "▶️ " } else { "⏸️ " }); - - for i in 0..20 { - if i == spot { - description.push('🔵'); - } else { - description.push('▬'); - } - } - - description.push_str("\n:alarm_clock: "); - description.push_str(&format!( - "{} / {}", - utils::time_to_str(position / 1000), - utils::time_to_str(pbi.duration_ms / 1000) - )); - - // Get the thumbnail image - let thumbnail = pbi.get_thumbnail_url().expect("to contain a value"); - - (title, description, thumbnail) -} diff --git a/src/bot/commands/ping.rs b/src/bot/commands/ping.rs deleted file mode 100644 index 1807889..0000000 --- a/src/bot/commands/ping.rs +++ /dev/null @@ -1,33 +0,0 @@ -use log::info; -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::interaction::{ - application_command::ApplicationCommandInteraction, InteractionResponseType, - }, - prelude::Context, -}; - -use super::CommandOutput; - -pub const NAME: &str = "ping"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - info!("Pong!"); - - command - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| message.content("Pong!")) - }) - .await - .ok(); - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name("ping") - .description("Check if the bot is alive") -} diff --git a/src/bot/commands/token.rs b/src/bot/commands/token.rs deleted file mode 100644 index 6c6977c..0000000 --- a/src/bot/commands/token.rs +++ /dev/null @@ -1,42 +0,0 @@ -use serenity::{ - builder::CreateApplicationCommand, - model::prelude::interaction::{ - application_command::ApplicationCommandInteraction, InteractionResponseType, - }, - prelude::Context, -}; - -use crate::database::Database; - -use super::CommandOutput; - -pub const NAME: &str = "token"; - -pub fn command(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutput { - Box::pin(async move { - let data = ctx.data.read().await; - let db = data.get::().expect("to contain a value"); - - let token = db.get_access_token(command.user.id.to_string()).await; - - let content = match token { - Ok(token) => format!("Your token is: {}", token), - Err(why) => format!("You don't have a token yet. (Real: {})", why), - }; - - command - .create_interaction_response(&ctx.http, |response| { - response - .kind(InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| message.content(content).ephemeral(true)) - }) - .await - .ok(); - }) -} - -pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { - command - .name("token") - .description("Get your Spotify access token") -} diff --git a/src/bot/events.rs b/src/bot/events.rs deleted file mode 100644 index f70639a..0000000 --- a/src/bot/events.rs +++ /dev/null @@ -1,136 +0,0 @@ -/* This file implements all events for the Discord gateway */ - -use super::commands::CommandManager; -use crate::consts::MOTD; -use log::*; -use serenity::{ - async_trait, - model::prelude::{ - interaction::{ - application_command::ApplicationCommandInteraction, - message_component::MessageComponentInteraction, Interaction, - }, - Activity, GuildId, Ready, - }, - prelude::{Context, EventHandler}, -}; - -// If the GUILD_ID environment variable is set, only allow commands from that guild -macro_rules! enforce_guild { - ($interaction:ident) => { - if let Ok(guild_id) = std::env::var("GUILD_ID") { - if let Ok(guild_id) = guild_id.parse::() { - let guild_id = GuildId(guild_id); - - if let Some(interaction_guild_id) = $interaction.guild_id { - if guild_id != interaction_guild_id { - return; - } - } - } - } - }; -} - -// Handler struct with a command parameter, an array of dictionary which takes a string and function -pub struct Handler; - -#[async_trait] -impl EventHandler for Handler { - // READY event, emitted when the bot/shard starts up - async fn ready(&self, ctx: Context, ready: Ready) { - let data = ctx.data.read().await; - let command_manager = data.get::().expect("to contain a value"); - - debug!("Ready received, logged in as {}", ready.user.name); - - command_manager.register(&ctx).await; - - ctx.set_activity(Activity::listening(MOTD)).await; - - info!("{} has come online", ready.user.name); - } - - // INTERACTION_CREATE event, emitted when the bot receives an interaction (slash command, button, etc.) - async fn interaction_create(&self, ctx: Context, interaction: Interaction) { - match interaction { - Interaction::ApplicationCommand(command) => handle_command(ctx, command).await, - Interaction::MessageComponent(component) => handle_component(ctx, component).await, - _ => {} - } - } -} - -async fn handle_command(ctx: Context, command: ApplicationCommandInteraction) { - enforce_guild!(command); - - // Commands must only be executed inside of guilds - - let guild_id = match command.guild_id { - Some(guild_id) => guild_id, - None => { - if let Err(why) = command - .create_interaction_response(&ctx.http, |response| { - response - .kind(serenity::model::prelude::interaction::InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message.content("You can only execute commands inside of a server") - }) - }) - .await { - error!("Failed to send run-in-guild-only error message: {}", why); - } - - return; - } - }; - - trace!( - "Received command interaction: command={} user={} guild={}", - command.data.name, - command.user.id, - guild_id - ); - - let data = ctx.data.read().await; - let command_manager = data.get::().expect("to contain a value"); - - command_manager.execute_command(&ctx, command).await; -} - -async fn handle_component(ctx: Context, component: MessageComponentInteraction) { - enforce_guild!(component); - - // Components can only be interacted with inside of guilds - - let guild_id = match component.guild_id { - Some(guild_id) => guild_id, - None => { - if let Err(why) = component - .create_interaction_response(&ctx.http, |response| { - response - .kind(serenity::model::prelude::interaction::InteractionResponseType::ChannelMessageWithSource) - .interaction_response_data(|message| { - message.content("You can only interact with components inside of a server") - }) - }) - .await { - error!("Failed to send run-in-guild-only error message: {}", why); - } - - return; - } - }; - - trace!( - "Received component interaction: command={} user={} guild={}", - component.data.custom_id, - component.user.id, - guild_id - ); - - let data = ctx.data.read().await; - let command_manager = data.get::().expect("to contain a value"); - - command_manager.execute_component(&ctx, component).await; -} diff --git a/src/bot/mod.rs b/src/bot/mod.rs deleted file mode 100644 index 2bddc4f..0000000 --- a/src/bot/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod commands; -pub mod events; diff --git a/src/commands/core/help.md b/src/commands/core/help.md new file mode 100644 index 0000000..89fe3eb --- /dev/null +++ b/src/commands/core/help.md @@ -0,0 +1,24 @@ +**Welcome to Spoticord** +Looks like you could use some help! Lets go over the basics! + +**What is Spoticord?** +Spoticord is a Discord music bot that acts like a Spotify speaker. + +_What does that mean?_ +Well think of it as being together with a group of friends, and playing some music over a bluetooth speaker. +That is what Spoticord does, but instead of being a bluetooth speaker, it's a Discord bot! + +**Do I need Spotify Premium?** +**_Yes_**, Spotify Premium is required for this bot to work. +This is a limitation set by Spotify, and even if this wasn't the case Spoticord still wouldn't allow free users. +This is because Spoticord does not support Spotify Free "features" (ads, limited skips, etc). + +**How to use the bot** +**[Click here](https://spoticord.com/#how-to)** for a quick overview about how to set up Spoticord, and some basic usage tips. + +**What commands can I use?** +For a list of commands, you can check out [the commands section](https://spoticord.com/#commands) on the website. +You can also just type `/` in a text chat and Discord will automatically show you all available commands. + +**Still stuck on something?** +If you still need some help, feel free to join the **[Spoticord Discord Server](https://discord.gg/wRCyhVqBZ5)**. diff --git a/src/commands/core/help.rs b/src/commands/core/help.rs new file mode 100644 index 0000000..36b34d4 --- /dev/null +++ b/src/commands/core/help.rs @@ -0,0 +1,27 @@ +use anyhow::Result; +use poise::CreateReply; +use serenity::all::{CreateEmbed, CreateEmbedAuthor}; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +const HELP_MESSAGE: &str = include_str!("help.md"); + +/// Displays the help message +#[poise::command(slash_command)] +pub async fn help(ctx: Context<'_>) -> Result<()> { + ctx.send( + CreateReply::default().embed( + CreateEmbed::new() + .author( + CreateEmbedAuthor::new("Spoticord Help") + .icon_url("https://spoticord.com/logo-standard.webp"), + ) + .description(HELP_MESSAGE) + .color(Colors::Info), + ), + ) + .await?; + + Ok(()) +} diff --git a/src/commands/core/link.rs b/src/commands/core/link.rs new file mode 100644 index 0000000..d9656eb --- /dev/null +++ b/src/commands/core/link.rs @@ -0,0 +1,94 @@ +use std::fmt::Display; + +use anyhow::Result; +use log::error; +use poise::{serenity_prelude::Error, CreateReply}; +use serenity::all::{ + CreateActionRow, CreateButton, CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter, +}; +use spoticord_database::error::DatabaseResultExt; +use spoticord_utils::discord::Colors; + +use crate::bot::{Context, FrameworkError}; + +/// Link your Spotify account to Spoticord +#[poise::command(slash_command, on_error = on_error)] +pub async fn link(ctx: Context<'_>) -> Result<()> { + let db = ctx.data().database(); + let user_id = ctx.author().id.to_string(); + + if db.get_account(&user_id).await.optional()?.is_some() { + ctx.send( + CreateReply::default().embed( + CreateEmbed::new() + .title("Spotify account already linked") + .description("You already have a Spotify account linked.") + .footer(CreateEmbedFooter::new( + "If you are trying to re-link your account then please use /unlink first.", + )).color(Colors::Info), + ).ephemeral(true), + ) + .await?; + + return Ok(()); + }; + + if let Some(request) = db.get_request(&user_id).await.optional()? { + if !request.expired() { + send_link_message(ctx, request.token).await?; + return Ok(()); + } + } + + let user = db.get_or_create_user(&user_id).await?; + let request = db.create_request(user.id).await?; + + send_link_message(ctx, request.token).await?; + + Ok(()) +} + +async fn send_link_message(ctx: Context<'_>, token: impl Display) -> Result<(), Error> { + let link = format!("{}/{token}", spoticord_config::link_url()); + + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .author( + CreateEmbedAuthor::new("Link your Spotify account") + .url(&link) + .icon_url("https://spoticord.com/spotify-logo.png"), + ) + .description("Click on the button below to start linking your Spotify account.") + .color(Colors::Info), + ) + .components(vec![CreateActionRow::Buttons(vec![ + CreateButton::new_link(&link).label("Link your account"), + ])]) + .ephemeral(true), + ) + .await?; + + Ok(()) +} + +async fn on_error(error: FrameworkError<'_>) { + if let FrameworkError::Command { error, ctx, .. } = error { + error!("An error occured during linking of new account: {error}"); + + _ = ctx + .send( + CreateReply::default() + .embed( + CreateEmbed::new() + .description("An error occured whilst trying to link your account.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await; + } else { + error!("{error}") + } +} diff --git a/src/commands/core/mod.rs b/src/commands/core/mod.rs new file mode 100644 index 0000000..f553be8 --- /dev/null +++ b/src/commands/core/mod.rs @@ -0,0 +1,11 @@ +mod help; +mod link; +mod rename; +mod unlink; +mod version; + +pub use help::*; +pub use link::*; +pub use rename::*; +pub use unlink::*; +pub use version::*; diff --git a/src/commands/core/rename.rs b/src/commands/core/rename.rs new file mode 100644 index 0000000..a71257b --- /dev/null +++ b/src/commands/core/rename.rs @@ -0,0 +1,88 @@ +use anyhow::Result; +use log::error; +use poise::CreateReply; +use serenity::all::{CreateEmbed, CreateEmbedFooter}; +use spoticord_session::manager::SessionQuery; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +#[poise::command(slash_command)] +pub async fn rename( + ctx: Context<'_>, + + #[description = "The new device name"] + #[max_length = 32] + #[min_length = 1] + name: String, +) -> Result<()> { + let db = ctx.data().database(); + + let user = match db.get_or_create_user(ctx.author().id.to_string()).await { + Ok(user) => user, + Err(why) => { + error!("Error fetching user: {why}"); + + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .description("Something went wrong whilst trying to rename your Spoticord device.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + }; + + if let Err(why) = db.update_device_name(user.id, &name).await { + error!("Error updating user device name: {why}"); + + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .description( + "Something went wrong while trying to rename your Spoticord device.", + ) + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + let has_session = ctx + .data() + .get_session(SessionQuery::Owner(ctx.author().id)) + .is_some(); + + ctx.send( + CreateReply::default() + .embed({ + let mut embed = CreateEmbed::new() + .description(format!( + "Successfully changed the Spotify device name to **{}**", + spoticord_utils::discord::escape(name) + )) + .color(Colors::Success); + + if has_session { + embed = embed.footer(CreateEmbedFooter::new( + "You must reconnect the player for the new name to show up", + )); + } + + embed + }) + .ephemeral(true), + ) + .await?; + + Ok(()) +} diff --git a/src/commands/core/unlink.rs b/src/commands/core/unlink.rs new file mode 100644 index 0000000..e55f791 --- /dev/null +++ b/src/commands/core/unlink.rs @@ -0,0 +1,79 @@ +use anyhow::Result; +use log::error; +use poise::CreateReply; +use serenity::all::{CreateEmbed, CreateEmbedFooter}; +use spoticord_session::manager::SessionQuery; +use spoticord_utils::discord::Colors; + +use crate::bot::{Context, FrameworkError}; + +/// Unlink your Spotify account from Spoticord +#[poise::command(slash_command, on_error = on_error)] +pub async fn unlink(ctx: Context<'_>) -> Result<()> { + let manager = ctx.data(); + let db = manager.database(); + let user_id = ctx.author().id.to_string(); + + // Disconnect session if user has any + if let Some(session) = manager.get_session(SessionQuery::Owner(ctx.author().id)) { + session.shutdown_player().await; + } + + if db.delete_account(&user_id).await? == 0 { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("No Spotify account linked") + .description( + "You cannot unlink your Spotify account if you haven't linked one.", + ) + .footer(CreateEmbedFooter::new( + "You can use /link to link a new Spotify account.", + )) + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Account unlinked") + .description("You have unlinked your Spotify account from Spoticord.") + .footer(CreateEmbedFooter::new( + "Changed your mind? You can use /link to link a new Spotify account.", + )) + .color(Colors::Success), + ) + .ephemeral(true), + ) + .await?; + + Ok(()) +} + +async fn on_error(error: FrameworkError<'_>) { + if let FrameworkError::Command { error, ctx, .. } = error { + error!("An error occured during linking of new account: {error}"); + + _ = ctx + .send( + CreateReply::default() + .embed( + CreateEmbed::new() + .description("An error occured whilst trying to unlink your account.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await; + } else { + error!("{error}") + } +} diff --git a/src/commands/core/version.rs b/src/commands/core/version.rs new file mode 100644 index 0000000..ce6073f --- /dev/null +++ b/src/commands/core/version.rs @@ -0,0 +1,33 @@ +use anyhow::Result; +use poise::CreateReply; +use serenity::all::{CreateEmbed, CreateEmbedAuthor}; +use spoticord_config::VERSION; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +const IMAGE_URL: &str = "https://cdn.discordapp.com/avatars/389786424142200835/6bfe3840b0aa6a1baf432bb251b70c9f.webp?size=128"; + +/// Shows the current active version of Spoticord +#[poise::command(slash_command)] +pub async fn version(ctx: Context<'_>) -> Result<()> { + // Had to pull this from the builder as rustfmt refused to format the file + let description = format!("Current version: {}\n\nSpoticord is open source, check it out [on GitHub](https://github.com/SpoticordMusic)", VERSION); + + ctx.send( + CreateReply::default().embed( + CreateEmbed::default() + .title("Spoticord Version") + .author( + CreateEmbedAuthor::new("Maintained by: DaXcess (@daxcess)") + .url("https://github.com/DaXcess") + .icon_url(IMAGE_URL), + ) + .description(description) + .color(Colors::Info), + ), + ) + .await?; + + Ok(()) +} diff --git a/src/commands/debug/mod.rs b/src/commands/debug/mod.rs new file mode 100644 index 0000000..32d3097 --- /dev/null +++ b/src/commands/debug/mod.rs @@ -0,0 +1,5 @@ +mod ping; +mod token; + +pub use ping::*; +pub use token::*; diff --git a/src/commands/debug/ping.rs b/src/commands/debug/ping.rs new file mode 100644 index 0000000..ce2b0c6 --- /dev/null +++ b/src/commands/debug/ping.rs @@ -0,0 +1,16 @@ +use anyhow::Result; +use log::info; +use poise::CreateReply; + +use crate::bot::Context; + +/// Very simple ping command +#[poise::command(slash_command)] +pub async fn ping(ctx: Context<'_>) -> Result<()> { + info!("Pong"); + + ctx.send(CreateReply::default().content("Pong!").reply(true)) + .await?; + + Ok(()) +} diff --git a/src/commands/debug/token.rs b/src/commands/debug/token.rs new file mode 100644 index 0000000..cfa48f0 --- /dev/null +++ b/src/commands/debug/token.rs @@ -0,0 +1,28 @@ +use anyhow::Result; +use poise::CreateReply; +use spoticord_database::error::DatabaseError; + +use crate::bot::Context; + +/// Retrieve the Spotify access token. For debugging purposes. +#[poise::command(slash_command)] +pub async fn token(ctx: Context<'_>) -> Result<()> { + let token = ctx + .data() + .database() + .get_access_token(ctx.author().id.to_string()) + .await; + + let content = match token { + Ok(token) => format!("Your token is:\n```\n{token}\n```"), + Err(DatabaseError::NotFound) => { + "You must authenticate first before requesting a token".to_string() + } + Err(why) => format!("Failed to retrieve access token: {why}"), + }; + + ctx.send(CreateReply::default().content(content).ephemeral(true)) + .await?; + + Ok(()) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000..1598478 --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,5 @@ +pub mod core; +pub mod music; + +#[cfg(debug_assertions)] +pub mod debug; diff --git a/src/commands/music/disconnect.rs b/src/commands/music/disconnect.rs new file mode 100644 index 0000000..63d93a8 --- /dev/null +++ b/src/commands/music/disconnect.rs @@ -0,0 +1,59 @@ +use anyhow::Error; +use poise::CreateReply; +use serenity::all::CreateEmbed; +use spoticord_session::manager::SessionQuery; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +#[poise::command(slash_command, guild_only, aliases("leave"))] +pub async fn disconnect(ctx: Context<'_>) -> Result<(), Error> { + let manager = ctx.data(); + let guild = ctx.guild().expect("poise lied to me").id; + + let Some(session) = manager.get_session(SessionQuery::Guild(guild)) else { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot disconnect bot") + .description("I'm currently not connected to any voice channel.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + }; + + if session.active().await? && session.owner().await? != ctx.author().id { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot disconnect bot") + .description("Only the host may disconnect the bot.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + session.disconnect().await; + + ctx.send( + CreateReply::default().embed( + CreateEmbed::new() + .title("Goodbye, for now!") + .description("I have left the voice channel, goodbye for now.") + .color(Colors::Info), + ), + ) + .await?; + + Ok(()) +} diff --git a/src/commands/music/join.rs b/src/commands/music/join.rs new file mode 100644 index 0000000..258fa6e --- /dev/null +++ b/src/commands/music/join.rs @@ -0,0 +1,248 @@ +use std::time::Duration; + +use anyhow::Result; +use log::error; +use poise::CreateReply; +use serenity::all::{ + Channel, ChannelId, CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter, Guild, UserId, +}; +use spoticord_database::error::DatabaseError; +use spoticord_session::manager::SessionQuery; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +/// Join the current voice channel +#[poise::command(slash_command, guild_only)] +pub async fn join(ctx: Context<'_>) -> Result<()> { + let guild: Guild = ctx.guild().expect("poise lied to me").clone(); + let manager = ctx.data(); + + let Some(channel) = guild + .voice_states + .get(&ctx.author().id) + .and_then(|state| state.channel_id) + else { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot join voice channel") + .description("You need to connect to a voice channel before running /join") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + }; + + if !has_voice_permissions(ctx, channel).await? { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot join voice channel") + .description( + "The voice channel you are in is not available. + I might not have the permissions to see this channel.", + ) + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + if !has_text_permissions(ctx, ctx.channel_id()).await? { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot join voice channel") + .description( + "I do not have permissions to send messages / links in this text channel.", + ) + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + // Check whether the user has linked their Spotify account + if let Err(DatabaseError::NotFound) = manager + .database() + .get_account(ctx.author().id.to_string()) + .await + { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("No Spotify account") + .description( + "You need to link your Spotify account to Spoticord before being able to use it.\nUse the `/link` command to link your account.", + ) + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + ctx.defer().await?; + + let mut session_opt = manager.get_session(SessionQuery::Guild(guild.id)); + + // Check if this server already has a session active + if let Some(session) = &session_opt { + if session.active().await? { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Spoticord is busy") + .description("Spoticord is already being used in this server.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + } + + // Prevent the user from using Spoticord simultaneously in multiple servers + if let Some(session) = manager.get_session(SessionQuery::Owner(ctx.author().id)) { + let server_name = session.guild().to_partial_guild(&ctx).await?.name; + + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("You are already using Spoticord") + .description(format!( + "You are already using Spoticord in `{}`\n\n\ + Stop playing in that server first before starting a new session.", + spoticord_utils::discord::escape(server_name) + )), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + if let Some(session) = &session_opt { + if session.voice_channel() != channel { + session.disconnect().await; + session_opt = None; + + // Give serenity/songbird some time to register the disconnect + tokio::time::sleep(Duration::from_secs(1)).await; + } + } + + if let Some(session) = session_opt { + if let Err(why) = session.reactivate(ctx.author().id).await { + error!("Failed to reactivate session: {why}"); + + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Failed to reactivate session") + .description( + "An error occured whilst trying to reactivate the session.", + ) + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + } else if let Err(why) = manager + .create_session( + ctx.serenity_context(), + guild.id, + channel, + ctx.channel_id(), + ctx.author().id, + ) + .await + { + error!("Failed to create session: {why}"); + + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Failed to create session") + .description("An error occured whilst trying to create a session.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + ctx.send( + CreateReply::default().embed( + CreateEmbed::new() + .author( + CreateEmbedAuthor::new("Connected to voice channel") + .icon_url("https://spoticord.com/speaker.png"), + ) + .description(format!("Come listen along in <#{}>", channel)) + .footer(CreateEmbedFooter::new( + "You must manually select your device in Spotify", + )) + .color(Colors::Info), + ), + ) + .await?; + + Ok(()) +} + +async fn has_voice_permissions(ctx: Context<'_>, channel: ChannelId) -> Result { + let me: UserId = ctx.cache().current_user().id; + + let Ok(Channel::Guild(channel)) = channel.to_channel(ctx).await else { + return Ok(false); + }; + + let Ok(permissions) = channel.permissions_for_user(ctx, me) else { + return Ok(false); + }; + + Ok(permissions.view_channel() && permissions.connect() && permissions.speak()) +} + +async fn has_text_permissions(ctx: Context<'_>, channel: ChannelId) -> Result { + let me: UserId = ctx.cache().current_user().id; + + let Ok(Channel::Guild(channel)) = channel.to_channel(ctx).await else { + return Ok(false); + }; + + let Ok(permissions) = channel.permissions_for_user(ctx, me) else { + return Ok(false); + }; + + Ok(permissions.view_channel() && permissions.send_messages() && permissions.embed_links()) +} diff --git a/src/commands/music/lyrics.rs b/src/commands/music/lyrics.rs new file mode 100644 index 0000000..a2a5428 --- /dev/null +++ b/src/commands/music/lyrics.rs @@ -0,0 +1,40 @@ +use anyhow::Result; +use poise::CreateReply; +use serenity::all::CreateEmbed; +use spoticord_session::manager::SessionQuery; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +/// Show the lyrics of the current song that is being played +#[poise::command(slash_command, guild_only)] +pub async fn lyrics(ctx: Context<'_>) -> Result<()> { + let manager = ctx.data(); + let guild = ctx.guild().expect("poise lied to me").id; + + let Some(session) = manager.get_session(SessionQuery::Guild(guild)) else { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot get lyrics") + .description("I'm currently not playing any music in this server.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + }; + + let Context::Application(context) = ctx else { + panic!("Slash command is a prefix command?"); + }; + + session + .create_lyrics_embed(context.interaction.clone()) + .await?; + + Ok(()) +} diff --git a/src/commands/music/mod.rs b/src/commands/music/mod.rs new file mode 100644 index 0000000..13386da --- /dev/null +++ b/src/commands/music/mod.rs @@ -0,0 +1,11 @@ +mod disconnect; +mod join; +mod lyrics; +mod playing; +mod stop; + +pub use disconnect::*; +pub use join::*; +pub use lyrics::*; +pub use playing::*; +pub use stop::*; diff --git a/src/commands/music/playing.rs b/src/commands/music/playing.rs new file mode 100644 index 0000000..b6d46f4 --- /dev/null +++ b/src/commands/music/playing.rs @@ -0,0 +1,40 @@ +use anyhow::Result; +use poise::CreateReply; +use serenity::all::CreateEmbed; +use spoticord_session::manager::SessionQuery; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +/// Show details of the current song that is being played +#[poise::command(slash_command, guild_only)] +pub async fn playing(ctx: Context<'_>) -> Result<()> { + let manager = ctx.data(); + let guild = ctx.guild().expect("poise lied to me").id; + + let Some(session) = manager.get_session(SessionQuery::Guild(guild)) else { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot display song details") + .description("I'm currently not playing any music in this server.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + }; + + let Context::Application(context) = ctx else { + panic!("Slash command is a prefix command?"); + }; + + session + .create_playback_embed(context.interaction.clone()) + .await?; + + Ok(()) +} diff --git a/src/commands/music/stop.rs b/src/commands/music/stop.rs new file mode 100644 index 0000000..90e3a2b --- /dev/null +++ b/src/commands/music/stop.rs @@ -0,0 +1,59 @@ +use anyhow::Error; +use poise::CreateReply; +use serenity::all::CreateEmbed; +use spoticord_session::manager::SessionQuery; +use spoticord_utils::discord::Colors; + +use crate::bot::Context; + +#[poise::command(slash_command, guild_only)] +pub async fn stop(ctx: Context<'_>) -> Result<(), Error> { + let manager = ctx.data(); + let guild = ctx.guild().expect("poise lied to me").id; + + let Some(session) = manager.get_session(SessionQuery::Guild(guild)) else { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot stop playback") + .description("I'm currently not connected to any voice channel.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + }; + + if session.active().await? && session.owner().await? != ctx.author().id { + ctx.send( + CreateReply::default() + .embed( + CreateEmbed::new() + .title("Cannot stop playback") + .description("Only the host may stop playback.") + .color(Colors::Error), + ) + .ephemeral(true), + ) + .await?; + + return Ok(()); + } + + session.shutdown_player().await; + + ctx.send( + CreateReply::default().embed( + CreateEmbed::new() + .title("Stopped playback") + .description("I have stopped playing for now. To resume playback, please run the /join command again.") + .color(Colors::Info), + ), + ) + .await?; + + Ok(()) +} diff --git a/src/consts.rs b/src/consts.rs deleted file mode 100644 index d3326bf..0000000 --- a/src/consts.rs +++ /dev/null @@ -1,27 +0,0 @@ -use lazy_static::lazy_static; - -#[cfg(not(debug_assertions))] -pub const VERSION: &str = env!("CARGO_PKG_VERSION"); - -#[cfg(debug_assertions)] -pub const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "-dev"); - -pub const MOTD: &str = "some good 'ol music"; - -/// The time it takes for Spoticord to disconnect when no music is being played -pub const DISCONNECT_TIME: u64 = 5 * 60; - -lazy_static! { - pub static ref DISCORD_TOKEN: String = - std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN environment variable"); - pub static ref DATABASE_URL: String = - std::env::var("DATABASE_URL").expect("missing DATABASE_URL environment variable"); - pub static ref SPOTICORD_ACCOUNTS_URL: String = std::env::var("SPOTICORD_ACCOUNTS_URL") - .expect("missing SPOTICORD_ACCOUNTS_URL environment variable"); -} - -#[cfg(feature = "stats")] -lazy_static! { - pub static ref KV_URL: String = - std::env::var("KV_URL").expect("missing KV_URL environment variable"); -} diff --git a/src/database.rs b/src/database.rs deleted file mode 100644 index a433894..0000000 --- a/src/database.rs +++ /dev/null @@ -1,355 +0,0 @@ -use thiserror::Error; - -use log::trace; -use reqwest::{header::HeaderMap, Client, Error, Response, StatusCode}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use serde_json::{json, Value}; -use serenity::prelude::TypeMapKey; - -use crate::utils; - -#[derive(Debug, Error)] -pub enum DatabaseError { - #[error("An error has occured during an I/O operation: {0}")] - IOError(String), - - #[error("An error has occured during a parsing operation: {0}")] - ParseError(String), - - #[error("An invalid status code was returned from a request: {0}")] - InvalidStatusCode(StatusCode), - - #[error("An invalid input body was provided: {0}")] - InvalidInputBody(String), -} - -#[derive(Serialize, Deserialize)] -struct GetAccessTokenResponse { - id: String, - access_token: String, -} - -#[derive(Deserialize)] -pub struct User { - pub id: String, - pub device_name: String, - pub request: Option, - pub accounts: Option>, -} - -#[derive(Deserialize)] -pub struct Account { - pub user_id: String, - pub r#type: String, - pub access_token: String, - pub refresh_token: String, - pub expires: u64, -} - -#[derive(Deserialize)] -pub struct Request { - pub token: String, - pub user_id: String, - pub expires: u64, -} - -pub struct Database { - base_url: String, - default_headers: Option, -} - -// Request options -#[derive(Debug, Clone)] -struct RequestOptions { - pub method: Method, - pub path: String, - pub body: Option, - pub headers: Option, -} - -#[derive(Debug, Clone)] -#[allow(dead_code)] -enum Body { - Json(Value), - Text(String), -} - -#[derive(Debug, Clone)] -#[allow(dead_code)] -enum Method { - Get, - Post, - Put, - Delete, - Patch, -} - -impl Database { - pub fn new(base_url: impl Into, default_headers: Option) -> Self { - Self { - base_url: base_url.into(), - default_headers, - } - } - - async fn request(&self, options: RequestOptions) -> Result { - let builder = Client::builder(); - let mut headers: HeaderMap = HeaderMap::new(); - let mut url = self.base_url.clone(); - - url.push_str(&options.path); - - if let Some(default_headers) = &self.default_headers { - headers.extend(default_headers.clone()); - } - - if let Some(request_headers) = options.headers { - headers.extend(request_headers); - } - - trace!("Requesting {} with headers: {:?}", url, headers); - - let client = builder.default_headers(headers).build()?; - - let mut request = match options.method { - Method::Get => client.get(url), - Method::Post => client.post(url), - Method::Put => client.put(url), - Method::Delete => client.delete(url), - Method::Patch => client.patch(url), - }; - - request = if let Some(body) = options.body { - match body { - Body::Json(json) => request.json(&json), - Body::Text(text) => request.body(text), - } - } else { - request - }; - - let response = request.send().await?; - - Ok(response) - } - - async fn simple_get( - &self, - path: impl Into, - ) -> Result { - let response = match self - .request(RequestOptions { - method: Method::Get, - path: path.into(), - body: None, - headers: None, - }) - .await - { - Ok(response) => response, - Err(error) => return Err(DatabaseError::IOError(error.to_string())), - }; - - match response.status() { - StatusCode::OK | StatusCode::CREATED | StatusCode::ACCEPTED | StatusCode::NO_CONTENT => {} - status => return Err(DatabaseError::InvalidStatusCode(status)), - }; - - let body = match response.json::().await { - Ok(body) => body, - Err(error) => return Err(DatabaseError::ParseError(error.to_string())), - }; - - Ok(body) - } - - async fn json_post( - &self, - value: impl Serialize, - path: impl Into, - ) -> Result { - let body = json!(value); - - let response = match self - .request(RequestOptions { - method: Method::Post, - path: path.into(), - body: Some(Body::Json(body)), - headers: None, - }) - .await - { - Ok(response) => response, - Err(error) => return Err(DatabaseError::IOError(error.to_string())), - }; - - match response.status() { - StatusCode::OK | StatusCode::CREATED | StatusCode::ACCEPTED | StatusCode::NO_CONTENT => {} - status => return Err(DatabaseError::InvalidStatusCode(status)), - }; - - let body = match response.json::().await { - Ok(body) => body, - Err(error) => return Err(DatabaseError::ParseError(error.to_string())), - }; - - Ok(body) - } -} - -impl Database { - // Get Spoticord user - pub async fn get_user(&self, user_id: impl Into) -> Result { - let path = format!("/user/{}", user_id.into()); - - self.simple_get(path).await - } - - // Get the Spotify access token for a user - pub async fn get_access_token( - &self, - user_id: impl Into + Send, - ) -> Result { - let body: GetAccessTokenResponse = self - .simple_get(format!("/user/{}/spotify/access_token", user_id.into())) - .await?; - - Ok(body.access_token) - } - - // Get the Spotify account for a user - pub async fn get_user_account( - &self, - user_id: impl Into + Send, - ) -> Result { - let body: Account = self - .simple_get(format!("/account/{}/spotify", user_id.into())) - .await?; - - Ok(body) - } - - // Get the Request for a user - pub async fn get_user_request( - &self, - user_id: impl Into + Send, - ) -> Result { - let body: Request = self - .simple_get(format!("/request/by-user/{}", user_id.into())) - .await?; - - Ok(body) - } - - // Create a Spoticord user - pub async fn create_user(&self, user_id: impl Into) -> Result { - let body = json!({ - "id": user_id.into(), - }); - - let user: User = self.json_post(body, "/user/new").await?; - - Ok(user) - } - - // Create the link Request for a user - pub async fn create_user_request( - &self, - user_id: impl Into + Send, - ) -> Result { - let body = json!({ - "user_id": user_id.into(), - "expires": utils::get_time() + (1000 * 60 * 60) - }); - - let response = match self - .request(RequestOptions { - method: Method::Post, - path: "/request".into(), - body: Some(Body::Json(body)), - headers: None, - }) - .await - { - Ok(response) => response, - Err(err) => return Err(DatabaseError::IOError(err.to_string())), - }; - - match response.status() { - StatusCode::OK | StatusCode::CREATED | StatusCode::ACCEPTED | StatusCode::NO_CONTENT => {} - status => return Err(DatabaseError::InvalidStatusCode(status)), - }; - - let body = match response.json::().await { - Ok(body) => body, - Err(error) => return Err(DatabaseError::ParseError(error.to_string())), - }; - - Ok(body) - } - - pub async fn delete_user_account( - &self, - user_id: impl Into + Send, - ) -> Result<(), DatabaseError> { - let response = match self - .request(RequestOptions { - method: Method::Delete, - path: format!("/account/{}/spotify", user_id.into()), - body: None, - headers: None, - }) - .await - { - Ok(response) => response, - Err(err) => return Err(DatabaseError::IOError(err.to_string())), - }; - - match response.status() { - StatusCode::OK | StatusCode::CREATED | StatusCode::ACCEPTED | StatusCode::NO_CONTENT => {} - status => return Err(DatabaseError::InvalidStatusCode(status)), - }; - - Ok(()) - } - - pub async fn update_user_device_name( - &self, - user_id: impl Into, - name: impl Into, - ) -> Result<(), DatabaseError> { - let device_name: String = name.into(); - - if device_name.len() > 16 || device_name.is_empty() { - return Err(DatabaseError::InvalidInputBody( - "Invalid device name length".into(), - )); - } - - let body = json!({ "device_name": device_name }); - - let response = match self - .request(RequestOptions { - method: Method::Patch, - path: format!("/user/{}", user_id.into()), - body: Some(Body::Json(body)), - headers: None, - }) - .await - { - Ok(response) => response, - Err(err) => return Err(DatabaseError::IOError(err.to_string())), - }; - - match response.status() { - StatusCode::OK | StatusCode::CREATED | StatusCode::ACCEPTED | StatusCode::NO_CONTENT => { - Ok(()) - } - status => Err(DatabaseError::InvalidStatusCode(status)), - } - } -} - -impl TypeMapKey for Database { - type Value = Database; -} diff --git a/src/librespot_ext/discovery.rs b/src/librespot_ext/discovery.rs deleted file mode 100644 index a048cd0..0000000 --- a/src/librespot_ext/discovery.rs +++ /dev/null @@ -1,18 +0,0 @@ -use librespot::discovery::Credentials; -use librespot::protocol::authentication::AuthenticationType; - -pub trait CredentialsExt { - fn with_token(username: impl Into, token: impl Into) -> Credentials; -} - -impl CredentialsExt for Credentials { - // Enable the use of a token to connect to Spotify - // Wouldn't want to ask users for their password would we? - fn with_token(username: impl Into, token: impl Into) -> Credentials { - Credentials { - username: username.into(), - auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN, - auth_data: token.into().into_bytes(), - } - } -} diff --git a/src/librespot_ext/mod.rs b/src/librespot_ext/mod.rs deleted file mode 100644 index 018c2b5..0000000 --- a/src/librespot_ext/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -// Librespot extensions -// ============================= -// Librespot is missing some key features/functionality for Spoticord to work properly. -// This module contains the extensions to librespot that are required for Spoticord to work. - -pub mod discovery; diff --git a/src/main.rs b/src/main.rs index f8b6f01..7a761b7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,152 +1,64 @@ -use dotenv::dotenv; - -#[cfg(feature = "stats")] -use crate::consts::KV_URL; - -use crate::{ - bot::commands::CommandManager, - consts::{DATABASE_URL, DISCORD_TOKEN, MOTD}, - database::Database, - session::manager::SessionManager, -}; -use log::*; -use serenity::{framework::StandardFramework, prelude::GatewayIntents, Client}; -use songbird::SerenityInit; -use std::{any::Any, process::exit}; - -#[cfg(unix)] -use tokio::signal::unix::SignalKind; - -mod audio; mod bot; -mod consts; -mod database; -mod librespot_ext; -mod player; -mod session; -mod utils; +mod commands; +// mod session; +// mod utils; -#[cfg(feature = "stats")] -mod stats; - -#[cfg(feature = "stats")] -use crate::stats::StatsManager; +use log::{error, info}; +use poise::Framework; +use serenity::all::ClientBuilder; +use songbird::SerenityInit; +use spoticord_database::Database; #[tokio::main] async fn main() { - if std::env::var("RUST_LOG").is_err() { - #[cfg(debug_assertions)] + // Setup logging + if std::env::var("RUST_LOG").is_err() { + #[cfg(debug_assertions)] + std::env::set_var("RUST_LOG", "spoticord"); + + #[cfg(not(debug_assertions))] + std::env::set_var("RUST_LOG", "spoticord=info"); + } + + env_logger::init(); + + info!("Today is a good day!"); + info!(" - Spoticord"); + + dotenvy::dotenv().ok(); + + // Set up database + let database = match Database::connect().await { + Ok(db) => db, + Err(why) => { + error!("Failed to connect to database and perform migrations: {why}"); + return; + } + }; + + // Set up bot + let framework = Framework::builder() + .setup(|ctx, ready, framework| Box::pin(bot::setup(ctx, ready, framework, database))) + .options(bot::framework_opts()) + .build(); + + let mut client = match ClientBuilder::new( + spoticord_config::discord_token(), + spoticord_config::discord_intents(), + ) + .framework(framework) + .register_songbird_from_config(songbird::Config::default().use_softclip(false)) + .await { - std::env::set_var("RUST_LOG", "spoticord"); - } - - #[cfg(not(debug_assertions))] - { - std::env::set_var("RUST_LOG", "spoticord=info"); - } - } - - env_logger::init(); - - info!("It's a good day"); - info!(" - Spoticord, {}", MOTD); - - let result = dotenv(); - - if let Ok(path) = result { - debug!( - "Loaded environment file: {}", - path.to_str().expect("to get the string") - ); - } else { - warn!("No .env file found, expecting all necessary environment variables"); - } - - #[cfg(feature = "stats")] - let stats_manager = StatsManager::new(KV_URL.as_str()).expect("Failed to connect to redis"); - - let session_manager = SessionManager::new(); - - // Create client - let mut client = Client::builder( - DISCORD_TOKEN.as_str(), - GatewayIntents::GUILDS | GatewayIntents::GUILD_VOICE_STATES, - ) - .event_handler(crate::bot::events::Handler) - .framework(StandardFramework::new()) - .register_songbird() - .await - .expect("to create a client"); - - { - let mut data = client.data.write().await; - - data.insert::(Database::new(DATABASE_URL.as_str(), None)); - data.insert::(CommandManager::new()); - data.insert::(session_manager.clone()); - } - - let shard_manager = client.shard_manager.clone(); - - #[cfg(unix)] - let mut term: Option> = Some(Box::new( - tokio::signal::unix::signal(SignalKind::terminate()) - .expect("to be able to create the signal stream"), - )); - - #[cfg(not(unix))] - let term: Option> = None; - - // Background tasks - tokio::spawn(async move { - loop { - tokio::select! { - _ = tokio::time::sleep(std::time::Duration::from_secs(60)) => { - #[cfg(feature = "stats")] - { - let active_count = session_manager.get_active_session_count().await; - - if let Err(why) = stats_manager.set_active_count(active_count) { - error!("Failed to update active count: {why}"); - } - } + Ok(client) => client, + Err(why) => { + error!("Fatal error when building Serenity client: {why}"); + return; } + }; - _ = tokio::signal::ctrl_c() => { - info!("Received interrupt signal, shutting down..."); - - session_manager.shutdown().await; - shard_manager.lock().await.shutdown_all().await; - - break; - } - - _ = async { - #[cfg(unix)] - match term { - Some(ref mut term) => { - let term = term.downcast_mut::().expect("to be able to downcast"); - - term.recv().await - } - - _ => None - } - }, if term.is_some() => { - info!("Received terminate signal, shutting down..."); - - session_manager.shutdown().await; - shard_manager.lock().await.shutdown_all().await; - - break; - } - } + if let Err(why) = client.start_autosharded().await { + error!("Fatal error occured during bot operations: {why}"); + error!("Bot will now shut down!"); } - }); - - // Start the bot - if let Err(why) = client.start_autosharded().await { - error!("FATAL Error in bot: {:?}", why); - exit(1); - } } diff --git a/src/player/mod.rs b/src/player/mod.rs deleted file mode 100644 index ef03233..0000000 --- a/src/player/mod.rs +++ /dev/null @@ -1,406 +0,0 @@ -use std::{io::Write, sync::Arc}; - -use anyhow::{anyhow, Result}; -use librespot::{ - connect::spirc::Spirc, - core::{ - config::{ConnectConfig, SessionConfig}, - session::Session, - spotify_id::{SpotifyAudioType, SpotifyId}, - }, - discovery::Credentials, - playback::{ - config::{Bitrate, PlayerConfig, VolumeCtrl}, - mixer::{self, MixerConfig}, - player::{Player as SpotifyPlayer, PlayerEvent as SpotifyEvent}, - }, - protocol::metadata::{Episode, Track}, -}; -use log::error; -use protobuf::Message; -use songbird::tracks::TrackHandle; -use tokio::sync::{ - broadcast::{Receiver, Sender}, - mpsc::UnboundedReceiver, - Mutex, -}; - -use crate::{ - audio::{stream::Stream, SinkEvent, StreamSink}, - librespot_ext::discovery::CredentialsExt, - session::pbi::{CurrentTrack, PlaybackInfo}, - utils, -}; - -enum Event { - Player(SpotifyEvent), - Sink(SinkEvent), - Command(PlayerCommand), -} - -#[derive(Clone)] -enum PlayerCommand { - Next, - Previous, - Pause, - Play, - Shutdown, -} - -#[derive(Clone, Debug)] -pub enum PlayerEvent { - Pause, - Play, - Stopped, -} - -#[derive(Clone)] -pub struct Player { - tx: Sender, - - pbi: Arc>>, -} - -impl Player { - pub async fn create( - stream: Stream, - token: &str, - device_name: &str, - track: TrackHandle, - ) -> Result<(Self, Receiver)> { - let username = utils::spotify::get_username(token).await?; - - let player_config = PlayerConfig { - bitrate: Bitrate::Bitrate96, - ..Default::default() - }; - - let credentials = Credentials::with_token(username, token); - - let (session, _) = Session::connect( - SessionConfig { - ap_port: Some(9999), // Force the use of ap.spotify.com, which has the lowest latency - ..Default::default() - }, - credentials, - None, - false, - ) - .await?; - - let mixer = (mixer::find(Some("softvol")).expect("to exist"))(MixerConfig { - volume_ctrl: VolumeCtrl::Linear, - ..Default::default() - }); - - let (tx, rx_sink) = tokio::sync::mpsc::unbounded_channel(); - let (player, rx_player) = - SpotifyPlayer::new(player_config, session.clone(), mixer.get_soft_volume(), { - let stream = stream.clone(); - move || Box::new(StreamSink::new(stream, tx)) - }); - - let (spirc, spirc_task) = Spirc::new( - ConnectConfig { - name: device_name.into(), - // 50% - initial_volume: Some(65535 / 2), - // Default Spotify behaviour - autoplay: true, - ..Default::default() - }, - session.clone(), - player, - mixer, - ); - - let (tx, rx) = tokio::sync::broadcast::channel(10); - let (tx_ev, rx_ev) = tokio::sync::broadcast::channel(10); - let pbi = Arc::new(Mutex::new(None)); - - let player_task = PlayerTask { - pbi: pbi.clone(), - session: session.clone(), - rx_player, - rx_sink, - rx, - tx: tx_ev, - spirc, - track, - stream, - }; - - tokio::spawn(spirc_task); - tokio::spawn(player_task.run()); - - Ok((Self { pbi, tx }, rx_ev)) - } - - pub fn next(&self) { - self.tx.send(PlayerCommand::Next).ok(); - } - - pub fn prev(&self) { - self.tx.send(PlayerCommand::Previous).ok(); - } - - pub fn pause(&self) { - self.tx.send(PlayerCommand::Pause).ok(); - } - - pub fn play(&self) { - self.tx.send(PlayerCommand::Play).ok(); - } - - pub fn shutdown(&self) { - self.tx.send(PlayerCommand::Shutdown).ok(); - } - - pub async fn pbi(&self) -> Option { - self.pbi.lock().await.as_ref().cloned() - } -} - -struct PlayerTask { - stream: Stream, - session: Session, - spirc: Spirc, - track: TrackHandle, - - rx_player: UnboundedReceiver, - rx_sink: UnboundedReceiver, - rx: Receiver, - tx: Sender, - - pbi: Arc>>, -} - -impl PlayerTask { - pub async fn run(mut self) { - let check_result = |result| { - if let Err(why) = result { - error!("Failed to issue track command: {:?}", why); - } - }; - - loop { - match self.next().await { - // Spotify player events - Some(Event::Player(event)) => match event { - SpotifyEvent::Playing { - play_request_id: _, - track_id, - position_ms, - duration_ms, - } => { - self - .update_pbi(track_id, position_ms, duration_ms, true) - .await; - - self.tx.send(PlayerEvent::Play).ok(); - } - - SpotifyEvent::Paused { - play_request_id: _, - track_id, - position_ms, - duration_ms, - } => { - self - .update_pbi(track_id, position_ms, duration_ms, false) - .await; - - self.tx.send(PlayerEvent::Pause).ok(); - } - - SpotifyEvent::Changed { - old_track_id: _, - new_track_id, - } => { - if let Ok(current) = self.resolve_audio_info(new_track_id).await { - let mut pbi = self.pbi.lock().await; - - if let Some(pbi) = pbi.as_mut() { - pbi.update_track(new_track_id, current); - } - } - } - - SpotifyEvent::Stopped { - play_request_id: _, - track_id: _, - } => { - check_result(self.track.pause()); - - self.tx.send(PlayerEvent::Pause).ok(); - } - - _ => {} - }, - - // Audio sink events - Some(Event::Sink(event)) => match event { - SinkEvent::Start => { - check_result(self.track.play()); - } - - SinkEvent::Stop => { - // EXPERIMENT: It may be beneficial to *NOT* pause songbird here - // We already have a fallback if no audio is present in the buffer (write all zeroes aka silence) - // So commenting this out may help prevent a substantial portion of jitter - // This comes at a cost of more bandwidth, though opus should compress it down to almost nothing - - // check_result(track.pause()); - - self.tx.send(PlayerEvent::Pause).ok(); - } - }, - - // The `Player` has instructed us to do something - Some(Event::Command(command)) => match command { - PlayerCommand::Next => self.spirc.next(), - PlayerCommand::Previous => self.spirc.prev(), - PlayerCommand::Pause => self.spirc.pause(), - PlayerCommand::Play => self.spirc.play(), - PlayerCommand::Shutdown => break, - }, - - None => { - // One of the channels died - log::debug!("Channel died"); - break; - } - } - } - - self.tx.send(PlayerEvent::Stopped).ok(); - } - - async fn next(&mut self) -> Option { - tokio::select! { - event = self.rx_player.recv() => { - event.map(Event::Player) - } - - event = self.rx_sink.recv() => { - event.map(Event::Sink) - } - - command = self.rx.recv() => { - command.ok().map(Event::Command) - } - } - } - - /// Update current playback info, or return early if not necessary - async fn update_pbi( - &self, - spotify_id: SpotifyId, - position_ms: u32, - duration_ms: u32, - playing: bool, - ) { - let mut pbi = self.pbi.lock().await; - - if let Some(pbi) = pbi.as_mut() { - pbi.update_pos_dur(position_ms, duration_ms, playing); - } - - if !pbi - .as_ref() - .map(|pbi| pbi.spotify_id == spotify_id) - .unwrap_or(true) - { - return; - } - - if let Ok(current) = self.resolve_audio_info(spotify_id).await { - match pbi.as_mut() { - Some(pbi) => { - pbi.update_track(spotify_id, current); - pbi.update_pos_dur(position_ms, duration_ms, playing); - } - None => { - *pbi = Some(PlaybackInfo::new( - duration_ms, - position_ms, - playing, - current, - spotify_id, - )); - } - } - } else { - log::error!("Failed to resolve audio info"); - } - } - - /// Retrieve the metadata for a `SpotifyId` - async fn resolve_audio_info(&self, spotify_id: SpotifyId) -> Result { - match spotify_id.audio_type { - SpotifyAudioType::Track => self.resolve_track_info(spotify_id).await, - SpotifyAudioType::Podcast => self.resolve_episode_info(spotify_id).await, - SpotifyAudioType::NonPlayable => Err(anyhow!("Cannot resolve non-playable audio type")), - } - } - - /// Retrieve the metadata for a Spotify Track - async fn resolve_track_info(&self, spotify_id: SpotifyId) -> Result { - let result = self - .session - .mercury() - .get(format!("hm://metadata/3/track/{}", spotify_id.to_base16()?)) - .await - .map_err(|_| anyhow!("Mercury metadata request failed"))?; - - if result.status_code != 200 { - return Err(anyhow!("Mercury metadata request invalid status code")); - } - - let message = match result.payload.get(0) { - Some(v) => v, - None => return Err(anyhow!("Mercury metadata request invalid payload")), - }; - - let proto_track = Track::parse_from_bytes(message)?; - - Ok(CurrentTrack::Track(proto_track)) - } - - /// Retrieve the metadata for a Spotify Podcast - async fn resolve_episode_info(&self, spotify_id: SpotifyId) -> Result { - let result = self - .session - .mercury() - .get(format!( - "hm://metadata/3/episode/{}", - spotify_id.to_base16()? - )) - .await - .map_err(|_| anyhow!("Mercury metadata request failed"))?; - - if result.status_code != 200 { - return Err(anyhow!("Mercury metadata request invalid status code")); - } - - let message = match result.payload.get(0) { - Some(v) => v, - None => return Err(anyhow!("Mercury metadata request invalid payload")), - }; - - let proto_episode = Episode::parse_from_bytes(message)?; - - Ok(CurrentTrack::Episode(proto_episode)) - } -} - -impl Drop for PlayerTask { - fn drop(&mut self) { - log::trace!("drop PlayerTask"); - - self.track.stop().ok(); - self.spirc.shutdown(); - self.session.shutdown(); - self.stream.flush().ok(); - } -} diff --git a/src/session/manager.rs b/src/session/manager.rs deleted file mode 100644 index d639b2d..0000000 --- a/src/session/manager.rs +++ /dev/null @@ -1,200 +0,0 @@ -use std::{collections::HashMap, sync::Arc}; - -use serenity::{ - model::prelude::{ChannelId, GuildId, UserId}, - prelude::{Context, TypeMapKey}, -}; -use songbird::error::JoinError; -use thiserror::Error; - -use super::SpoticordSession; - -#[derive(Debug, Error)] -pub enum SessionCreateError { - #[error("This session has no owner assigned")] - NoOwner, - - #[error("The user has not linked their Spotify account")] - NoSpotify, - - #[error("The application no longer has access to the user's Spotify account")] - SpotifyExpired, - - #[error("An error has occured while communicating with the database")] - DatabaseError, - - #[error("Failed to join voice channel")] - JoinError(JoinError), - - #[error("Failed to start the player")] - PlayerStartError, -} - -#[derive(Clone)] -pub struct SessionManager(Arc>); - -impl TypeMapKey for SessionManager { - type Value = SessionManager; -} - -pub struct InnerSessionManager { - sessions: HashMap, - owner_map: HashMap, -} - -impl InnerSessionManager { - pub fn new() -> Self { - Self { - sessions: HashMap::new(), - owner_map: HashMap::new(), - } - } - - /// Creates a new session for the given user in the given guild. - pub async fn create_session( - &mut self, - session: SpoticordSession, - guild_id: GuildId, - owner_id: UserId, - ) { - self.sessions.insert(guild_id, session); - self.owner_map.insert(owner_id, guild_id); - } - - /// Remove a session - pub async fn remove_session(&mut self, guild_id: GuildId, owner: Option) { - // Remove the owner from the owner map (if it exists) - if let Some(owner) = owner { - self.owner_map.remove(&owner); - } - - self.sessions.remove(&guild_id); - } - - /// Remove owner from owner map. - /// Used whenever a user stops playing music without leaving the bot. - pub fn remove_owner(&mut self, owner_id: UserId) { - self.owner_map.remove(&owner_id); - } - - /// Set the owner of a session - /// Used when a user joins a session that is already active - pub fn set_owner(&mut self, owner_id: UserId, guild_id: GuildId) { - self.owner_map.insert(owner_id, guild_id); - } - - /// Get a session by its guild ID - pub fn get_session(&self, guild_id: GuildId) -> Option { - self.sessions.get(&guild_id).cloned() - } - - /// Find a Spoticord session by their current owner's ID - pub fn find(&self, owner_id: UserId) -> Option { - let guild_id = self.owner_map.get(&owner_id)?; - - self.sessions.get(guild_id).cloned() - } - - /// Get the amount of sessions - pub fn get_session_count(&self) -> usize { - self.sessions.len() - } - - /// Get the amount of sessions with an owner - pub async fn get_active_session_count(&self) -> usize { - let mut count: usize = 0; - - for session in self.sessions.values() { - let session = session.0.read().await; - - if session.owner.is_some() { - count += 1; - } - } - - count - } - - pub fn sessions(&self) -> Vec { - self.sessions.values().cloned().collect() - } -} - -impl SessionManager { - pub fn new() -> Self { - Self(Arc::new(tokio::sync::RwLock::new( - InnerSessionManager::new(), - ))) - } - - /// Creates a new session for the given user in the given guild. - pub async fn create_session( - &self, - ctx: &Context, - guild_id: GuildId, - channel_id: ChannelId, - text_channel_id: ChannelId, - owner_id: UserId, - ) -> Result<(), SessionCreateError> { - // Create session first to make sure locks are kept for as little time as possible - let session = - SpoticordSession::new(ctx, guild_id, channel_id, text_channel_id, owner_id).await?; - - self - .0 - .write() - .await - .create_session(session, guild_id, owner_id) - .await; - - Ok(()) - } - - /// Remove a session - pub async fn remove_session(&self, guild_id: GuildId, owner: Option) { - self.0.write().await.remove_session(guild_id, owner).await; - } - - /// Remove owner from owner map. - /// Used whenever a user stops playing music without leaving the bot. - pub async fn remove_owner(&self, owner_id: UserId) { - self.0.write().await.remove_owner(owner_id); - } - - /// Set the owner of a session - /// Used when a user joins a session that is already active - pub async fn set_owner(&self, owner_id: UserId, guild_id: GuildId) { - self.0.write().await.set_owner(owner_id, guild_id); - } - - /// Get a session by its guild ID - pub async fn get_session(&self, guild_id: GuildId) -> Option { - self.0.read().await.get_session(guild_id) - } - - /// Find a Spoticord session by their current owner's ID - pub async fn find(&self, owner_id: UserId) -> Option { - self.0.read().await.find(owner_id) - } - - /// Get the amount of sessions - #[allow(dead_code)] - pub async fn get_session_count(&self) -> usize { - self.0.read().await.get_session_count() - } - - /// Get the amount of sessions with an owner - #[allow(dead_code)] - pub async fn get_active_session_count(&self) -> usize { - self.0.read().await.get_active_session_count().await - } - - /// Tell all sessions to instantly shut down - pub async fn shutdown(&self) { - let sessions = self.0.read().await.sessions(); - - for session in sessions { - session.disconnect().await; - } - } -} diff --git a/src/session/mod.rs b/src/session/mod.rs deleted file mode 100644 index a0f0ca5..0000000 --- a/src/session/mod.rs +++ /dev/null @@ -1,569 +0,0 @@ -pub mod manager; -pub mod pbi; - -use self::{ - manager::{SessionCreateError, SessionManager}, - pbi::PlaybackInfo, -}; -use crate::{ - audio::stream::Stream, - consts::DISCONNECT_TIME, - database::{Database, DatabaseError}, - player::{Player, PlayerEvent}, - utils::embed::Status, -}; -use log::*; -use reqwest::StatusCode; -use serenity::{ - async_trait, - http::Http, - model::prelude::{ChannelId, GuildId, UserId}, - prelude::{Context, RwLock}, -}; -use songbird::{ - create_player, - input::{Codec, Container, Input, Reader}, - tracks::TrackHandle, - Call, Event, EventContext, EventHandler, -}; -use std::{ - ops::{Deref, DerefMut}, - sync::Arc, - time::Duration, -}; -use tokio::sync::{Mutex, RwLockReadGuard, RwLockWriteGuard}; - -#[derive(Clone)] -pub struct SpoticordSession(Arc>); - -impl Drop for SpoticordSession { - fn drop(&mut self) { - log::trace!("drop SpoticordSession"); - } -} - -struct InnerSpoticordSession { - owner: Option, - guild_id: GuildId, - channel_id: ChannelId, - text_channel_id: ChannelId, - - http: Arc, - - session_manager: SessionManager, - - call: Arc>, - track: Option, - player: Option, - - disconnect_handle: Option>, - - /// Whether the session has been disconnected - /// If this is true then this instance should no longer be used and dropped - disconnected: bool, -} - -impl SpoticordSession { - pub async fn new( - ctx: &Context, - guild_id: GuildId, - channel_id: ChannelId, - text_channel_id: ChannelId, - owner_id: UserId, - ) -> Result { - // Get the Spotify token of the owner - let data = ctx.data.read().await; - let session_manager = data - .get::() - .expect("to contain a value") - .clone(); - - // Join the voice channel - let songbird = songbird::get(ctx).await.expect("to be present").clone(); - - let (call, result) = songbird.join(guild_id, channel_id).await; - - if let Err(why) = result { - error!("Error joining voice channel: {:?}", why); - return Err(SessionCreateError::JoinError(why)); - } - - let inner = InnerSpoticordSession { - owner: Some(owner_id), - guild_id, - channel_id, - text_channel_id, - http: ctx.http.clone(), - session_manager: session_manager.clone(), - call: call.clone(), - track: None, - player: None, - disconnect_handle: None, - disconnected: false, - }; - - let mut instance = Self(Arc::new(RwLock::new(inner))); - if let Err(why) = instance.create_player(ctx).await { - songbird.remove(guild_id).await.ok(); - - return Err(why); - } - - let mut call = call.lock().await; - - // Set up events - call.add_global_event( - songbird::Event::Core(songbird::CoreEvent::DriverDisconnect), - instance.clone(), - ); - - call.add_global_event( - songbird::Event::Core(songbird::CoreEvent::ClientDisconnect), - instance.clone(), - ); - - Ok(instance) - } - - pub async fn update_owner( - &mut self, - ctx: &Context, - owner_id: UserId, - ) -> Result<(), SessionCreateError> { - // Get the Spotify token of the owner - let data = ctx.data.read().await; - let session_manager = data - .get::() - .expect("to contain a value") - .clone(); - - { - let mut inner = self.acquire_write().await; - inner.owner = Some(owner_id); - } - - { - let guild_id = self.acquire_read().await.guild_id; - session_manager.set_owner(owner_id, guild_id).await; - } - - // Create the player - self.create_player(ctx).await?; - - Ok(()) - } - - /// Advance to the next track - pub async fn next(&mut self) { - if let Some(ref player) = self.acquire_read().await.player { - player.next(); - } - } - - /// Rewind to the previous track - pub async fn previous(&mut self) { - if let Some(ref player) = self.acquire_read().await.player { - player.prev(); - } - } - - /// Pause the current track - pub async fn pause(&mut self) { - if let Some(ref player) = self.acquire_read().await.player { - player.pause(); - } - } - - /// Resume the current track - pub async fn resume(&mut self) { - if let Some(ref player) = self.acquire_read().await.player { - player.play(); - } - } - - async fn create_player(&mut self, ctx: &Context) -> Result<(), SessionCreateError> { - let owner_id = match self.owner().await { - Some(owner_id) => owner_id, - None => return Err(SessionCreateError::NoOwner), - }; - - let data = ctx.data.read().await; - let database = data.get::().expect("to contain a value"); - - let token = match database.get_access_token(owner_id.to_string()).await { - Ok(token) => token, - Err(why) => { - return match why { - DatabaseError::InvalidStatusCode(StatusCode::NOT_FOUND) => { - Err(SessionCreateError::NoSpotify) - } - DatabaseError::InvalidStatusCode(StatusCode::BAD_REQUEST) => { - Err(SessionCreateError::SpotifyExpired) - } - _ => Err(SessionCreateError::DatabaseError), - }; - } - }; - - let user = match database.get_user(owner_id.to_string()).await { - Ok(user) => user, - Err(why) => { - error!("Failed to get user: {:?}", why); - return Err(SessionCreateError::DatabaseError); - } - }; - - // Create stream - let stream = Stream::new(); - - // Create track (paused, fixes audio glitches) - let (mut track, track_handle) = create_player(Input::new( - true, - Reader::Extension(Box::new(stream.clone())), - Codec::FloatPcm, - Container::Raw, - None, - )); - track.pause(); - - let call = self.call().await; - let mut call = call.lock().await; - - // Set call audio to track - call.play_only(track); - - let (player, mut rx) = - match Player::create(stream, &token, &user.device_name, track_handle.clone()).await { - Ok(v) => v, - Err(why) => { - error!("Failed to start the player: {:?}", why); - - return Err(SessionCreateError::PlayerStartError); - } - }; - - tokio::spawn({ - let session = self.clone(); - - async move { - loop { - match rx.recv().await { - Ok(event) => match event { - PlayerEvent::Pause => session.start_disconnect_timer().await, - PlayerEvent::Play => session.stop_disconnect_timer().await, - PlayerEvent::Stopped => { - session.player_stopped().await; - break; - } - }, - Err(why) => { - error!("Communication with player abruptly ended: {why}"); - session.player_stopped().await; - - break; - } - } - } - } - }); - - // Start DC timer by default, as automatic device switching is now gone - self.start_disconnect_timer().await; - - let mut inner = self.acquire_write().await; - inner.track = Some(track_handle); - inner.player = Some(player); - - Ok(()) - } - - /// Called when the player must stop, but not leave the call - async fn player_stopped(&self) { - let mut inner = self.acquire_write().await; - - if let Some(track) = inner.track.take() { - if let Err(why) = track.stop() { - error!("Failed to stop track: {:?}", why); - } - } - - // Clear owner - if let Some(owner_id) = inner.owner.take() { - inner.session_manager.remove_owner(owner_id).await; - } - - // Disconnect from Spotify - if let Some(player) = inner.player.take() { - player.shutdown(); - } - - // Unlock to prevent deadlock in start_disconnect_timer - drop(inner); - - // Disconnect automatically after some time - self.start_disconnect_timer().await; - } - - // Disconnect from voice channel and remove session from manager - pub async fn disconnect(&self) { - info!( - "[{}] Disconnecting from voice channel {}", - self.guild_id().await, - self.channel_id().await - ); - - // We must run disconnect_no_abort within a read lock - // This is because `SessionManager::remove_session` will acquire a - // read lock to read the current owner. - // This would deadlock if we have an active write lock - { - let mut inner = self.acquire_write().await; - inner.disconnect_no_abort().await; - } - - self.stop_disconnect_timer().await; - } - - /// Start the disconnect timer, which will disconnect the bot from the voice channel after a - /// certain amount of time - async fn start_disconnect_timer(&self) { - self.stop_disconnect_timer().await; - - let mut inner = self.acquire_write().await; - - // Check if we are already disconnected - if inner.disconnected { - return; - } - - inner.disconnect_handle = Some(tokio::spawn({ - let session = self.clone(); - - async move { - let mut timer = tokio::time::interval(Duration::from_secs(DISCONNECT_TIME)); - - // Ignore first (immediate) tick - timer.tick().await; - timer.tick().await; - - trace!("Ring ring, time to check :)"); - - // Make sure this task has not been aborted, if it has this will automatically stop execution. - tokio::task::yield_now().await; - - let is_playing = session - .playback_info() - .await - .map(|pbi| pbi.is_playing) - .unwrap_or(false); - - trace!("is_playing = {is_playing}"); - - if !is_playing { - info!("Player is not playing, disconnecting"); - session - .disconnect_with_message( - "The player has been inactive for too long, and has been disconnected.", - ) - .await; - } - } - })); - } - - /// Stop the disconnect timer (if one is running) - async fn stop_disconnect_timer(&self) { - let mut inner = self.acquire_write().await; - if let Some(handle) = inner.disconnect_handle.take() { - handle.abort(); - } - } - - /// Disconnect from the VC and send a message to the text channel - pub async fn disconnect_with_message(&self, content: &str) { - { - let mut inner = self.acquire_write().await; - - // Firstly we disconnect - inner.disconnect_no_abort().await; - - // Then we send the message - if let Err(why) = inner - .text_channel_id - .send_message(&inner.http, |message| { - message.embed(|embed| { - embed.title("Disconnected from voice channel"); - embed.description(content); - embed.color(Status::Warning as u64); - - embed - }) - }) - .await - { - error!("Failed to send disconnect message: {:?}", why); - } - } - - // Finally we stop and remove the disconnect timer - self.stop_disconnect_timer().await; - } - - /* Inner getters */ - - /// Get the owner - pub async fn owner(&self) -> Option { - self.acquire_read().await.owner - } - - /// Get the session manager - pub async fn session_manager(&self) -> SessionManager { - self.acquire_read().await.session_manager.clone() - } - - /// Get the guild id - pub async fn guild_id(&self) -> GuildId { - self.acquire_read().await.guild_id - } - - /// Get the channel id - pub async fn channel_id(&self) -> ChannelId { - self.acquire_read().await.channel_id - } - - /// Get the channel id - #[allow(dead_code)] - pub async fn text_channel_id(&self) -> ChannelId { - self.acquire_read().await.text_channel_id - } - - /// Get the playback info - pub async fn playback_info(&self) -> Option { - let handle = self.acquire_read().await; - let player = handle.player.as_ref()?; - - player.pbi().await - } - - pub async fn call(&self) -> Arc> { - self.acquire_read().await.call.clone() - } - - #[allow(dead_code)] - pub async fn http(&self) -> Arc { - self.acquire_read().await.http.clone() - } - - async fn acquire_read(&self) -> ReadLock { - ReadLock(self.0.read().await) - } - - async fn acquire_write(&self) -> WriteLock { - WriteLock(self.0.write().await) - } -} - -struct ReadLock<'a>(RwLockReadGuard<'a, InnerSpoticordSession>); - -impl<'a> Deref for ReadLock<'a> { - type Target = RwLockReadGuard<'a, InnerSpoticordSession>; - - #[inline] - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl<'a> DerefMut for ReadLock<'a> { - #[inline] - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -struct WriteLock<'a>(RwLockWriteGuard<'a, InnerSpoticordSession>); - -impl<'a> Deref for WriteLock<'a> { - type Target = RwLockWriteGuard<'a, InnerSpoticordSession>; - - #[inline] - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl<'a> DerefMut for WriteLock<'a> { - #[inline] - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -impl InnerSpoticordSession { - /// Internal version of disconnect, which does not abort the disconnect timer - async fn disconnect_no_abort(&mut self) { - // Disconnect from Spotify - if let Some(player) = self.player.take() { - player.shutdown(); - } - - self.disconnected = true; - self - .session_manager - .remove_session(self.guild_id, self.owner) - .await; - - if let Some(track) = self.track.take() { - if let Err(why) = track.stop() { - error!("Failed to stop track: {:?}", why); - } - }; - - let mut call = self.call.lock().await; - - if let Err(why) = call.leave().await { - error!("Failed to leave voice channel: {:?}", why); - } - - call.remove_all_global_events(); - } -} - -#[async_trait] -impl EventHandler for SpoticordSession { - async fn act(&self, ctx: &EventContext<'_>) -> Option { - match ctx { - EventContext::DriverDisconnect(_) => { - debug!("Driver disconnected, leaving voice channel"); - trace!("Arc strong count: {}", Arc::strong_count(&self.0)); - self.disconnect().await; - } - EventContext::ClientDisconnect(who) => { - trace!("Client disconnected, {}", who.user_id.to_string()); - trace!("Arc strong count: {}", Arc::strong_count(&self.0)); - - if let Some(session) = self - .session_manager() - .await - .find(UserId(who.user_id.0)) - .await - { - if session.guild_id().await == self.guild_id().await - && session.channel_id().await == self.channel_id().await - { - self.player_stopped().await; - } - } - } - _ => {} - } - - return None; - } -} - -impl Drop for InnerSpoticordSession { - fn drop(&mut self) { - log::trace!("drop InnerSpoticordSession"); - } -} diff --git a/src/session/pbi.rs b/src/session/pbi.rs deleted file mode 100644 index e3402b8..0000000 --- a/src/session/pbi.rs +++ /dev/null @@ -1,142 +0,0 @@ -use librespot::{ - core::spotify_id::SpotifyId, - protocol::metadata::{Episode, Track}, -}; - -use crate::utils; - -#[derive(Clone)] -pub struct PlaybackInfo { - last_updated: u128, - position_ms: u32, - - pub track: CurrentTrack, - pub spotify_id: SpotifyId, - - pub duration_ms: u32, - pub is_playing: bool, -} - -#[derive(Clone)] -pub enum CurrentTrack { - Track(Track), - Episode(Episode), -} - -impl PlaybackInfo { - /// Create a new instance of PlaybackInfo - pub fn new( - duration_ms: u32, - position_ms: u32, - is_playing: bool, - track: CurrentTrack, - spotify_id: SpotifyId, - ) -> Self { - Self { - last_updated: utils::get_time_ms(), - track, - spotify_id, - duration_ms, - position_ms, - is_playing, - } - } - - /// Update position, duration and playback state - pub fn update_pos_dur(&mut self, position_ms: u32, duration_ms: u32, is_playing: bool) { - self.position_ms = position_ms; - self.duration_ms = duration_ms; - self.is_playing = is_playing; - - self.last_updated = utils::get_time_ms(); - } - - /// Update spotify id, track and episode - pub fn update_track(&mut self, spotify_id: SpotifyId, track: CurrentTrack) { - self.spotify_id = spotify_id; - self.track = track; - } - - /// Get the current playback position - pub fn get_position(&self) -> u32 { - if self.is_playing { - let now = utils::get_time_ms(); - let diff = now - self.last_updated; - - self.position_ms + diff as u32 - } else { - self.position_ms - } - } - - /// Get the name of the track or episode - pub fn get_name(&self) -> String { - match &self.track { - CurrentTrack::Track(track) => track.get_name().to_string(), - CurrentTrack::Episode(episode) => episode.get_name().to_string(), - } - } - - /// Get the artist(s) or show name of the current track - pub fn get_artists(&self) -> String { - match &self.track { - CurrentTrack::Track(track) => track - .get_artist() - .iter() - .map(|a| a.get_name().to_string()) - .collect::>() - .join(", "), - CurrentTrack::Episode(episode) => episode.get_show().get_name().to_string(), - } - } - - /// Get the album art url - pub fn get_thumbnail_url(&self) -> Option { - let file_id = match &self.track { - CurrentTrack::Track(track) => { - let mut images = track.get_album().get_cover_group().get_image().to_vec(); - images.sort_by_key(|b| std::cmp::Reverse(b.get_width())); - - images - .get(0) - .as_ref() - .map(|image| image.get_file_id()) - .map(hex::encode) - } - CurrentTrack::Episode(episode) => { - let mut images = episode.get_covers().get_image().to_vec(); - images.sort_by_key(|b| std::cmp::Reverse(b.get_width())); - - images - .get(0) - .as_ref() - .map(|image| image.get_file_id()) - .map(hex::encode) - } - }; - - file_id.map(|id| format!("https://i.scdn.co/image/{id}")) - } - - /// Get the type of audio (track or episode) - #[allow(dead_code)] - pub fn get_type(&self) -> String { - match &self.track { - CurrentTrack::Track(_) => "track".to_string(), - CurrentTrack::Episode(_) => "episode".to_string(), - } - } - - /// Get the public facing url of the track or episode - #[allow(dead_code)] - pub fn get_url(&self) -> Option<&str> { - match &self.track { - CurrentTrack::Track(track) => track - .get_external_id() - .iter() - .find(|id| id.get_typ() == "spotify") - .map(|v| v.get_id()), - CurrentTrack::Episode(episode) => Some(episode.get_external_url()), - } - } -} diff --git a/src/stats.rs b/src/stats.rs deleted file mode 100644 index 7dde73a..0000000 --- a/src/stats.rs +++ /dev/null @@ -1,20 +0,0 @@ -use redis::{Client, Commands, RedisResult as Result}; - -#[derive(Clone)] -pub struct StatsManager { - redis: Client, -} - -impl StatsManager { - pub fn new(url: impl AsRef) -> Result { - let redis = Client::open(url.as_ref())?; - - Ok(StatsManager { redis }) - } - - pub fn set_active_count(&self, count: usize) -> Result<()> { - let mut con = self.redis.get_connection()?; - - con.set("sc-bot-active-servers", count.to_string()) - } -} diff --git a/src/utils/discord.rs b/src/utils/discord.rs deleted file mode 100644 index e0068e5..0000000 --- a/src/utils/discord.rs +++ /dev/null @@ -1,27 +0,0 @@ -use serenity::{ - model::{prelude::UserId, user::User}, - prelude::Context, -}; - -pub fn escape(text: impl Into) -> String { - let text: String = text.into(); - - text - .replace('\\', "\\\\") - .replace('*', "\\*") - .replace('_', "\\_") - .replace('~', "\\~") - .replace('`', "\\`") -} - -pub async fn get_user(ctx: &Context, id: UserId) -> Option { - let user = match ctx.cache.user(id) { - Some(user) => user, - None => match ctx.http.get_user(id.0).await { - Ok(user) => user, - Err(_) => return None, - }, - }; - - Some(user) -} diff --git a/src/utils/embed.rs b/src/utils/embed.rs deleted file mode 100644 index 839cc45..0000000 --- a/src/utils/embed.rs +++ /dev/null @@ -1,104 +0,0 @@ -use serenity::builder::CreateEmbed; - -pub enum Status { - Info = 0x0773D6, - Success = 0x3BD65D, - Warning = 0xF0D932, - Error = 0xFC1F28, - None = 0, -} - -impl From for serenity::utils::Colour { - fn from(value: Status) -> Self { - Self(value as u32) - } -} - -#[derive(Default)] -pub struct EmbedMessageOptions { - pub title: Option, - pub title_url: Option, - pub icon_url: Option, - pub description: String, - pub status: Option, - pub footer: Option, -} - -pub struct EmbedBuilder { - embed: EmbedMessageOptions, -} - -impl EmbedBuilder { - pub fn new() -> Self { - Self { - embed: EmbedMessageOptions::default(), - } - } - - pub fn title(mut self, title: impl Into) -> Self { - self.embed.title = Some(title.into()); - self - } - - pub fn title_url(mut self, title_url: impl Into) -> Self { - self.embed.title_url = Some(title_url.into()); - self - } - - pub fn icon_url(mut self, icon_url: impl Into) -> Self { - self.embed.icon_url = Some(icon_url.into()); - self - } - - pub fn description(mut self, description: impl Into) -> Self { - self.embed.description = description.into(); - self - } - - pub fn status(mut self, status: Status) -> Self { - self.embed.status = Some(status); - self - } - - pub fn footer(mut self, footer: impl Into) -> Self { - self.embed.footer = Some(footer.into()); - self - } - - /// Build the embed - pub fn build(self) -> EmbedMessageOptions { - self.embed - } -} - -pub fn make_embed_message( - embed: &'_ mut CreateEmbed, - options: EmbedMessageOptions, -) -> &'_ mut CreateEmbed { - let status = options.status.unwrap_or(Status::None); - - embed.author(|author| { - if let Some(title) = options.title { - author.name(title); - } - - if let Some(title_url) = options.title_url { - author.url(title_url); - } - - if let Some(icon_url) = options.icon_url { - author.icon_url(icon_url); - } - - author - }); - - if let Some(text) = options.footer { - embed.footer(|footer| footer.text(text)); - } - - embed.description(options.description); - embed.color(status as u32); - - embed -} diff --git a/src/utils/mod.rs b/src/utils/mod.rs deleted file mode 100644 index 3199249..0000000 --- a/src/utils/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -pub mod discord; -pub mod embed; -pub mod spotify; - -pub fn get_time() -> u64 { - let now = SystemTime::now(); - let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards"); - - since_the_epoch.as_secs() -} - -pub fn get_time_ms() -> u128 { - let now = SystemTime::now(); - let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards"); - - since_the_epoch.as_millis() -} - -pub fn time_to_str(time: u32) -> String { - let hour = 3600; - let min = 60; - - if time / hour >= 1 { - format!( - "{}h{}m{}s", - time / hour, - (time % hour) / min, - (time % hour) % min - ) - } else if time / min >= 1 { - format!("{}m{}s", time / min, time % min) - } else { - format!("{}s", time) - } -} diff --git a/src/utils/spotify.rs b/src/utils/spotify.rs deleted file mode 100644 index 7468693..0000000 --- a/src/utils/spotify.rs +++ /dev/null @@ -1,54 +0,0 @@ -use anyhow::{anyhow, Result}; -use log::{error, trace}; -use serde_json::Value; - -pub async fn get_username(token: impl Into) -> Result { - let token = token.into(); - let client = reqwest::Client::new(); - - let mut retries = 3; - - loop { - let response = match client - .get("https://api.spotify.com/v1/me") - .bearer_auth(&token) - .send() - .await - { - Ok(response) => response, - Err(why) => { - error!("Failed to get username: {}", why); - return Err(why.into()); - } - }; - - if response.status().as_u16() >= 500 && retries > 0 { - retries -= 1; - continue; - } - - if response.status() != 200 { - error!("Failed to get username: {}", response.status()); - return Err(anyhow!( - "Failed to get track info: Invalid status code: {}", - response.status() - )); - } - - let body: Value = match response.json().await { - Ok(body) => body, - Err(why) => { - error!("Failed to parse body: {}", why); - return Err(why.into()); - } - }; - - if let Value::String(username) = &body["id"] { - trace!("Got username: {}", username); - return Ok(username.clone()); - } - - error!("Missing 'id' field in body: {:#?}", body); - return Err(anyhow!("Failed to parse body: Invalid body received")); - } -}