12 Commits

Author SHA1 Message Date
7edd14c628 save tracks
All checks were successful
tests / fmt (push) Successful in 48s
tests / clippy (push) Successful in 1m14s
tests / pre-commit (push) Successful in 1m21s
tests / test (push) Successful in 1m32s
tests / build (push) Successful in 1m48s
deploy / release-image (push) Successful in 4m45s
2024-06-27 22:45:09 +02:00
3242f23f84 play around with input types
All checks were successful
tests / fmt (push) Successful in 1m11s
tests / clippy (push) Successful in 2m24s
tests / pre-commit (push) Successful in 2m23s
tests / build (push) Successful in 2m36s
tests / test (push) Successful in 2m40s
2024-06-27 19:59:15 +02:00
8985945659 add database
All checks were successful
tests / fmt (push) Successful in 1m46s
tests / clippy (push) Successful in 1m48s
tests / test (push) Successful in 1m50s
tests / pre-commit (push) Successful in 2m5s
tests / build (push) Successful in 2m31s
deploy / release-image (push) Successful in 5m44s
2024-06-20 20:16:19 +02:00
4a69e0f578 cleanup
All checks were successful
tests / build (push) Successful in 1m4s
tests / fmt (push) Successful in 2m17s
tests / clippy (push) Successful in 2m14s
tests / pre-commit (push) Successful in 2m12s
tests / test (push) Successful in 2m27s
deploy / release-image (push) Successful in 6m11s
2024-06-19 19:14:44 +02:00
cad6cf22fa fix empty pages
All checks were successful
tests / fmt (push) Successful in 1m16s
tests / build (push) Successful in 1m54s
tests / clippy (push) Successful in 1m50s
tests / pre-commit (push) Successful in 1m50s
tests / test (push) Successful in 2m13s
deploy / release-image (push) Successful in 5m34s
2024-06-19 00:24:32 +02:00
9f0e934f92 use original_url returned by yt-dlp
All checks were successful
tests / build (push) Successful in 56s
tests / test (push) Successful in 3m4s
tests / fmt (push) Successful in 3m28s
tests / clippy (push) Successful in 3m55s
tests / pre-commit (push) Successful in 3m58s
deploy / release-image (push) Successful in 6m0s
2024-06-18 23:38:37 +02:00
92be6c26a6 fix pagination + add refresh button
All checks were successful
tests / fmt (push) Successful in 1m57s
tests / test (push) Successful in 2m7s
tests / clippy (push) Successful in 2m5s
tests / build (push) Successful in 2m11s
tests / pre-commit (push) Successful in 2m5s
deploy / release-image (push) Successful in 5m3s
2024-06-18 23:27:47 +02:00
c5d9c49452 improve message format
All checks were successful
tests / fmt (push) Successful in 1m50s
tests / test (push) Successful in 2m1s
tests / clippy (push) Successful in 1m59s
tests / pre-commit (push) Successful in 1m58s
tests / build (push) Successful in 2m7s
deploy / release-image (push) Successful in 5m22s
2024-06-18 17:06:33 +02:00
dbaf1a1374 reset loop state on leave/stop 2024-06-18 15:49:58 +02:00
c0d9f6cad5 update README.md
All checks were successful
tests / fmt (push) Successful in 36s
tests / build (push) Successful in 46s
tests / test (push) Successful in 54s
tests / clippy (push) Successful in 1m45s
tests / pre-commit (push) Successful in 1m52s
deploy / release-image (push) Successful in 6m23s
2024-06-18 11:51:28 +02:00
1aa0efc4a6 collect all youtube errors
All checks were successful
tests / fmt (push) Successful in 33s
tests / build (push) Successful in 45s
tests / test (push) Successful in 2m20s
tests / clippy (push) Successful in 51s
tests / pre-commit (push) Successful in 53s
deploy / release-image (push) Successful in 4m48s
2024-06-18 11:26:52 +02:00
ab7f56fe05 disable arm target (#8)
All checks were successful
tests / test (push) Successful in 1m27s
tests / clippy (push) Successful in 1m32s
tests / pre-commit (push) Successful in 1m33s
tests / fmt (push) Successful in 1m43s
tests / build (push) Successful in 1m42s
deploy / release-image (push) Successful in 4m34s
Reviewed-on: #8
2024-06-18 11:19:44 +02:00
23 changed files with 1337 additions and 226 deletions

View File

@@ -12,3 +12,6 @@ README.md
# Cargo files
**/*.rs.bk
/target/
# Database files
data

View File

@@ -5,6 +5,9 @@ on:
branches:
- main
paths-ignore:
- 'README.md'
jobs:
release-image:
runs-on: ubuntu-latest
@@ -26,6 +29,5 @@ jobs:
with:
platforms: |
linux/amd64
# linux/arm64
push: true
tags: jheuel/ohrwurm:latest

3
.gitignore vendored
View File

@@ -1,3 +1,6 @@
/target
.env
.vscode
# Database files
data

675
Cargo.lock generated
View File

@@ -27,6 +27,19 @@ dependencies = [
"generic-array",
]
[[package]]
name = "ahash"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
dependencies = [
"cfg-if",
"getrandom",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.3"
@@ -51,6 +64,12 @@ dependencies = [
"alloc-no-stdlib",
]
[[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"
@@ -101,6 +120,15 @@ dependencies = [
"syn 2.0.66",
]
[[package]]
name = "atoi"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528"
dependencies = [
"num-traits",
]
[[package]]
name = "audiopus"
version = "0.3.0-rc.0"
@@ -160,6 +188,12 @@ 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"
version = "1.3.2"
@@ -171,6 +205,9 @@ name = "bitflags"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
dependencies = [
"serde",
]
[[package]]
name = "block-buffer"
@@ -246,7 +283,9 @@ checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"wasm-bindgen",
"windows-targets 0.52.5",
]
@@ -270,6 +309,12 @@ dependencies = [
"cc",
]
[[package]]
name = "const-oid"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]]
name = "core-foundation"
version = "0.9.4"
@@ -295,6 +340,21 @@ dependencies = [
"libc",
]
[[package]]
name = "crc"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636"
dependencies = [
"crc-catalog",
]
[[package]]
name = "crc-catalog"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
[[package]]
name = "crc32fast"
version = "1.4.2"
@@ -313,6 +373,15 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.20"
@@ -364,6 +433,17 @@ version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2"
[[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"
@@ -392,7 +472,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"subtle",
]
[[package]]
@@ -422,6 +504,21 @@ version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
[[package]]
name = "dotenvy"
version = "0.15.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
[[package]]
name = "either"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b"
dependencies = [
"serde",
]
[[package]]
name = "encoding_rs"
version = "0.8.34"
@@ -447,6 +544,23 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "etcetera"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943"
dependencies = [
"cfg-if",
"home",
"windows-sys 0.48.0",
]
[[package]]
name = "event-listener"
version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "extended"
version = "0.1.0"
@@ -554,6 +668,17 @@ dependencies = [
"futures-util",
]
[[package]]
name = "futures-intrusive"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
dependencies = [
"futures-core",
"lock_api",
"parking_lot",
]
[[package]]
name = "futures-io"
version = "0.3.30"
@@ -668,6 +793,28 @@ name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
"allocator-api2",
]
[[package]]
name = "hashlink"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7"
dependencies = [
"hashbrown",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "hermit-abi"
@@ -675,6 +822,39 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hkdf"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
dependencies = [
"hmac",
]
[[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]]
name = "http"
version = "0.2.12"
@@ -983,6 +1163,9 @@ name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
dependencies = [
"spin 0.5.2",
]
[[package]]
name = "libc"
@@ -990,6 +1173,23 @@ version = "0.2.155"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
[[package]]
name = "libm"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
[[package]]
name = "libsqlite3-sys"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4e226dcd58b4be396f7bd3c20da8fdee2911400705297ba7d2d7cc2c30f716"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "libz-sys"
version = "1.1.18"
@@ -1062,6 +1262,16 @@ dependencies = [
"regex-automata 0.1.10",
]
[[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"
@@ -1084,6 +1294,12 @@ dependencies = [
"unicase",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.7.3"
@@ -1142,6 +1358,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
@@ -1152,6 +1378,23 @@ dependencies = [
"winapi",
]
[[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"
@@ -1176,6 +1419,17 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1183,6 +1437,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
@@ -1210,6 +1465,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"chrono",
"dashmap",
"dotenv",
"futures",
@@ -1218,6 +1474,7 @@ dependencies = [
"serde",
"serde_json",
"songbird",
"sqlx",
"symphonia",
"tokio",
"tracing",
@@ -1321,11 +1578,26 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"redox_syscall 0.5.2",
"smallvec",
"windows-targets 0.52.5",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
dependencies = [
"base64ct",
]
[[package]]
name = "percent-encoding"
version = "2.3.1"
@@ -1364,6 +1636,27 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkcs1"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
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"
@@ -1489,6 +1782,15 @@ dependencies = [
"rustfft",
]
[[package]]
name = "redox_syscall"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
dependencies = [
"bitflags 1.3.2",
]
[[package]]
name = "redox_syscall"
version = "0.5.2"
@@ -1628,6 +1930,26 @@ dependencies = [
"crossbeam-utils",
]
[[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 = "rubato"
version = "0.14.1"
@@ -1994,6 +2316,17 @@ dependencies = [
"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]]
name = "sharded-slab"
version = "0.1.7"
@@ -2012,6 +2345,16 @@ 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 = "slab"
version = "0.4.9"
@@ -2097,6 +2440,224 @@ 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 = "sqlformat"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f895e3734318cc55f1fe66258926c9b910c124d47520339efecbb6c59cec7c1f"
dependencies = [
"nom",
"unicode_categories",
]
[[package]]
name = "sqlx"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9a2ccff1a000a5a59cd33da541d9f2fdcd9e6e8229cc200565942bff36d0aaa"
dependencies = [
"sqlx-core",
"sqlx-macros",
"sqlx-mysql",
"sqlx-postgres",
"sqlx-sqlite",
]
[[package]]
name = "sqlx-core"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24ba59a9342a3d9bab6c56c118be528b27c9b60e490080e9711a04dccac83ef6"
dependencies = [
"ahash",
"atoi",
"byteorder",
"bytes",
"chrono",
"crc",
"crossbeam-queue",
"either",
"event-listener",
"futures-channel",
"futures-core",
"futures-intrusive",
"futures-io",
"futures-util",
"hashlink",
"hex",
"indexmap",
"log",
"memchr",
"once_cell",
"paste",
"percent-encoding",
"serde",
"serde_json",
"sha2",
"smallvec",
"sqlformat",
"thiserror",
"tokio",
"tokio-stream",
"tracing",
"url",
]
[[package]]
name = "sqlx-macros"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea40e2345eb2faa9e1e5e326db8c34711317d2b5e08d0d5741619048a803127"
dependencies = [
"proc-macro2",
"quote",
"sqlx-core",
"sqlx-macros-core",
"syn 1.0.109",
]
[[package]]
name = "sqlx-macros-core"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5833ef53aaa16d860e92123292f1f6a3d53c34ba8b1969f152ef1a7bb803f3c8"
dependencies = [
"dotenvy",
"either",
"heck",
"hex",
"once_cell",
"proc-macro2",
"quote",
"serde",
"serde_json",
"sha2",
"sqlx-core",
"sqlx-mysql",
"sqlx-postgres",
"sqlx-sqlite",
"syn 1.0.109",
"tempfile",
"tokio",
"url",
]
[[package]]
name = "sqlx-mysql"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ed31390216d20e538e447a7a9b959e06ed9fc51c37b514b46eb758016ecd418"
dependencies = [
"atoi",
"base64 0.21.7",
"bitflags 2.5.0",
"byteorder",
"bytes",
"chrono",
"crc",
"digest",
"dotenvy",
"either",
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"generic-array",
"hex",
"hkdf",
"hmac",
"itoa",
"log",
"md-5",
"memchr",
"once_cell",
"percent-encoding",
"rand",
"rsa",
"serde",
"sha1",
"sha2",
"smallvec",
"sqlx-core",
"stringprep",
"thiserror",
"tracing",
"whoami",
]
[[package]]
name = "sqlx-postgres"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c824eb80b894f926f89a0b9da0c7f435d27cdd35b8c655b114e58223918577e"
dependencies = [
"atoi",
"base64 0.21.7",
"bitflags 2.5.0",
"byteorder",
"chrono",
"crc",
"dotenvy",
"etcetera",
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"hex",
"hkdf",
"hmac",
"home",
"itoa",
"log",
"md-5",
"memchr",
"once_cell",
"rand",
"serde",
"serde_json",
"sha2",
"smallvec",
"sqlx-core",
"stringprep",
"thiserror",
"tracing",
"whoami",
]
[[package]]
name = "sqlx-sqlite"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b244ef0a8414da0bed4bb1910426e890b19e5e9bccc27ada6b797d05c55ae0aa"
dependencies = [
"atoi",
"chrono",
"flume",
"futures-channel",
"futures-core",
"futures-executor",
"futures-intrusive",
"futures-util",
"libsqlite3-sys",
"log",
"percent-encoding",
"serde",
"sqlx-core",
"tracing",
"url",
"urlencoding",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@@ -2120,6 +2681,17 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
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 = "subtle"
version = "2.5.0"
@@ -2464,6 +3036,21 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.38.0"
@@ -2535,6 +3122,17 @@ dependencies = [
"tokio",
]
[[package]]
name = "tokio-stream"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tokio-tungstenite"
version = "0.18.0"
@@ -2901,12 +3499,45 @@ dependencies = [
"version_check",
]
[[package]]
name = "unicode-bidi"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75"
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "unicode-normalization"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-properties"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
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_categories"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -2941,6 +3572,12 @@ dependencies = [
"serde",
]
[[package]]
name = "urlencoding"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "utf-8"
version = "0.7.6"
@@ -3001,6 +3638,12 @@ version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
[[package]]
name = "wasm-bindgen"
version = "0.2.92"
@@ -3115,6 +3758,16 @@ dependencies = [
"rustls-pki-types",
]
[[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",
]
[[package]]
name = "winapi"
version = "0.3.9"
@@ -3340,6 +3993,26 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.7.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae87e3fcd617500e5d106f0380cf7b77f3c6092aae37191433159dda23cfb087"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.7.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.66",
]
[[package]]
name = "zerofrom"
version = "0.1.4"

View File

@@ -9,6 +9,7 @@ license = "MIT"
symphonia = { version = "0.5.2", features=["all"] }
songbird = { version = "0.4.0", features = ["driver", "gateway", "twilight", "rustls", "builtin-queue"] }
tokio = { features = ["macros", "rt-multi-thread", "signal", "sync"], version = "1" }
sqlx = { version = "0.7", features = [ "runtime-tokio", "sqlite", "chrono", "migrate"] }
regex = { version = "1", features = ["unicode-case"] }
futures = "0.3"
reqwest = "0.11"
@@ -23,8 +24,9 @@ twilight-util = { version = "0.15", features=["builder"] }
dotenv = "0.15.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
url = "2.5.0"
url = "2.5.1"
anyhow = "1.0.86"
dashmap = "5.5.3"
async-trait = "0.1.80"
uuid = "1.8.0"
chrono = "0.4.38"

View File

@@ -8,7 +8,7 @@
Ohrwurm is a user-friendly bot designed to play music in Discord voice chats. Once added to your server, you can request a song using the command `/play {query}`, where query can be a URL to a YouTube video or playlist, or a simple search term. The bot will fetch the song and start playing it. You can pause the music with `/pause`, resume playback with `/resume`, and stop and clear the queue with `/stop`. If the bot is alone in a voice chat, it will automatically leave, but you can also manually make it leave with the `/leave` command.
# Deployment
To deploy Ohrwurm with Docker, you can use the [provided Docker](https://hub.docker.com/r/jheuel/ohrwurm) image:
To deploy Ohrwurm with Docker, you can use the [provided Docker image](https://hub.docker.com/r/jheuel/ohrwurm):
```bash
docker run -d \
--name ohrwurm \

3
build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
println!("cargo:rerun-if-changed=migrations");
}

View File

@@ -0,0 +1,33 @@
CREATE TABLE IF NOT EXISTS tracks
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
channel TEXT NOT NULL,
duration TEXT NOT NULL,
thumbnail TEXT NOT NULL,
updated DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS queries
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
guild_id TEXT NOT NULL,
track_id NUMBER NOT NULL,
updated DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS users
(
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
global_name TEXT,
updated DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS guilds
(
id TEXT PRIMARY KEY,
updated DATETIME NOT NULL
);

View File

@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS blobs
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
data BLOB
);

View File

@@ -38,6 +38,9 @@ pub(crate) async fn join_channel(
call.deafen(true).await?;
}
// create guild config
state.guild_settings.entry(guild_id).or_default();
Ok(())
}

View File

@@ -1,6 +1,56 @@
use crate::state::State;
use std::error::Error;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use crate::state::{State, StateRef};
use anyhow::Context;
use std::{error::Error, sync::Arc};
use twilight_model::{
gateway::payload::incoming::InteractionCreate,
id::{marker::GuildMarker, Id},
};
pub(crate) async fn leave_if_alone(
guild_id: Id<GuildMarker>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let user = state
.cache
.current_user()
.context("Cannot get current user")?;
let user_voice_state = state
.cache
.voice_state(user.id, guild_id)
.context("Cannot get voice state")?;
let channel = state
.cache
.channel(user_voice_state.channel_id())
.context("Cannot get channel")?;
let channel_voice_states = state
.cache
.voice_channel_states(channel.id)
.context("Cannot get voice channel")?;
let count = channel_voice_states.count();
// count is 1 if the bot is the only one in the channel
if count == 1 {
leave_channel(guild_id, Arc::clone(&state)).await?;
}
Ok(())
}
pub(crate) async fn leave_channel(
guild_id: Id<GuildMarker>,
state: Arc<StateRef>,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
// stop playing
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
call.queue().stop();
}
// leave the voice channel
state.songbird.leave(guild_id).await?;
// reset guild settings
state.guild_settings.remove(&guild_id);
Ok(())
}
pub(crate) async fn leave(
interaction: Box<InteractionCreate>,
@@ -16,6 +66,8 @@ pub(crate) async fn leave(
let Some(guild_id) = interaction.guild_id else {
return Ok(());
};
state.songbird.leave(guild_id).await?;
leave_channel(guild_id, Arc::clone(&state)).await?;
Ok(())
}

View File

@@ -1,5 +1,5 @@
use crate::metadata::MetadataMap;
use crate::state::{Settings, State, StateRef};
use crate::state::{State, StateRef};
use async_trait::async_trait;
use songbird::{Event, EventContext, EventHandler, TrackEvent};
use std::ops::Sub;
@@ -29,14 +29,8 @@ pub(crate) async fn loop_queue(
return Ok(());
};
state
.guild_settings
.entry(guild_id)
.or_insert_with(|| Settings { loop_queue: false });
state.guild_settings.entry(guild_id).and_modify(|settings| {
settings.loop_queue = !settings.loop_queue;
println!("loop_queue: {}", settings.loop_queue);
});
let looping = state

View File

@@ -3,6 +3,7 @@ pub(crate) use join::join;
mod leave;
pub(crate) use leave::leave;
pub(crate) use leave::leave_if_alone;
mod pause;
pub(crate) use pause::pause;

View File

@@ -1,16 +1,24 @@
use crate::colors;
use crate::commands::join::join_channel;
use crate::db::track::{insert_blob, Blob};
use crate::metadata::{Metadata, MetadataMap};
use crate::state::State;
use crate::state::{State, StateRef};
use crate::{colors, db};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use songbird::input::cached::Memory;
use songbird::input::{Compose, YoutubeDl};
use songbird::tracks::Track;
use std::io::{BufRead, BufReader};
use songbird::{Event, EventContext, EventHandler, TrackEvent};
use std::io::{BufRead, BufReader, Read};
use std::ops::Sub;
use std::sync::Arc;
use std::{error::Error, time::Duration};
use tokio::process::Command;
use tracing::debug;
use twilight_model::channel::message::embed::{
EmbedAuthor, EmbedField, EmbedFooter, EmbedThumbnail,
};
use twilight_model::channel::message::MessageFlags;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
@@ -161,17 +169,74 @@ pub(crate) async fn play(
call.queue().resume()?;
}
struct TrackType {
url: String,
title: Option<String>,
duration_string: String,
channel: String,
thumbnail: Option<String>,
}
let mut tracks_added = vec![];
for track in &tracks {
tracing::debug!("track: {:?}", track);
let url = track.url.clone().or(track.original_url.clone()).ok_or("")?;
for yttrack in &tracks {
tracing::debug!("track: {:?}", yttrack);
let url = yttrack
.original_url
.clone()
.or(yttrack.url.clone())
.ok_or("Could not find url")?;
let mut src = YoutubeDl::new(reqwest::Client::new(), url.clone());
let src_copy = src.clone();
let track: Track = src_copy.into();
let memory = Memory::new(src.clone().into()).await.unwrap();
let track: Track = memory.new_handle().into();
if let Ok(metadata) = src.aux_metadata().await {
debug!("metadata: {:?}", metadata);
tracks_added.push((url.clone(), metadata.title.clone()));
let (author_name, author_global_name) = if let Some(author) = interaction.author() {
(author.name.clone(), author.global_name.clone())
} else {
("".to_string(), None)
};
db::track::insert_guild(&state.pool, db::track::Guild::new(guild_id.to_string()))
.await
.expect("failed to insert guild: {e}");
db::track::insert_user(
&state.pool,
db::track::User::new(user_id.to_string(), author_name, author_global_name),
)
.await
.expect("failed to insert user: {e}");
let track_id = db::track::insert_track(
&state.pool,
db::track::Track::new(
url.clone(),
yttrack.title.clone(),
yttrack.channel.clone(),
yttrack.duration_string.clone(),
metadata.thumbnail.clone().unwrap_or_default(),
),
)
.await
.expect("failed to insert track: {e}");
db::track::insert_query(
&state.pool,
db::track::Query::new(user_id.to_string(), guild_id.to_string(), track_id),
)
.await
.expect("failed to insert track: {e}");
tracks_added.push(TrackType {
url: url.clone(),
title: metadata.title.clone(),
duration_string: yttrack.duration_string.clone(),
channel: yttrack.channel.clone(),
thumbnail: metadata.thumbnail.clone(),
});
if let Some(call_lock) = state.songbird.get(guild_id) {
let mut call = call_lock.lock().await;
@@ -192,21 +257,74 @@ pub(crate) async fn play(
url,
src,
});
handle
.add_event(
Event::Track(TrackEvent::Preparing),
TrackPreparingNotifier {
memory,
track_id,
state: Arc::clone(&state),
},
)
.expect("could not add event");
}
}
}
let mut content = String::new();
let num_tracks_added = tracks_added.len();
match num_tracks_added {
0 => {}
let embeds = match num_tracks_added {
0 => {
vec![]
}
1 => {
let (title, url) = if let Some(track) = tracks_added.first() {
let track = track.clone();
(track.1.unwrap_or("Unknown".to_string()), track.0)
} else {
("Unknown".to_string(), "".to_string())
};
content = format!("Added [{}]({}) to the queue", title, url);
let track = tracks_added.first().unwrap();
let host = Url::parse(&track.url)?;
let host = host
.host_str()
.unwrap_or_default()
.trim_start_matches("www.");
let mut embed = EmbedBuilder::new()
.author(EmbedAuthor {
name: "🔊 Added to queue".to_string(),
icon_url: None,
proxy_icon_url: None,
url: None,
})
.title(track.title.clone().unwrap_or("Unknown".to_string()))
.url(track.url.clone())
.color(colors::BLURPLE)
.footer(EmbedFooter {
text: format!("Streaming from {}", host),
icon_url: Some(format!(
"https://www.google.com/s2/favicons?domain={}",
host
)),
proxy_icon_url: None,
})
.field(EmbedField {
inline: true,
name: "Duration".to_string(),
value: track.duration_string.clone(),
})
.field(EmbedField {
inline: true,
name: "Channel".to_string(),
value: track.channel.clone(),
})
.build();
if let Some(thumbnail) = &track.thumbnail {
embed.thumbnail = Some(EmbedThumbnail {
height: None,
proxy_url: None,
url: thumbnail.to_string(),
width: None,
});
}
vec![embed]
}
_ => {
let first_track = tracks.first().unwrap();
@@ -227,13 +345,14 @@ pub(crate) async fn play(
"Added {} tracks to the queue:\n",
num_tracks_added
));
let embed = EmbedBuilder::new()
.description(content)
.color(colors::BLURPLE)
.build();
vec![embed]
}
}
};
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::BLURPLE)
.build()];
state
.http
.interaction(interaction.application_id)
@@ -244,6 +363,31 @@ pub(crate) async fn play(
Ok(())
}
struct TrackPreparingNotifier {
memory: Memory,
track_id: i64,
state: Arc<StateRef>,
}
#[async_trait]
impl EventHandler for TrackPreparingNotifier {
async fn act(&self, _ctx: &EventContext<'_>) -> Option<Event> {
tracing::info!("Build buffer");
let mut reader = BufReader::new(self.memory.new_handle());
let mut bytes = Vec::new();
reader
.read_to_end(&mut bytes)
.expect("could not read track in memory");
tracing::info!("Saving track");
insert_blob(&self.state.pool, Blob::new(self.track_id, bytes))
.await
.expect("could not insert blob");
tracing::info!("Saved");
None
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -59,9 +59,9 @@ pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Ve
}
message.push('\n');
let max_pages = queue.len() / TRACKS_PER_PAGE;
if max_pages > 0 {
message.push_str(&format!("page {}/{}", 1 + page, 1 + max_pages));
let n_pages = (queue.len() + TRACKS_PER_PAGE - 1) / TRACKS_PER_PAGE;
if n_pages > 1 {
message.push_str(&format!("page {}/{}", 1 + page, n_pages));
}
vec![EmbedBuilder::new()
.description(&message)
@@ -69,10 +69,7 @@ pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Ve
.build()]
}
pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component> {
if max_pages == 0 {
return Vec::new();
}
pub(crate) fn build_action_row(page: usize, n_pages: usize) -> Vec<Component> {
vec![Component::ActionRow(ActionRow {
components: vec![
Component::Button(Button {
@@ -85,6 +82,16 @@ pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component>
url: None,
disabled: page == 0,
}),
Component::Button(Button {
custom_id: Some(format!("page:{}", page)),
style: ButtonStyle::Primary,
label: Some("Refresh".to_string()),
emoji: Some(ReactionType::Unicode {
name: "🔄".to_string(),
}),
url: None,
disabled: false,
}),
Component::Button(Button {
custom_id: Some(format!("page:{}", page + 1)),
style: ButtonStyle::Primary,
@@ -93,7 +100,7 @@ pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component>
name: "➡️".to_string(),
}),
url: None,
disabled: page >= max_pages,
disabled: page >= n_pages - 1,
}),
],
})]
@@ -139,7 +146,8 @@ pub(crate) async fn queue(
}
let embeds = build_queue_embeds(&queue, 0).await;
let action_row = build_action_row(0, queue.len() / TRACKS_PER_PAGE);
let n_pages = (queue.len() + TRACKS_PER_PAGE - 1) / TRACKS_PER_PAGE;
let action_row = build_action_row(0, n_pages);
state
.http

View File

@@ -23,6 +23,10 @@ pub(crate) async fn stop(
return Ok(());
};
state.guild_settings.entry(guild_id).and_modify(|settings| {
settings.loop_queue = false;
});
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
call.queue().stop();

1
src/db/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod track;

168
src/db/track.rs Normal file
View File

@@ -0,0 +1,168 @@
use chrono::{DateTime, Utc};
use sqlx::FromRow;
#[derive(Debug, FromRow)]
pub(crate) struct Track {
#[allow(dead_code)]
pub(crate) id: i64,
pub(crate) url: String,
pub(crate) title: String,
pub(crate) channel: String,
pub(crate) duration: String,
pub(crate) thumbnail: String,
pub(crate) updated: DateTime<Utc>,
}
impl Track {
pub(crate) fn new(
url: String,
title: String,
channel: String,
duration: String,
thumbnail: String,
) -> Self {
Self {
id: 0,
url,
title,
channel,
duration,
thumbnail,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_track(
pool: &sqlx::SqlitePool,
track: Track,
) -> Result<i64, sqlx::Error> {
let query =
"INSERT OR REPLACE INTO tracks (url, title, channel, duration, thumbnail, updated) VALUES ($1, $2, $3, $4, $5, $6)";
let res = sqlx::query(query)
.bind(track.url)
.bind(track.title)
.bind(track.channel)
.bind(track.duration)
.bind(track.thumbnail)
.bind(track.updated)
.execute(pool)
.await?;
Ok(res.last_insert_rowid())
}
#[derive(Debug, FromRow)]
pub(crate) struct User {
pub(crate) id: String,
pub(crate) name: String,
pub(crate) global_name: Option<String>,
pub(crate) updated: DateTime<Utc>,
}
impl User {
pub(crate) fn new(id: String, name: String, global_name: Option<String>) -> Self {
Self {
id,
name,
global_name,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_user(pool: &sqlx::SqlitePool, user: User) -> Result<(), sqlx::Error> {
let query =
"INSERT OR REPLACE INTO users (id, name, global_name, updated) VALUES ($1, $2, $3, $4)";
sqlx::query(query)
.bind(user.id)
.bind(user.name)
.bind(user.global_name)
.bind(user.updated)
.execute(pool)
.await?;
Ok(())
}
#[derive(Debug, FromRow)]
pub(crate) struct Query {
#[allow(dead_code)]
pub(crate) id: i64,
pub(crate) user_id: String,
pub(crate) guild_id: String,
pub(crate) track_id: i64,
pub(crate) updated: DateTime<Utc>,
}
impl Query {
pub(crate) fn new(user_id: String, guild_id: String, track_id: i64) -> Self {
Self {
id: 0,
user_id,
guild_id,
track_id,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_query(pool: &sqlx::SqlitePool, q: Query) -> Result<i64, sqlx::Error> {
let query =
"INSERT OR REPLACE INTO queries (user_id, guild_id, track_id, updated) VALUES ($1, $2, $3, $4)";
let res = sqlx::query(query)
.bind(q.user_id)
.bind(q.guild_id)
.bind(q.track_id)
.bind(q.updated)
.execute(pool)
.await?;
Ok(res.last_insert_rowid())
}
#[derive(Debug, FromRow)]
pub(crate) struct Guild {
pub(crate) id: String,
pub(crate) updated: DateTime<Utc>,
}
impl Guild {
pub(crate) fn new(id: String) -> Self {
Self {
id,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_guild(
pool: &sqlx::SqlitePool,
guild: Guild,
) -> Result<i64, sqlx::Error> {
let query = "INSERT OR REPLACE INTO guilds (id, updated) VALUES ($1, $2)";
let res = sqlx::query(query)
.bind(guild.id)
.bind(guild.updated)
.execute(pool)
.await?;
Ok(res.last_insert_rowid())
}
#[derive(Debug, FromRow)]
pub(crate) struct Blob {
pub(crate) id: i64,
pub(crate) data: Vec<u8>,
}
impl Blob {
pub(crate) fn new(id: i64, data: Vec<u8>) -> Self {
Self { id, data }
}
}
pub(crate) async fn insert_blob(pool: &sqlx::SqlitePool, blob: Blob) -> Result<(), sqlx::Error> {
let query = "INSERT OR REPLACE INTO blobs (id, data) VALUES ($1, $2)";
sqlx::query(query)
.bind(blob.id)
.bind(blob.data)
.execute(pool)
.await?;
Ok(())
}

View File

@@ -1,79 +1,19 @@
use crate::commands::queue::{build_action_row, build_queue_embeds, TRACKS_PER_PAGE};
use crate::commands::{delete, join, leave, loop_queue, pause, play, queue, resume, skip, stop};
use crate::state::State;
use futures::Future;
use std::error::Error;
use std::sync::Arc;
use tracing::debug;
use twilight_gateway::Event;
use twilight_model::application::interaction::application_command::{
CommandData, CommandOptionValue,
use crate::commands::{
delete, join, leave, leave_if_alone, loop_queue, pause, play, queue, resume, skip, stop,
};
use crate::interaction_commands::InteractionCommand;
use crate::state::State;
use crate::utils::spawn;
use anyhow::Context;
use std::sync::Arc;
use twilight_gateway::Event;
use twilight_model::application::interaction::message_component::MessageComponentInteractionData;
use twilight_model::application::interaction::InteractionData;
use twilight_model::gateway::payload::incoming::VoiceStateUpdate;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
use twilight_util::builder::InteractionResponseDataBuilder;
#[derive(Debug)]
enum InteractionCommand {
Play(String),
Stop,
Pause,
Skip,
Loop,
Resume,
Leave,
Join,
Queue,
NotImplemented,
}
fn spawn(
fut: impl Future<Output = Result<(), Box<dyn Error + Send + Sync + 'static>>> + Send + 'static,
) {
tokio::spawn(async move {
if let Err(why) = fut.await {
tracing::debug!("handler error: {:?}", why);
}
});
}
pub(crate) async fn leave_if_alone(
update: VoiceStateUpdate,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let guild_id = update.guild_id.ok_or("Guild ID not found")?;
let user = state
.cache
.current_user()
.ok_or("Cannot get current user")?;
let user_voice_state = state
.cache
.voice_state(user.id, guild_id)
.ok_or("Cannot get voice state")?;
let channel = state
.cache
.channel(user_voice_state.channel_id())
.ok_or("Cannot get channel")?;
let channel_voice_states = state
.cache
.voice_channel_states(channel.id)
.ok_or("Cannot get voice channel")?;
let count = channel_voice_states.count();
// count is 1 if the bot is the only one in the channel
if count == 1 {
// stop playing
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
call.queue().stop();
}
// leave the voice channel
state.songbird.leave(guild_id).await?;
}
Ok(())
}
pub(crate) struct Handler {
state: State,
}
@@ -83,6 +23,13 @@ impl Handler {
Self { state }
}
pub(crate) async fn act(&self, event: Event) -> anyhow::Result<()> {
self.handle_messages(&event).await?;
self.handle_voice_state_update(&event).await?;
self.handle_interaction(&event).await?;
Ok(())
}
async fn handle_messages(&self, event: &Event) -> anyhow::Result<()> {
match event {
Event::MessageCreate(message) if message.content.starts_with('!') => {
if message.content.contains("!delete") {
@@ -90,121 +37,102 @@ impl Handler {
}
Ok(())
}
_ => Ok(()),
}
}
async fn handle_voice_state_update(&self, event: &Event) -> anyhow::Result<()> {
match event {
Event::VoiceStateUpdate(update) => {
spawn(leave_if_alone(*update.clone(), Arc::clone(&self.state)));
let guild_id = update.guild_id.context("Guild ID not found")?;
spawn(leave_if_alone(guild_id, Arc::clone(&self.state)));
Ok(())
}
Event::InteractionCreate(interaction) => {
tracing::info!("interaction: {:?}", &interaction);
match &interaction.data {
Some(InteractionData::ApplicationCommand(command)) => {
let interaction_command = parse_interaction_command(command);
debug!("{:?}", interaction_command);
match interaction_command {
InteractionCommand::Play(query) => {
spawn(play(interaction, Arc::clone(&self.state), query))
}
InteractionCommand::Stop => {
spawn(stop(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Pause => {
spawn(pause(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Skip => {
spawn(skip(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Loop => {
spawn(loop_queue(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Resume => {
spawn(resume(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Leave => {
spawn(leave(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Join => {
spawn(join(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Queue => {
spawn(queue(interaction, Arc::clone(&self.state)))
}
_ => {}
}
Ok(())
}
Some(InteractionData::MessageComponent(data)) => {
tracing::info!("message component: {:?}", data);
_ => Ok(()),
}
}
if !data.custom_id.starts_with("page:") {
return Ok(());
}
let page = data
.custom_id
.trim_start_matches("page:")
.parse::<usize>()
.unwrap_or(0);
tracing::info!("page: {:?}", page);
if let Some(guild_id) = interaction.guild_id {
let mut queue = Vec::new();
if let Some(call_lock) = self.state.songbird.get(guild_id) {
let call = call_lock.lock().await;
queue = call.queue().current_queue();
}
let embeds = build_queue_embeds(&queue, page).await;
let action_row = build_action_row(page, queue.len() / TRACKS_PER_PAGE);
let interaction_response_data = InteractionResponseDataBuilder::new()
.embeds(embeds)
.components(action_row)
.build();
let response = InteractionResponse {
kind: InteractionResponseType::UpdateMessage,
data: Some(interaction_response_data),
};
self.state
.http
.interaction(interaction.application_id)
.create_response(interaction.id, &interaction.token, &response)
.await?;
Ok(())
} else {
Ok(())
}
}
_ => Ok(()),
async fn handle_interaction(&self, event: &Event) -> anyhow::Result<()> {
match event {
Event::InteractionCreate(interaction) => match &interaction.data {
Some(InteractionData::ApplicationCommand(command)) => {
self.handle_application_command(command.clone().into(), interaction.clone())
}
Some(InteractionData::MessageComponent(data)) => {
self.handle_message_component(data, interaction.clone())
.await
}
_ => Ok(()),
},
_ => Ok(()),
}
}
fn handle_application_command(
&self,
command: InteractionCommand,
interaction: Box<InteractionCreate>,
) -> anyhow::Result<()> {
{
match command {
InteractionCommand::Play(query) => {
spawn(play(interaction, Arc::clone(&self.state), query))
}
InteractionCommand::Stop => spawn(stop(interaction, Arc::clone(&self.state))),
InteractionCommand::Pause => spawn(pause(interaction, Arc::clone(&self.state))),
InteractionCommand::Skip => spawn(skip(interaction, Arc::clone(&self.state))),
InteractionCommand::Loop => spawn(loop_queue(interaction, Arc::clone(&self.state))),
InteractionCommand::Resume => spawn(resume(interaction, Arc::clone(&self.state))),
InteractionCommand::Leave => spawn(leave(interaction, Arc::clone(&self.state))),
InteractionCommand::Join => spawn(join(interaction, Arc::clone(&self.state))),
InteractionCommand::Queue => spawn(queue(interaction, Arc::clone(&self.state))),
_ => {}
}
event => {
tracing::info!("unhandled event: {:?}", event);
Ok(())
Ok(())
}
}
async fn handle_message_component(
&self,
data: &MessageComponentInteractionData,
interaction: Box<InteractionCreate>,
) -> anyhow::Result<()> {
if !data.custom_id.starts_with("page:") {
return Ok(());
}
let page = data
.custom_id
.trim_start_matches("page:")
.parse::<usize>()
.unwrap_or(0);
if let Some(guild_id) = interaction.guild_id {
let mut queue = Vec::new();
if let Some(call_lock) = self.state.songbird.get(guild_id) {
let call = call_lock.lock().await;
queue = call.queue().current_queue();
}
let n_pages = (queue.len() + TRACKS_PER_PAGE - 1) / TRACKS_PER_PAGE;
let page = page.min(n_pages - 1).max(0);
let embeds = build_queue_embeds(&queue, page).await;
let action_row = build_action_row(page, n_pages);
let interaction_response_data = InteractionResponseDataBuilder::new()
.embeds(embeds)
.components(action_row)
.build();
let response = InteractionResponse {
kind: InteractionResponseType::UpdateMessage,
data: Some(interaction_response_data),
};
self.state
.http
.interaction(interaction.application_id)
.create_response(interaction.id, &interaction.token, &response)
.await?;
Ok(())
} else {
Ok(())
}
}
}
fn parse_interaction_command(command: &CommandData) -> InteractionCommand {
debug!("command: {:?}", command);
match command.name.as_str() {
"play" => {
if let Some(query_option) = command.options.iter().find(|opt| opt.name == "query") {
if let CommandOptionValue::String(query) = &query_option.value {
InteractionCommand::Play(query.clone())
} else {
InteractionCommand::NotImplemented
}
} else {
InteractionCommand::NotImplemented
}
}
"stop" => InteractionCommand::Stop,
"pause" => InteractionCommand::Pause,
"skip" => InteractionCommand::Skip,
"loop" => InteractionCommand::Loop,
"resume" => InteractionCommand::Resume,
"leave" => InteractionCommand::Leave,
"join" => InteractionCommand::Join,
"queue" => InteractionCommand::Queue,
_ => InteractionCommand::NotImplemented,
}
}

View File

@@ -0,0 +1,44 @@
use twilight_model::application::interaction::application_command::{
CommandData, CommandOptionValue,
};
#[derive(Debug)]
pub(crate) enum InteractionCommand {
Play(String),
Stop,
Pause,
Skip,
Loop,
Resume,
Leave,
Join,
Queue,
NotImplemented,
}
impl From<Box<CommandData>> for InteractionCommand {
fn from(command: Box<CommandData>) -> InteractionCommand {
match command.name.as_str() {
"play" => {
if let Some(query_option) = command.options.iter().find(|opt| opt.name == "query") {
if let CommandOptionValue::String(query) = &query_option.value {
InteractionCommand::Play(query.clone())
} else {
InteractionCommand::NotImplemented
}
} else {
InteractionCommand::NotImplemented
}
}
"stop" => InteractionCommand::Stop,
"pause" => InteractionCommand::Pause,
"skip" => InteractionCommand::Skip,
"loop" => InteractionCommand::Loop,
"resume" => InteractionCommand::Resume,
"leave" => InteractionCommand::Leave,
"join" => InteractionCommand::Join,
"queue" => InteractionCommand::Queue,
_ => InteractionCommand::NotImplemented,
}
}
}

View File

@@ -1,10 +1,14 @@
mod handler;
use handler::Handler;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
mod colors;
mod commands;
mod db;
mod interaction_commands;
mod metadata;
mod signal;
mod state;
mod utils;
use crate::commands::get_chat_commands;
use dotenv::dotenv;
@@ -12,7 +16,7 @@ use futures::StreamExt;
use signal::signal_handler;
use songbird::{shards::TwilightMap, Songbird};
use state::StateRef;
use std::{env, error::Error, sync::Arc};
use std::{env, error::Error, str::FromStr, sync::Arc};
use tokio::select;
use tracing::{debug, info};
use twilight_cache_inmemory::InMemoryCache;
@@ -36,6 +40,16 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
info!("Starting up...");
let (mut shards, state) = {
let db = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let options = SqliteConnectOptions::from_str(&db)
.expect("could not create options")
.create_if_missing(true);
let pool = SqlitePoolOptions::new()
.max_connections(5)
.connect_with(options)
.await?;
sqlx::migrate!().run(&pool).await?;
let token = env::var("DISCORD_TOKEN").map_err(|_| "DISCORD_TOKEN is not set")?;
let app_id = env::var("DISCORD_APP_ID")
.map_err(|_| "DISCORD_APP_ID is not set")?
@@ -78,6 +92,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
songbird,
standby: Standby::new(),
guild_settings: Default::default(),
pool,
}),
)
};

View File

@@ -13,6 +13,18 @@ pub(crate) struct Settings {
pub(crate) loop_queue: bool,
}
impl Settings {
pub(crate) fn new() -> Self {
Self { loop_queue: false }
}
}
impl Default for Settings {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub(crate) struct StateRef {
pub(crate) http: HttpClient,
@@ -20,4 +32,5 @@ pub(crate) struct StateRef {
pub(crate) songbird: Songbird,
pub(crate) standby: Standby,
pub(crate) guild_settings: DashMap<Id<GuildMarker>, Settings>,
pub(crate) pool: sqlx::SqlitePool,
}

12
src/utils.rs Normal file
View File

@@ -0,0 +1,12 @@
use futures::Future;
use std::error::Error;
pub(crate) fn spawn(
fut: impl Future<Output = Result<(), Box<dyn Error + Send + Sync + 'static>>> + Send + 'static,
) {
tokio::spawn(async move {
if let Err(why) = fut.await {
tracing::debug!("handler error: {:?}", why);
}
});
}