Compare commits

...

5 Commits

Author SHA1 Message Date
febef5ad29 comeonnnnn
All checks were successful
Build and push Docker image / build (push) Successful in 8m8s
Build and push Docker image / deploy (push) Successful in 41s
2024-12-02 08:46:09 -05:00
95c4544232 Getting eepy now...
Some checks failed
Build and push Docker image / build (push) Failing after 17s
Build and push Docker image / deploy (push) Has been skipped
2024-12-03 00:43:08 +11:00
863d4b44ea Uhh..
Some checks failed
Build and push Docker image / build (push) Failing after 3s
Build and push Docker image / deploy (push) Has been skipped
2024-12-03 00:38:12 +11:00
0a94cb5938 Update workflow
Some checks failed
Build and push Docker image / build (push) Failing after 3s
Build and push Docker image / deploy (push) Has been skipped
2024-12-03 00:32:14 +11:00
28b8940609 Bring over the rustfmt stuff
Some checks failed
Build and push Docker image / build (push) Failing after 1m27s
Build and push Docker image / deploy (push) Has been skipped
2024-12-03 00:17:58 +11:00
24 changed files with 726 additions and 573 deletions

View File

@ -17,10 +17,10 @@ jobs:
steps: steps:
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@988b5a0280414f521da01fcc63a27aeeb4b104db # v3.6.1 uses: docker/setup-buildx-action@v3
- name: Checkout - name: Checkout
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 uses: actions/checkout@v4
- name: Install zstd - name: Install zstd
run: sudo apt-get update && sudo apt-get install -y zstd run: sudo apt-get update && sudo apt-get install -y zstd
@ -32,7 +32,7 @@ jobs:
cat hash.txt cat hash.txt
- name: Cache - name: Cache
uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 uses: actions/cache@v4
id: cache id: cache
with: with:
save-always: true save-always: true
@ -45,16 +45,15 @@ jobs:
key: ${{ runner.os }}-cache-${{ steps.cargo-cache-key.outputs.hash }} key: ${{ runner.os }}-cache-${{ steps.cargo-cache-key.outputs.hash }}
- name: Login to Gitea - name: Login to Gitea
uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0 uses: docker/login-action@v3
with: with:
registry: git.toast-server.net registry: git.toast-server.net
username: ${{ secrets.DOCKER_USERNAME }} username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }} password: ${{ secrets.DOCKER_TOKEN }}
- name: Set up Rust toolchain - name: Set up Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@1fbea72663f6d4c03efaab13560c8a24cfd2a7cc # v1.9.0 uses: actions-rust-lang/setup-rust-toolchain@v1
with: with:
toolchain: stable
rustflags: -C target-feature=-crt-static rustflags: -C target-feature=-crt-static
- name: Install zigbuild - name: Install zigbuild
@ -70,7 +69,7 @@ jobs:
cargo zigbuild --target x86_64-unknown-linux-musl --locked -rF production cargo zigbuild --target x86_64-unknown-linux-musl --locked -rF production
- name: Build and push image - name: Build and push image
uses: docker/build-push-action@5cd11c3a4ced054e52742c5fd54dca954e0edd85 # v6.7.0 uses: docker/build-push-action@v6
with: with:
context: . context: .
platforms: linux/amd64 platforms: linux/amd64
@ -85,7 +84,7 @@ jobs:
needs: build needs: build
steps: steps:
- name: Deploy update - name: Deploy update
uses: appleboy/ssh-action@d732991ab09097d8c8f390d91385b0386e619598 # v1.0.3 uses: appleboy/ssh-action@v1.2.0
with: with:
host: ${{ secrets.SSH_HOST }} host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USERNAME }} username: ${{ secrets.SSH_USERNAME }}

231
Cargo.lock generated
View File

@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 4
[[package]] [[package]]
name = "addr2line" name = "addr2line"
@ -64,7 +64,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -170,9 +170,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]] [[package]]
name = "bytes" name = "bytes"
version = "1.8.0" version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" checksum = "325918d6fe32f23b19878fe4b34794ae41fc19ddbe53b10571a4874d44ffd39b"
[[package]] [[package]]
name = "camino" name = "camino"
@ -185,9 +185,9 @@ dependencies = [
[[package]] [[package]]
name = "cargo-platform" name = "cargo-platform"
version = "0.1.8" version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc" checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"
dependencies = [ dependencies = [
"serde", "serde",
] ]
@ -217,9 +217,9 @@ dependencies = [
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.1" version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc"
dependencies = [ dependencies = [
"shlex", "shlex",
] ]
@ -277,9 +277,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.2.15" version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ca741a962e1b0bff6d724a1a0958b686406e853bb14061f218562e1896f95e6" checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3"
dependencies = [ dependencies = [
"libc", "libc",
] ]
@ -358,7 +358,7 @@ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"strsim", "strsim",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -369,7 +369,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"
dependencies = [ dependencies = [
"darling_core", "darling_core",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -431,7 +431,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -458,7 +458,7 @@ dependencies = [
"heck", "heck",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -469,12 +469,12 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]] [[package]]
name = "errno" name = "errno"
version = "0.3.9" version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"
dependencies = [ dependencies = [
"libc", "libc",
"windows-sys 0.52.0", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -593,7 +593,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -689,9 +689,9 @@ dependencies = [
[[package]] [[package]]
name = "h2" name = "h2"
version = "0.4.6" version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" checksum = "ccae279728d634d083c00f6099cb58f01cc99c145b84b8be2f6c74618d79922e"
dependencies = [ dependencies = [
"atomic-waker", "atomic-waker",
"bytes", "bytes",
@ -714,9 +714,9 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.15.1" version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a9bfc1af68b1726ea47d3d5109de126281def866b33970e10fbab11b5dafab3" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
[[package]] [[package]]
name = "heck" name = "heck"
@ -724,12 +724,6 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
[[package]] [[package]]
name = "hostname" name = "hostname"
version = "0.3.1" version = "0.3.1"
@ -835,14 +829,14 @@ dependencies = [
[[package]] [[package]]
name = "hyper" name = "hyper"
version = "1.5.0" version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbbff0a806a4728c99295b254c8838933b5b082d75e3cb70c8dab21fdfbcfa9a" checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-channel", "futures-channel",
"futures-util", "futures-util",
"h2 0.4.6", "h2 0.4.7",
"http 1.1.0", "http 1.1.0",
"http-body 1.0.1", "http-body 1.0.1",
"httparse", "httparse",
@ -875,9 +869,9 @@ checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333"
dependencies = [ dependencies = [
"futures-util", "futures-util",
"http 1.1.0", "http 1.1.0",
"hyper 1.5.0", "hyper 1.5.1",
"hyper-util", "hyper-util",
"rustls 0.23.17", "rustls 0.23.19",
"rustls-pki-types", "rustls-pki-types",
"tokio", "tokio",
"tokio-rustls 0.26.0", "tokio-rustls 0.26.0",
@ -892,7 +886,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
dependencies = [ dependencies = [
"bytes", "bytes",
"http-body-util", "http-body-util",
"hyper 1.5.0", "hyper 1.5.1",
"hyper-util", "hyper-util",
"native-tls", "native-tls",
"tokio", "tokio",
@ -911,7 +905,7 @@ dependencies = [
"futures-util", "futures-util",
"http 1.1.0", "http 1.1.0",
"http-body 1.0.1", "http-body 1.0.1",
"hyper 1.5.0", "hyper 1.5.1",
"pin-project-lite", "pin-project-lite",
"socket2", "socket2",
"tokio", "tokio",
@ -1057,7 +1051,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -1099,12 +1093,12 @@ dependencies = [
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.6.0" version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown 0.15.1", "hashbrown 0.15.2",
] ]
[[package]] [[package]]
@ -1127,22 +1121,23 @@ checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708"
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.11" version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674"
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.72" version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" checksum = "a865e038f7f6ed956f788f0d7d60c541fff74c7bd74272c5d4cf15c63743e705"
dependencies = [ dependencies = [
"once_cell",
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]] [[package]]
name = "kon" name = "kon"
version = "0.5.0" version = "0.5.1"
dependencies = [ dependencies = [
"bb8", "bb8",
"bb8-redis", "bb8-redis",
@ -1162,9 +1157,9 @@ dependencies = [
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.164" version = "0.2.167"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "433bfe06b8c75da9b2e3fbea6e5329ff87748f0b144ef75306e674c3f6f7c13f" checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc"
[[package]] [[package]]
name = "linked-hash-map" name = "linked-hash-map"
@ -1180,9 +1175,9 @@ checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
[[package]] [[package]]
name = "litemap" name = "litemap"
version = "0.7.3" version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104"
[[package]] [[package]]
name = "lock_api" name = "lock_api"
@ -1272,11 +1267,10 @@ dependencies = [
[[package]] [[package]]
name = "mio" name = "mio"
version = "1.0.2" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd"
dependencies = [ dependencies = [
"hermit-abi",
"libc", "libc",
"wasi", "wasi",
"windows-sys 0.52.0", "windows-sys 0.52.0",
@ -1380,7 +1374,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -1484,7 +1478,7 @@ dependencies = [
"darling", "darling",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -1504,9 +1498,9 @@ dependencies = [
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.89" version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
@ -1711,11 +1705,11 @@ dependencies = [
"encoding_rs", "encoding_rs",
"futures-core", "futures-core",
"futures-util", "futures-util",
"h2 0.4.6", "h2 0.4.7",
"http 1.1.0", "http 1.1.0",
"http-body 1.0.1", "http-body 1.0.1",
"http-body-util", "http-body-util",
"hyper 1.5.0", "hyper 1.5.1",
"hyper-rustls 0.27.3", "hyper-rustls 0.27.3",
"hyper-tls", "hyper-tls",
"hyper-util", "hyper-util",
@ -1731,7 +1725,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
"sync_wrapper 1.0.1", "sync_wrapper 1.0.2",
"system-configuration 0.6.1", "system-configuration 0.6.1",
"tokio", "tokio",
"tokio-native-tls", "tokio-native-tls",
@ -1815,9 +1809,9 @@ dependencies = [
[[package]] [[package]]
name = "rustls" name = "rustls"
version = "0.23.17" version = "0.23.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f1a745511c54ba6d4465e8d5dfbd81b45791756de28d4981af70d6dca128f1e" checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"rustls-pki-types", "rustls-pki-types",
@ -1979,7 +1973,7 @@ checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -2112,9 +2106,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]] [[package]]
name = "socket2" name = "socket2"
version = "0.5.7" version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8"
dependencies = [ dependencies = [
"libc", "libc",
"windows-sys 0.52.0", "windows-sys 0.52.0",
@ -2157,9 +2151,9 @@ dependencies = [
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.87" version = "2.0.90"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -2174,9 +2168,9 @@ checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160"
[[package]] [[package]]
name = "sync_wrapper" name = "sync_wrapper"
version = "1.0.1" version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
dependencies = [ dependencies = [
"futures-core", "futures-core",
] ]
@ -2189,14 +2183,14 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
name = "sysinfo" name = "sysinfo"
version = "0.32.0" version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3b5ae3f4f7d64646c46c4cae4e3f01d1c5d255c7406fdd7c7f999a94e488791" checksum = "4c33cd241af0f2e9e3b5c32163b873b29956890b5342e6745b917ce9d490f4af"
dependencies = [ dependencies = [
"core-foundation-sys", "core-foundation-sys",
"libc", "libc",
@ -2284,7 +2278,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -2382,7 +2376,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -2422,7 +2416,7 @@ version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4"
dependencies = [ dependencies = [
"rustls 0.23.17", "rustls 0.23.19",
"rustls-pki-types", "rustls-pki-types",
"tokio", "tokio",
] ]
@ -2440,7 +2434,7 @@ dependencies = [
"tokio", "tokio",
"tokio-rustls 0.25.0", "tokio-rustls 0.25.0",
"tungstenite", "tungstenite",
"webpki-roots 0.26.6", "webpki-roots 0.26.7",
] ]
[[package]] [[package]]
@ -2498,9 +2492,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.40" version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
dependencies = [ dependencies = [
"log", "log",
"pin-project-lite", "pin-project-lite",
@ -2510,20 +2504,20 @@ dependencies = [
[[package]] [[package]]
name = "tracing-attributes" name = "tracing-attributes"
version = "0.1.27" version = "0.1.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
name = "tracing-core" name = "tracing-core"
version = "0.1.32" version = "0.1.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c"
dependencies = [ dependencies = [
"once_cell", "once_cell",
] ]
@ -2651,7 +2645,7 @@ checksum = "fd9fc0ad9e03a2b0c2e2a0eafaecccef2121829e1ab6ce9c9d790e6c6766bd1c"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -2668,9 +2662,9 @@ checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.13" version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
[[package]] [[package]]
name = "unicode-normalization" name = "unicode-normalization"
@ -2700,9 +2694,9 @@ dependencies = [
[[package]] [[package]]
name = "url" name = "url"
version = "2.5.3" version = "2.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d157f1b96d14500ffdc1f10ba712e780825526c03d9a49b4d0324b0d9113ada" checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60"
dependencies = [ dependencies = [
"form_urlencoded", "form_urlencoded",
"idna 1.0.3", "idna 1.0.3",
@ -2776,9 +2770,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.95" version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" checksum = "d15e63b4482863c109d70a7b8706c1e364eb6ea449b201a76c5b89cedcec2d5c"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"once_cell", "once_cell",
@ -2787,36 +2781,37 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.95" version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" checksum = "8d36ef12e3aaca16ddd3f67922bc63e48e953f126de60bd33ccc0101ef9998cd"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"log", "log",
"once_cell", "once_cell",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
[[package]] [[package]]
name = "wasm-bindgen-futures" name = "wasm-bindgen-futures"
version = "0.4.45" version = "0.4.47"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7ec4f8827a71586374db3e87abdb5a2bb3a15afed140221307c3ec06b1f63b" checksum = "9dfaf8f50e5f293737ee323940c7d8b08a66a95a419223d9f41610ca08b0833d"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys", "js-sys",
"once_cell",
"wasm-bindgen", "wasm-bindgen",
"web-sys", "web-sys",
] ]
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.95" version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" checksum = "705440e08b42d3e4b36de7d66c944be628d579796b8090bfa3471478a2260051"
dependencies = [ dependencies = [
"quote", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@ -2824,22 +2819,22 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.95" version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" checksum = "98c9ae5a76e46f4deecd0f0255cc223cfa18dc9b261213b8aa0c7b36f61b3f1d"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
"wasm-bindgen-backend", "wasm-bindgen-backend",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.95" version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49"
[[package]] [[package]]
name = "wasm-streams" name = "wasm-streams"
@ -2856,9 +2851,9 @@ dependencies = [
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.72" version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" checksum = "a98bc3c33f0fe7e59ad7cd041b89034fa82a7c2d4365ca538dda6cdaf513863c"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",
@ -2872,9 +2867,9 @@ checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1"
[[package]] [[package]]
name = "webpki-roots" name = "webpki-roots"
version = "0.26.6" version = "0.26.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841c67bff177718f1d4dfefde8d8f0e78f9b6589319ba88312f567fc5841a958" checksum = "5d642ff16b7e79272ae451b7322067cdc17cadf68c23264be9d94a32319efe7e"
dependencies = [ dependencies = [
"rustls-pki-types", "rustls-pki-types",
] ]
@ -2955,7 +2950,7 @@ checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -2966,7 +2961,7 @@ checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
@ -3189,9 +3184,9 @@ checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51"
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.7.4" version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40"
dependencies = [ dependencies = [
"serde", "serde",
"stable_deref_trait", "stable_deref_trait",
@ -3201,13 +3196,13 @@ dependencies = [
[[package]] [[package]]
name = "yoke-derive" name = "yoke-derive"
version = "0.7.4" version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
"synstructure", "synstructure",
] ]
@ -3229,27 +3224,27 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]
[[package]] [[package]]
name = "zerofrom" name = "zerofrom"
version = "0.1.4" version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" checksum = "cff3ee08c995dee1859d998dea82f7374f2826091dd9cd47def953cae446cd2e"
dependencies = [ dependencies = [
"zerofrom-derive", "zerofrom-derive",
] ]
[[package]] [[package]]
name = "zerofrom-derive" name = "zerofrom-derive"
version = "0.1.4" version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
"synstructure", "synstructure",
] ]
@ -3278,5 +3273,5 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.90",
] ]

View File

@ -1,7 +1,7 @@
[package] [package]
name = "kon" name = "kon"
version = "0.5.0" version = "0.5.1"
edition = "2021" edition = "2024"
[dependencies] [dependencies]
bb8 = "0.8.6" bb8 = "0.8.6"
@ -14,8 +14,8 @@ regex = "1.11.1"
reqwest = { version = "0.12.9", features = ["json", "native-tls-vendored"] } reqwest = { version = "0.12.9", features = ["json", "native-tls-vendored"] }
serde = "1.0.215" serde = "1.0.215"
serde_json = "1.0.133" serde_json = "1.0.133"
sysinfo = "0.32.0" sysinfo = "0.32.1"
tokenservice-client = { version = "0.4.0", registry = "gitea" } tokenservice-client = { version = "0.4.1", registry = "gitea" }
tokio = { version = "1.41.1", features = ["macros", "signal", "rt-multi-thread"] } tokio = { version = "1.41.1", features = ["macros", "signal", "rt-multi-thread"] }
uptime_lib = "0.3.1" uptime_lib = "0.3.1"

2
run.sh
View File

@ -1,3 +1,3 @@
#!/bin/bash #!/bin/bash
clear && cargo run kon_dev clear && cargo fmt && cargo run kon_dev

2
rust-toolchain Normal file
View File

@ -0,0 +1,2 @@
[toolchain]
channel = "nightly"

20
rustfmt.toml Normal file
View File

@ -0,0 +1,20 @@
edition = "2024"
hex_literal_case = "Upper"
binop_separator = "Front"
brace_style = "SameLineWhere"
fn_params_layout = "Vertical"
imports_layout = "Vertical"
imports_granularity = "One"
fn_single_line = true
format_strings = true
max_width = 150
tab_spaces = 2
hard_tabs = false
trailing_comma = "Never"
match_block_trailing_comma = true
reorder_imports = true
reorder_modules = true
reorder_impl_items = true
trailing_semicolon = false
struct_field_align_threshold = 20
condense_wildcard_suffixes = true

View File

@ -9,11 +9,7 @@ pub mod uptime;
type PoiseCtx<'a> = poise::Context<'a, (), Error>; type PoiseCtx<'a> = poise::Context<'a, (), Error>;
/// Deploy the commands globally or in a guild /// Deploy the commands globally or in a guild
#[poise::command( #[poise::command(prefix_command, owners_only, guild_only)]
prefix_command,
owners_only,
guild_only
)]
pub async fn deploy(ctx: PoiseCtx<'_>) -> Result<(), Error> { pub async fn deploy(ctx: PoiseCtx<'_>) -> Result<(), Error> {
poise::builtins::register_application_commands_buttons(ctx).await?; poise::builtins::register_application_commands_buttons(ctx).await?;
Ok(()) Ok(())

View File

@ -6,20 +6,22 @@ use crate::{
} }
}; };
use reqwest::{ use {
ClientBuilder, poise::{
Error as ReqError
};
use serde::{
Serialize,
Deserialize
};
use poise::{
CreateReply, CreateReply,
serenity_prelude::{ serenity_prelude::{
CreateEmbed, CreateEmbed,
Timestamp Timestamp
} }
},
reqwest::{
ClientBuilder,
Error as ReqError
},
serde::{
Deserialize,
Serialize
}
}; };
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -37,7 +39,7 @@ struct Fan {
#[serde(rename = "FanName")] #[serde(rename = "FanName")]
fan_name: String, fan_name: String,
#[serde(rename = "Status")] #[serde(rename = "Status")]
status: Status, status: Status
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -153,10 +155,7 @@ impl RedfishEndpoint {
} }
async fn ilo_data(endpoint: RedfishEndpoint) -> Result<Box<dyn std::any::Any + Send>, ReqError> { async fn ilo_data(endpoint: RedfishEndpoint) -> Result<Box<dyn std::any::Any + Send>, ReqError> {
let client = ClientBuilder::new() let client = ClientBuilder::new().danger_accept_invalid_certs(true).build().unwrap();
.danger_accept_invalid_certs(true)
.build()
.unwrap();
let res = client let res = client
.get(format!("https://{}/redfish/v1/{}", token_path().await.ilo_ip, endpoint.url())) .get(format!("https://{}/redfish/v1/{}", token_path().await.ilo_ip, endpoint.url()))
.basic_auth(token_path().await.ilo_user, Some(token_path().await.ilo_pw)) .basic_auth(token_path().await.ilo_user, Some(token_path().await.ilo_pw))
@ -168,15 +167,15 @@ async fn ilo_data(endpoint: RedfishEndpoint) -> Result<Box<dyn std::any::Any + S
RedfishEndpoint::Thermal => { RedfishEndpoint::Thermal => {
let body: Chassis = res.json().await.unwrap(); let body: Chassis = res.json().await.unwrap();
Ok(Box::new(body)) Ok(Box::new(body))
} },
RedfishEndpoint::Power => { RedfishEndpoint::Power => {
let body: Power = res.json().await.unwrap(); let body: Power = res.json().await.unwrap();
Ok(Box::new(body)) Ok(Box::new(body))
} },
RedfishEndpoint::System => { RedfishEndpoint::System => {
let body: System = res.json().await.unwrap(); let body: System = res.json().await.unwrap();
Ok(Box::new(body)) Ok(Box::new(body))
} },
RedfishEndpoint::EventService => { RedfishEndpoint::EventService => {
let body: Event = res.json().await.unwrap(); let body: Event = res.json().await.unwrap();
Ok(Box::new(body)) Ok(Box::new(body))
@ -191,9 +190,7 @@ async fn ilo_data(endpoint: RedfishEndpoint) -> Result<Box<dyn std::any::Any + S
interaction_context = "Guild|BotDm|PrivateChannel", interaction_context = "Guild|BotDm|PrivateChannel",
subcommands("temperature", "power", "system") subcommands("temperature", "power", "system")
)] )]
pub async fn ilo(_: super::PoiseCtx<'_>) -> Result<(), Error> { pub async fn ilo(_: super::PoiseCtx<'_>) -> Result<(), Error> { Ok(()) }
Ok(())
}
/// Retrieve the server's temperature data /// Retrieve the server's temperature data
#[poise::command(slash_command)] #[poise::command(slash_command)]
@ -204,11 +201,7 @@ pub async fn temperature(ctx: super::PoiseCtx<'_>) -> Result<(), Error> {
let mut tempdata = String::new(); let mut tempdata = String::new();
let mut fandata = String::new(); let mut fandata = String::new();
let allowed_sensors = [ let allowed_sensors = ["01-Inlet Ambient", "04-P1 DIMM 1-6", "14-Chipset Zone"];
"01-Inlet Ambient",
"04-P1 DIMM 1-6",
"14-Chipset Zone"
];
for temp in &data.temperatures { for temp in &data.temperatures {
if temp.reading_celsius == 0 || !allowed_sensors.contains(&temp.name.as_str()) { if temp.reading_celsius == 0 || !allowed_sensors.contains(&temp.name.as_str()) {
@ -232,16 +225,17 @@ pub async fn temperature(ctx: super::PoiseCtx<'_>) -> Result<(), Error> {
fandata.push_str(&format!("**{}:** `{}%`\n", fan.fan_name, fan.current_reading)); fandata.push_str(&format!("**{}:** `{}%`\n", fan.fan_name, fan.current_reading));
} }
ctx.send(CreateReply::default().embed( ctx
.send(
CreateReply::default().embed(
CreateEmbed::new() CreateEmbed::new()
.color(BINARY_PROPERTIES.embed_color) .color(BINARY_PROPERTIES.embed_color)
.timestamp(Timestamp::now()) .timestamp(Timestamp::now())
.title(format!("{} - Temperatures", ILO_HOSTNAME)) .title(format!("{} - Temperatures", ILO_HOSTNAME))
.fields(vec![ .fields(vec![("Temperatures", tempdata, false), ("Fans", fandata, false)])
("Temperatures", tempdata, false), )
("Fans", fandata, false) )
]) .await?;
)).await?;
Ok(()) Ok(())
} }
@ -261,13 +255,17 @@ pub async fn power(ctx: super::PoiseCtx<'_>) -> Result<(), Error> {
powerdata.push_str(&format!("**Max Consumed:** `{}w`\n", &data.power_metrics.max_consumed_watts)); powerdata.push_str(&format!("**Max Consumed:** `{}w`\n", &data.power_metrics.max_consumed_watts));
powerdata.push_str(&format!("**Min Consumed:** `{}w`", &data.power_metrics.min_consumed_watts)); powerdata.push_str(&format!("**Min Consumed:** `{}w`", &data.power_metrics.min_consumed_watts));
ctx.send(CreateReply::default().embed( ctx
.send(
CreateReply::default().embed(
CreateEmbed::new() CreateEmbed::new()
.color(BINARY_PROPERTIES.embed_color) .color(BINARY_PROPERTIES.embed_color)
.timestamp(Timestamp::now()) .timestamp(Timestamp::now())
.title(format!("{} - Power", ILO_HOSTNAME)) .title(format!("{} - Power", ILO_HOSTNAME))
.description(powerdata) .description(powerdata)
)).await?; )
)
.await?;
Ok(()) Ok(())
} }
@ -277,10 +275,7 @@ pub async fn power(ctx: super::PoiseCtx<'_>) -> Result<(), Error> {
pub async fn system(ctx: super::PoiseCtx<'_>) -> Result<(), Error> { pub async fn system(ctx: super::PoiseCtx<'_>) -> Result<(), Error> {
ctx.defer().await?; ctx.defer().await?;
let (ilo_sys, ilo_event) = tokio::join!( let (ilo_sys, ilo_event) = tokio::join!(ilo_data(RedfishEndpoint::System), ilo_data(RedfishEndpoint::EventService));
ilo_data(RedfishEndpoint::System),
ilo_data(RedfishEndpoint::EventService)
);
let ilo_sys = ilo_sys.unwrap(); let ilo_sys = ilo_sys.unwrap();
let ilo_event = ilo_event.unwrap(); let ilo_event = ilo_event.unwrap();
@ -300,22 +295,33 @@ pub async fn system(ctx: super::PoiseCtx<'_>) -> Result<(), Error> {
println!("iLO:PostState = {}", system_data.oem.hp.post_state); println!("iLO:PostState = {}", system_data.oem.hp.post_state);
} }
data.push_str(&format!("**Health:** `{}`\n", event_data.status.health.as_ref().unwrap_or(&"Unknown".to_string()))); data.push_str(&format!(
"**Health:** `{}`\n",
event_data.status.health.as_ref().unwrap_or(&"Unknown".to_string())
));
data.push_str(&format!("**POST:** `{}`\n", post_state)); data.push_str(&format!("**POST:** `{}`\n", post_state));
data.push_str(&format!("**Power:** `{}`\n", &system_data.power_state)); data.push_str(&format!("**Power:** `{}`\n", &system_data.power_state));
data.push_str(&format!("**Model:** `{}`", &system_data.model)); data.push_str(&format!("**Model:** `{}`", &system_data.model));
ctx.send(CreateReply::default().embed( ctx
.send(
CreateReply::default().embed(
CreateEmbed::new() CreateEmbed::new()
.color(BINARY_PROPERTIES.embed_color) .color(BINARY_PROPERTIES.embed_color)
.timestamp(Timestamp::now()) .timestamp(Timestamp::now())
.title(format!("{} - System", ILO_HOSTNAME)) .title(format!("{} - System", ILO_HOSTNAME))
.description(data) .description(data)
.fields(vec![ .fields(vec![
(format!("CPU ({}x)", system_data.processor_summary.count), system_data.processor_summary.cpu.trim().to_string(), true), (
("RAM".to_string(), format!("{} GB", system_data.memory.total_system_memory), true) format!("CPU ({}x)", system_data.processor_summary.count),
system_data.processor_summary.cpu.trim().to_string(),
true
),
("RAM".to_string(), format!("{} GB", system_data.memory.total_system_memory), true),
]) ])
)).await?; )
)
.await?;
Ok(()) Ok(())
} }

View File

@ -1,30 +1,32 @@
use crate::{ use crate::{
Error, Error,
internals::utils::{ internals::utils::{
mention_dev, format_bytes,
format_bytes mention_dev
} }
}; };
use regex::Regex; use {
use std::{ poise::{
os::unix::fs::MetadataExt,
fs::{
write,
remove_file,
metadata
}
};
use poise::{
CreateReply, CreateReply,
serenity_prelude::CreateAttachment serenity_prelude::CreateAttachment
},
regex::Regex,
std::{
fs::{
metadata,
remove_file,
write
},
os::unix::fs::MetadataExt
}
}; };
/// Convert MIDI file to WAV /// Convert MIDI file to WAV
#[poise::command( #[poise::command(
context_menu_command = "MIDI -> WAV", context_menu_command = "MIDI -> WAV",
install_context = "User", install_context = "User",
interaction_context = "Guild|BotDm|PrivateChannel", interaction_context = "Guild|BotDm|PrivateChannel"
)] )]
pub async fn midi_to_wav( pub async fn midi_to_wav(
ctx: super::PoiseCtx<'_>, ctx: super::PoiseCtx<'_>,
@ -42,13 +44,13 @@ pub async fn midi_to_wav(
let bytes = match message.attachments[0].download().await { let bytes = match message.attachments[0].download().await {
Ok(bytes) => bytes, Ok(bytes) => bytes,
Err(y) => { Err(y) => {
ctx.send(CreateReply::default() ctx
.content(format!( .send(CreateReply::default().content(format!(
"Download failed, ask {} to check console for more information!", "Download failed, ask {} to check console for more information!",
mention_dev(ctx).unwrap_or_default() mention_dev(ctx).unwrap_or_default()
)) )))
) .await
.await.unwrap(); .unwrap();
return Err(Error::from(format!("Failed to download the file: {y}"))) return Err(Error::from(format!("Failed to download the file: {y}")))
} }
@ -71,9 +73,9 @@ pub async fn midi_to_wav(
match output { match output {
Ok(_) => { Ok(_) => {
let reply = ctx.send(CreateReply::default() let reply = ctx
.attachment(CreateAttachment::path(&*wav_path).await.unwrap()) .send(CreateReply::default().attachment(CreateAttachment::path(&*wav_path).await.unwrap()))
).await; .await;
if reply.is_err() { if reply.is_err() {
println!( println!(
@ -81,21 +83,24 @@ pub async fn midi_to_wav(
ctx.command().qualified_name ctx.command().qualified_name
); );
ctx.send(CreateReply::default() ctx
.content(format!( .send(CreateReply::default().content(format!(
"Couldn't upload the processed file (`{}`, `{}`) due to upload limit", "Couldn't upload the processed file (`{}`, `{}`) due to upload limit",
&*wav_path, format_bytes(metadata(&*wav_path).unwrap().size()) &*wav_path,
)) format_bytes(metadata(&*wav_path).unwrap().size())
).await.unwrap(); )))
.await
.unwrap();
} else if reply.is_ok() { } else if reply.is_ok() {
remove_file(midi_path)?; remove_file(midi_path)?;
remove_file(&*wav_path)?; remove_file(&*wav_path)?;
} }
}, },
Err(y) => { Err(y) => {
ctx.send(CreateReply::default() ctx
.content("Command didn't execute successfully, check console for more information!") .send(CreateReply::default().content("Command didn't execute successfully, check console for more information!"))
).await.unwrap(); .await
.unwrap();
return Err(Error::from(format!("Midi conversion failed: {y}"))) return Err(Error::from(format!("Midi conversion failed: {y}")))
} }

View File

@ -7,12 +7,14 @@ use crate::{
} }
}; };
use serde_json::Value; use {
use std::collections::HashMap; poise::{
use tokio::join;
use poise::{
CreateReply, CreateReply,
serenity_prelude::builder::CreateEmbed serenity_prelude::builder::CreateEmbed
},
serde_json::Value,
std::collections::HashMap,
tokio::join
}; };
async fn pms_serverstatus(url: &str) -> Result<Vec<(String, Vec<Value>)>, Error> { async fn pms_serverstatus(url: &str) -> Result<Vec<(String, Vec<Value>)>, Error> {
@ -38,11 +40,10 @@ async fn pms_serverstatus(url: &str) -> Result<Vec<(String, Vec<Value>)>, Error>
fn process_pms_statuses(servers: Vec<(String, Vec<Value>)>) -> Vec<(String, String, bool)> { fn process_pms_statuses(servers: Vec<(String, Vec<Value>)>) -> Vec<(String, String, bool)> {
let mut server_map: HashMap<String, Vec<(String, String)>> = HashMap::new(); let mut server_map: HashMap<String, Vec<(String, String)>> = HashMap::new();
let id_name_map: HashMap<&str, &str> = [ let id_name_map: HashMap<&str, &str> = [("wotbsg", "ASIA"), ("wowssg", "WoWS (ASIA)"), ("wowseu", "WoWS (EU)")]
("wotbsg", "ASIA"), .iter()
("wowssg", "WoWS (ASIA)"), .cloned()
("wowseu", "WoWS (EU)") .collect();
].iter().cloned().collect();
for (title, mapped_servers) in servers { for (title, mapped_servers) in servers {
for server in mapped_servers { for server in mapped_servers {
@ -54,26 +55,28 @@ fn process_pms_statuses(servers: Vec<(String, Vec<Value>)>) -> Vec<(String, Stri
_ => "Unknown" _ => "Unknown"
}; };
let name = id_name_map.get(id).unwrap_or(&name); let name = id_name_map.get(id).unwrap_or(&name);
server_map.entry(title.clone()).or_default().push((name.to_owned().to_string(), status.to_owned())); server_map
.entry(title.clone())
.or_default()
.push((name.to_owned().to_string(), status.to_owned()));
} }
} }
let mut statuses = Vec::new(); let mut statuses = Vec::new();
for (title, servers) in server_map { for (title, servers) in server_map {
let servers_str = servers.iter().map(|(name, status)| format!("{}: {}", name, status)).collect::<Vec<String>>().join("\n"); let servers_str = servers
.iter()
.map(|(name, status)| format!("{}: {}", name, status))
.collect::<Vec<String>>()
.join("\n");
statuses.push((title, servers_str, true)); statuses.push((title, servers_str, true));
} }
statuses statuses
} }
/// Query the server statuses /// Query the server statuses
#[poise::command( #[poise::command(slash_command, subcommands("wg"))]
slash_command, pub async fn status(_: super::PoiseCtx<'_>) -> Result<(), Error> { Ok(()) }
subcommands("wg")
)]
pub async fn status(_: super::PoiseCtx<'_>) -> Result<(), Error> {
Ok(())
}
/// Retrieve the server statuses from Wargaming /// Retrieve the server statuses from Wargaming
#[poise::command(slash_command)] #[poise::command(slash_command)]
@ -86,7 +89,9 @@ pub async fn wg(ctx: super::PoiseCtx<'_>) -> Result<(), Error> {
let joined_pms_servers = [servers_eu.unwrap(), servers_asia.unwrap()].concat(); let joined_pms_servers = [servers_eu.unwrap(), servers_asia.unwrap()].concat();
let pms_servers = process_pms_statuses(joined_pms_servers.to_vec()); let pms_servers = process_pms_statuses(joined_pms_servers.to_vec());
ctx.send(CreateReply::default().embed(embed.title("Wargaming Server Status").fields(pms_servers))).await?; ctx
.send(CreateReply::default().embed(embed.title("Wargaming Server Status").fields(pms_servers)))
.await?;
Ok(()) Ok(())
} }

View File

@ -1,27 +1,29 @@
use crate::{ use crate::{
Error, Error,
GIT_COMMIT_HASH,
GIT_COMMIT_BRANCH, GIT_COMMIT_BRANCH,
GIT_COMMIT_HASH,
internals::utils::{ internals::utils::{
BOT_VERSION, BOT_VERSION,
format_duration format_duration
} }
}; };
use sysinfo::System; use {
use uptime_lib::get; std::{
use std::{
fs::File, fs::File,
io::{
BufRead,
BufReader
},
path::Path, path::Path,
time::{ time::{
Duration, Duration,
SystemTime, SystemTime,
UNIX_EPOCH UNIX_EPOCH
},
io::{
BufRead,
BufReader
} }
},
sysinfo::System,
uptime_lib::get
}; };
fn get_os_info() -> String { fn get_os_info() -> String {
@ -32,13 +34,11 @@ fn get_os_info() -> String {
if let Ok(file) = File::open(path) { if let Ok(file) = File::open(path) {
let reader = BufReader::new(file); let reader = BufReader::new(file);
let set_value = |s: String| s.split('=').nth(1).unwrap_or_default().trim_matches('"').to_string(); let set_value = |s: String| s.split('=').nth(1).unwrap_or_default().trim_matches('"').to_string();
reader.lines().map_while(Result::ok).for_each(|line| { reader.lines().map_while(Result::ok).for_each(|line| match line {
match line {
l if l.starts_with("NAME=") => name = set_value(l), l if l.starts_with("NAME=") => name = set_value(l),
l if l.starts_with("VERSION=") => version = set_value(l), l if l.starts_with("VERSION=") => version = set_value(l),
l if l.starts_with("VERSION_ID=") => version = set_value(l), l if l.starts_with("VERSION_ID=") => version = set_value(l),
_ => {} _ => {}
}
}); });
} }

View File

@ -1,16 +1,20 @@
use crate::internals::utils::token_path; use crate::internals::utils::token_path;
use bb8_redis::{ use {
bb8_redis::{
RedisConnectionManager,
bb8::Pool, bb8::Pool,
redis::cmd, redis::{
redis::RedisError, AsyncCommands,
redis::RedisResult, RedisError,
redis::AsyncCommands, RedisResult,
RedisConnectionManager cmd
}; }
use tokio::time::{ },
tokio::time::{
Duration, Duration,
sleep sleep
}
}; };
#[derive(Debug)] #[derive(Debug)]
@ -31,8 +35,7 @@ impl RedisController {
loop { loop {
match Pool::builder().max_size(20).retry_connection(true).build(manager.clone()).await { match Pool::builder().max_size(20).retry_connection(true).build(manager.clone()).await {
Ok(pool) => { Ok(pool) => match pool.get().await {
match pool.get().await {
Ok(mut conn) => { Ok(mut conn) => {
let ping: RedisResult<String> = cmd("PING").query_async(&mut *conn).await; let ping: RedisResult<String> = cmd("PING").query_async(&mut *conn).await;
match ping { match ping {
@ -41,17 +44,26 @@ impl RedisController {
return pool.clone(); return pool.clone();
}, },
Err(e) => { Err(e) => {
eprintln!("{}", redis_err.replace("{{ e }}", &e.to_string()).replace("{{ backoff }}", &backoff.to_string())); eprintln!(
"{}",
redis_err
.replace("{{ e }}", &e.to_string())
.replace("{{ backoff }}", &backoff.to_string())
);
Self::apply_backoff(&mut backoff).await; Self::apply_backoff(&mut backoff).await;
} }
} }
}, },
Err(e) => { Err(e) => {
eprintln!("{}", redis_err.replace("{{ e }}", &e.to_string()).replace("{{ backoff }}", &backoff.to_string())); eprintln!(
"{}",
redis_err
.replace("{{ e }}", &e.to_string())
.replace("{{ backoff }}", &backoff.to_string())
);
Self::apply_backoff(&mut backoff).await; Self::apply_backoff(&mut backoff).await;
} }
} },
}
Err(e) => { Err(e) => {
eprintln!("Redis[PoolError]: {e}, retrying in {backoff} seconds"); eprintln!("Redis[PoolError]: {e}, retrying in {backoff} seconds");
Self::apply_backoff(&mut backoff).await; Self::apply_backoff(&mut backoff).await;
@ -68,24 +80,38 @@ impl RedisController {
} }
/// Get a key from the cache /// Get a key from the cache
pub async fn get(&self, key: &str) -> RedisResult<Option<String>> { pub async fn get(
&self,
key: &str
) -> RedisResult<Option<String>> {
let mut conn = self.pool.get().await.unwrap(); let mut conn = self.pool.get().await.unwrap();
conn.get(key).await conn.get(key).await
} }
pub async fn del(&self, key: &str) -> RedisResult<()> { pub async fn del(
&self,
key: &str
) -> RedisResult<()> {
let mut conn = self.pool.get().await.unwrap(); let mut conn = self.pool.get().await.unwrap();
conn.del(key).await conn.del(key).await
} }
/// Set a key with a value in the cache /// Set a key with a value in the cache
pub async fn set(&self, key: &str, value: &str) -> RedisResult<()> { pub async fn set(
&self,
key: &str,
value: &str
) -> RedisResult<()> {
let mut conn = self.pool.get().await.unwrap(); let mut conn = self.pool.get().await.unwrap();
conn.set(key, value).await conn.set(key, value).await
} }
/// Set a key with an expiration time in seconds /// Set a key with an expiration time in seconds
pub async fn expire(&self, key: &str, seconds: i64) -> RedisResult<()> { pub async fn expire(
&self,
key: &str,
seconds: i64
) -> RedisResult<()> {
let mut conn = self.pool.get().await.unwrap(); let mut conn = self.pool.get().await.unwrap();
conn.expire(key, seconds).await conn.expire(key, seconds).await
} }

View File

@ -13,49 +13,61 @@ pub struct ConfigMeta {
pub static BINARY_PROPERTIES: LazyLock<ConfigMeta> = LazyLock::new(ConfigMeta::new); pub static BINARY_PROPERTIES: LazyLock<ConfigMeta> = LazyLock::new(ConfigMeta::new);
#[cfg(not(feature = "production"))] #[cfg(not(feature = "production"))]
pub static BINARY_PROPERTIES: LazyLock<ConfigMeta> = LazyLock::new(|| pub static BINARY_PROPERTIES: LazyLock<ConfigMeta> = LazyLock::new(|| {
ConfigMeta::new() ConfigMeta::new()
.env("dev") .env("dev")
.embed_color(0xf1d63c) .embed_color(0xF1D63C)
.ready_notify(865673694184996888) .ready_notify(1311282815601741844)
.rss_channel(865673694184996888) .rss_channel(1311282815601741844)
); });
impl ConfigMeta { impl ConfigMeta {
fn new() -> Self { fn new() -> Self {
Self { Self {
env: "prod".to_string(), env: "prod".to_string(),
embed_color: 0x5a99c7, embed_color: 0x5A99C7,
ready_notify: 865673694184996888, ready_notify: 865673694184996888,
rss_channel: 865673694184996888, rss_channel: 865673694184996888,
kon_logs: 1268493237912604672, kon_logs: 1268493237912604672,
developers: vec![ developers: vec![
190407856527376384 // toast.ts 190407856527376384, // toast.ts
] ]
} }
} }
// Scalable functions below; // Scalable functions below;
#[cfg(not(feature = "production"))] #[cfg(not(feature = "production"))]
fn env(mut self, env: &str) -> Self { fn env(
mut self,
env: &str
) -> Self {
self.env = env.to_string(); self.env = env.to_string();
self self
} }
#[cfg(not(feature = "production"))] #[cfg(not(feature = "production"))]
fn embed_color(mut self, color: i32) -> Self { fn embed_color(
mut self,
color: i32
) -> Self {
self.embed_color = color; self.embed_color = color;
self self
} }
#[cfg(not(feature = "production"))] #[cfg(not(feature = "production"))]
fn ready_notify(mut self, channel_id: u64) -> Self { fn ready_notify(
mut self,
channel_id: u64
) -> Self {
self.ready_notify = channel_id; self.ready_notify = channel_id;
self self
} }
#[cfg(not(feature = "production"))] #[cfg(not(feature = "production"))]
fn rss_channel(mut self, channel_id: u64) -> Self { fn rss_channel(
mut self,
channel_id: u64
) -> Self {
self.rss_channel = channel_id; self.rss_channel = channel_id;
self self
} }

View File

@ -1,8 +1,10 @@
use std::time::Duration; use {
use reqwest::{ reqwest::{
Client, Client,
Response, Error,
Error Response
},
std::time::Duration
}; };
const ERROR_PREFIX: &str = "HTTPClient[Error]:"; const ERROR_PREFIX: &str = "HTTPClient[Error]:";
@ -10,12 +12,17 @@ const ERROR_PREFIX: &str = "HTTPClient[Error]:";
pub struct HttpClient(Client); pub struct HttpClient(Client);
impl HttpClient { impl HttpClient {
pub fn new() -> Self { pub fn new() -> Self { Self(Client::new()) }
Self(Client::new())
}
pub async fn get(&self, url: &str, ua: &str) -> Result<Response, Error> { pub async fn get(
let response = self.0.get(url).header( &self,
url: &str,
ua: &str
) -> Result<Response, Error> {
let response = self
.0
.get(url)
.header(
reqwest::header::USER_AGENT, reqwest::header::USER_AGENT,
format!("Kon ({}-{}) - {ua}/reqwest", super::utils::BOT_VERSION.as_str(), crate::GIT_COMMIT_HASH) format!("Kon ({}-{}) - {ua}/reqwest", super::utils::BOT_VERSION.as_str(), crate::GIT_COMMIT_HASH)
) )

View File

@ -2,31 +2,41 @@ mod rss;
pub use rss::rss; pub use rss::rss;
use tokio::task::spawn; use {
use poise::serenity_prelude::Context; poise::serenity_prelude::Context,
use std::{ std::{
future::Future,
sync::{ sync::{
Arc, Arc,
atomic::{ atomic::{
AtomicBool, AtomicBool,
Ordering Ordering
} }
}
}, },
future::Future tokio::task::spawn
}; };
fn task_info(name: &str, message: &str) { fn task_info(
name: &str,
message: &str
) {
println!("TaskScheduler[{name}]: {message}") println!("TaskScheduler[{name}]: {message}")
} }
fn task_err(name: &str, message: &str) { fn task_err(
name: &str,
message: &str
) {
eprintln!("TaskScheduler[{name}:Error]: {message}") eprintln!("TaskScheduler[{name}:Error]: {message}")
} }
static TASK_RUNNING: AtomicBool = AtomicBool::new(false); static TASK_RUNNING: AtomicBool = AtomicBool::new(false);
pub async fn run_task<F, T>(ctx: Arc<Context>, task: F) pub async fn run_task<F, T>(
where ctx: Arc<Context>,
task: F
) where
F: Fn(Arc<Context>) -> T + Send + 'static, F: Fn(Arc<Context>) -> T + Send + 'static,
T: Future<Output = Result<(), crate::Error>> + Send + 'static T: Future<Output = Result<(), crate::Error>> + Send + 'static
{ {

View File

@ -5,32 +5,36 @@ mod github;
mod gportal; mod gportal;
mod rust; mod rust;
use crate::{ use {
super::{
super::{
config::BINARY_PROPERTIES,
http::HttpClient
},
task_err,
task_info
},
crate::{
Error, Error,
controllers::cache::RedisController controllers::cache::RedisController
}; }
use super::{
super::{
http::HttpClient,
config::BINARY_PROPERTIES
},
task_info,
task_err
}; };
use once_cell::sync::OnceCell; use {
use feed_rs::parser::parse; feed_rs::parser::parse,
use reqwest::Response; once_cell::sync::OnceCell,
use regex::Regex; poise::serenity_prelude::{
use std::sync::Arc;
use poise::serenity_prelude::{
Context, Context,
CreateEmbed, CreateEmbed,
Timestamp Timestamp
}; },
use tokio::time::{ regex::Regex,
reqwest::Response,
std::sync::Arc,
tokio::time::{
Duration, Duration,
interval interval
}
}; };
const TASK_NAME: &str = "RSS"; const TASK_NAME: &str = "RSS";
@ -88,7 +92,10 @@ async fn fetch_feed(url: &str) -> Result<Response, Error> {
Ok(res) Ok(res)
} }
async fn save_to_redis(key: &str, value: &str) -> Result<(), Error> { async fn save_to_redis(
key: &str,
value: &str
) -> Result<(), Error> {
let redis = get_redis().await; let redis = get_redis().await;
redis.set(key, value).await.unwrap(); redis.set(key, value).await.unwrap();
if let Err(y) = redis.expire(key, REDIS_EXPIRY_SECS).await { if let Err(y) = redis.expire(key, REDIS_EXPIRY_SECS).await {

View File

@ -1,20 +1,24 @@
use crate::Error; use {
use super::{ super::{
super::task_err, super::task_err,
REDIS_EXPIRY_SECS, REDIS_EXPIRY_SECS,
get_redis,
save_to_redis,
fetch_feed, fetch_feed,
format_href_to_discord,
get_redis,
parse, parse,
format_href_to_discord save_to_redis
},
crate::Error
}; };
use std::io::Cursor; use {
use regex::Regex; poise::serenity_prelude::{
use poise::serenity_prelude::{
CreateEmbed, CreateEmbed,
CreateEmbedAuthor, CreateEmbedAuthor,
Timestamp Timestamp
},
regex::Regex,
std::io::Cursor
}; };
pub async fn esxi_embed() -> Result<Option<CreateEmbed>, Error> { pub async fn esxi_embed() -> Result<Option<CreateEmbed>, Error> {
@ -57,7 +61,8 @@ pub async fn esxi_embed() -> Result<Option<CreateEmbed>, Error> {
Ok(None) Ok(None)
} else { } else {
save_to_redis(rkey, &article.categories[3].term).await?; save_to_redis(rkey, &article.categories[3].term).await?;
Ok(Some(CreateEmbed::new() Ok(Some(
CreateEmbed::new()
.color(0x4EFBCB) .color(0x4EFBCB)
.author(CreateEmbedAuthor::new(feed.title.unwrap().content).url(home_page)) .author(CreateEmbedAuthor::new(feed.title.unwrap().content).url(home_page))
.thumbnail(feed.logo.unwrap().uri) .thumbnail(feed.logo.unwrap().uri)
@ -69,11 +74,17 @@ pub async fn esxi_embed() -> Result<Option<CreateEmbed>, Error> {
article.categories[1].term, article.categories[1].term,
format_href_to_discord(article.summary.unwrap().content.as_str()) format_href_to_discord(article.summary.unwrap().content.as_str())
)) ))
.timestamp(Timestamp::from(article.updated.unwrap()))) .timestamp(Timestamp::from(article.updated.unwrap()))
) ))
} }
} else { } else {
task_err("RSS:ESXi", &format!("Article term does not match the expected RegEx pattern! ({})", article.categories[3].term.as_str())); task_err(
"RSS:ESXi",
&format!(
"Article term does not match the expected RegEx pattern! ({})",
article.categories[3].term.as_str()
)
);
Ok(None) Ok(None)
} }
} }

View File

@ -1,22 +1,26 @@
use crate::Error; use {
use super::{ super::{
super::task_err, super::task_err,
REDIS_EXPIRY_SECS,
IncidentColorMap, IncidentColorMap,
get_redis, REDIS_EXPIRY_SECS,
save_to_redis,
fetch_feed,
parse,
embed, embed,
trim_old_content, fetch_feed,
format_html_to_discord format_html_to_discord,
get_redis,
parse,
save_to_redis,
trim_old_content
},
crate::Error
}; };
use std::io::Cursor; use {
use regex::Regex; poise::serenity_prelude::{
use poise::serenity_prelude::{
CreateEmbed, CreateEmbed,
Timestamp Timestamp
},
regex::Regex,
std::io::Cursor
}; };
pub async fn github_embed() -> Result<Option<CreateEmbed>, Error> { pub async fn github_embed() -> Result<Option<CreateEmbed>, Error> {
@ -47,7 +51,11 @@ pub async fn github_embed() -> Result<Option<CreateEmbed>, Error> {
let resolved_patt = Regex::new(r"(?i)\bresolved\b").unwrap(); let resolved_patt = Regex::new(r"(?i)\bresolved\b").unwrap();
let date_patt = Regex::new(r"\b[A-Z][a-z]{2} \d{2}, \d{2}:\d{2} UTC\b").unwrap(); let date_patt = Regex::new(r"\b[A-Z][a-z]{2} \d{2}, \d{2}:\d{2} UTC\b").unwrap();
let first_entry = date_patt.split(&new_content).map(str::trim).find(|e| !e.is_empty()).unwrap_or(&new_content); let first_entry = date_patt
.split(&new_content)
.map(str::trim)
.find(|e| !e.is_empty())
.unwrap_or(&new_content);
let color: u32 = if update_patt.is_match(first_entry) { let color: u32 = if update_patt.is_match(first_entry) {
IncidentColorMap::Update.color() IncidentColorMap::Update.color()
@ -96,7 +104,10 @@ pub async fn github_embed() -> Result<Option<CreateEmbed>, Error> {
))) )))
} }
} else { } else {
task_err("RSS:GitHub", &format!("Incident ID does not match the expected RegEx pattern! ({})", &article.links[0].href)); task_err(
"RSS:GitHub",
&format!("Incident ID does not match the expected RegEx pattern! ({})", &article.links[0].href)
);
Ok(None) Ok(None)
} }
} }

View File

@ -1,22 +1,26 @@
use crate::Error; use {
use super::{ super::{
super::task_err, super::task_err,
REDIS_EXPIRY_SECS,
IncidentColorMap, IncidentColorMap,
get_redis, REDIS_EXPIRY_SECS,
save_to_redis,
fetch_feed,
parse,
embed, embed,
trim_old_content, fetch_feed,
format_html_to_discord format_html_to_discord,
get_redis,
parse,
save_to_redis,
trim_old_content
},
crate::Error
}; };
use std::io::Cursor; use {
use regex::Regex; poise::serenity_prelude::{
use poise::serenity_prelude::{
CreateEmbed, CreateEmbed,
Timestamp Timestamp
},
regex::Regex,
std::io::Cursor
}; };
pub async fn gportal_embed() -> Result<Option<CreateEmbed>, Error> { pub async fn gportal_embed() -> Result<Option<CreateEmbed>, Error> {
@ -48,7 +52,11 @@ pub async fn gportal_embed() -> Result<Option<CreateEmbed>, Error> {
let resolved_patt = Regex::new(r"(?i)\bresolved\b").unwrap(); let resolved_patt = Regex::new(r"(?i)\bresolved\b").unwrap();
let date_patt = Regex::new(r"\b[A-Z][a-z]{2} \d{2}, \d{2}:\d{2} UTC\b").unwrap(); let date_patt = Regex::new(r"\b[A-Z][a-z]{2} \d{2}, \d{2}:\d{2} UTC\b").unwrap();
let first_entry = date_patt.split(&new_content).map(str::trim).find(|e| !e.is_empty()).unwrap_or(&new_content); let first_entry = date_patt
.split(&new_content)
.map(str::trim)
.find(|e| !e.is_empty())
.unwrap_or(&new_content);
let color: u32 = if update_patt.is_match(first_entry) { let color: u32 = if update_patt.is_match(first_entry) {
IncidentColorMap::Update.color() IncidentColorMap::Update.color()
@ -99,7 +107,10 @@ pub async fn gportal_embed() -> Result<Option<CreateEmbed>, Error> {
))) )))
} }
} else { } else {
task_err("RSS:GPortal", &format!("Incident ID does not match the expected RegEx pattern! ({})", &article.links[0].href)); task_err(
"RSS:GPortal",
&format!("Incident ID does not match the expected RegEx pattern! ({})", &article.links[0].href)
);
Ok(None) Ok(None)
} }
} }

View File

@ -1,35 +1,36 @@
use super::{ use super::{
task_err,
TASK_NAME,
BINARY_PROPERTIES, BINARY_PROPERTIES,
get_redis, TASK_NAME,
esxi::esxi_embed, esxi::esxi_embed,
get_redis,
github::github_embed, github::github_embed,
gportal::gportal_embed, gportal::gportal_embed,
rust::rust_message rust::rust_message,
task_err
}; };
use regex::Regex; use {
use tokio::time::{ poise::serenity_prelude::{
ChannelId,
Context,
CreateEmbed,
CreateMessage,
EditMessage
},
regex::Regex,
tokio::time::{
Duration, Duration,
sleep sleep
}; }
use poise::serenity_prelude::{
Context,
ChannelId,
EditMessage,
CreateMessage,
CreateEmbed,
}; };
// This is for building up the embed with the feed data // This is for building up the embed with the feed data
/* std::fs::File::create("rss_name.log").unwrap(); /* std::fs::File::create("rss_name.log").unwrap();
std::fs::write("rss_name.log", format!("{:#?}", feed))?; */ std::fs::write("rss_name.log", format!("{:#?}", feed))?; */
// todo; have a reusable function for feeding RSS data and building the embed out of it. // todo; have a reusable function for feeding RSS data and building the embed out of it.
// see github.rs / esxi.rs / gportal.rs for references of this idea. // see github.rs / esxi.rs / gportal.rs for references of this idea.
async fn process_embed( async fn process_embed(
ctx: &Context, ctx: &Context,
embed: Option<CreateEmbed>, embed: Option<CreateEmbed>,
@ -74,11 +75,17 @@ pub async fn feed_processor(ctx: &Context) {
match esxi_embed().await { match esxi_embed().await {
Ok(Some(embed)) => { Ok(Some(embed)) => {
ChannelId::new(BINARY_PROPERTIES.rss_channel).send_message(&ctx.http, CreateMessage::new().add_embed(embed)).await.unwrap(); ChannelId::new(BINARY_PROPERTIES.rss_channel)
.send_message(&ctx.http, CreateMessage::new().add_embed(embed))
.await
.unwrap();
}, },
Ok(None) => (), Ok(None) => (),
Err(y) => { Err(y) => {
log_msgs.push(format!("**[{TASK_NAME}:ESXi:Error]:** Feed failed with the following error:```\n{}\n```", y)); log_msgs.push(format!(
"**[{TASK_NAME}:ESXi:Error]:** Feed failed with the following error:```\n{}\n```",
y
));
task_err(TASK_NAME, &y.to_string()) task_err(TASK_NAME, &y.to_string())
} }
} }
@ -87,7 +94,10 @@ pub async fn feed_processor(ctx: &Context) {
Ok(Some(embed)) => process_embed(ctx, Some(embed), "RSS_GPortal_MsgID", "RSS_GPortal_Content").await.unwrap(), Ok(Some(embed)) => process_embed(ctx, Some(embed), "RSS_GPortal_MsgID", "RSS_GPortal_Content").await.unwrap(),
Ok(None) => (), Ok(None) => (),
Err(y) => { Err(y) => {
log_msgs.push(format!("**[{TASK_NAME}:GPortal:Error]:** Feed failed with the following error:```\n{}\n```", y)); log_msgs.push(format!(
"**[{TASK_NAME}:GPortal:Error]:** Feed failed with the following error:```\n{}\n```",
y
));
task_err(TASK_NAME, &y.to_string()) task_err(TASK_NAME, &y.to_string())
} }
} }
@ -96,25 +106,35 @@ pub async fn feed_processor(ctx: &Context) {
Ok(Some(embed)) => process_embed(ctx, Some(embed), "RSS_GitHub_MsgID", "RSS_GitHub_Content").await.unwrap(), Ok(Some(embed)) => process_embed(ctx, Some(embed), "RSS_GitHub_MsgID", "RSS_GitHub_Content").await.unwrap(),
Ok(None) => (), Ok(None) => (),
Err(y) => { Err(y) => {
log_msgs.push(format!("**[{TASK_NAME}:GitHub:Error]:** Feed failed with the following error:```\n{}\n```", y)); log_msgs.push(format!(
"**[{TASK_NAME}:GitHub:Error]:** Feed failed with the following error:```\n{}\n```",
y
));
task_err(TASK_NAME, &y.to_string()) task_err(TASK_NAME, &y.to_string())
} }
} }
match rust_message().await { match rust_message().await {
Ok(Some(content)) => { Ok(Some(content)) => {
ChannelId::new(BINARY_PROPERTIES.rss_channel).send_message(&ctx.http, CreateMessage::new().content(content)).await.unwrap(); ChannelId::new(BINARY_PROPERTIES.rss_channel)
.send_message(&ctx.http, CreateMessage::new().content(content))
.await
.unwrap();
}, },
Ok(None) => (), Ok(None) => (),
Err(y) => { Err(y) => {
log_msgs.push(format!("**[{TASK_NAME}:RustBlog:Error]:** Feed failed with the following error:```\n{}\n```", y)); log_msgs.push(format!(
"**[{TASK_NAME}:RustBlog:Error]:** Feed failed with the following error:```\n{}\n```",
y
));
task_err(TASK_NAME, &y.to_string()) task_err(TASK_NAME, &y.to_string())
} }
} }
if !log_msgs.is_empty() { if !log_msgs.is_empty() {
ChannelId::new(BINARY_PROPERTIES.kon_logs).send_message( ChannelId::new(BINARY_PROPERTIES.kon_logs)
&ctx.http, CreateMessage::new().content(log_msgs.join("\n")) .send_message(&ctx.http, CreateMessage::new().content(log_msgs.join("\n")))
).await.unwrap(); .await
.unwrap();
} }
} }

View File

@ -1,15 +1,19 @@
use crate::Error; use {
use super::{ super::{
task_err,
REDIS_EXPIRY_SECS, REDIS_EXPIRY_SECS,
get_redis,
save_to_redis,
fetch_feed, fetch_feed,
parse get_redis,
parse,
save_to_redis,
task_err
},
crate::Error
}; };
use std::io::Cursor; use {
use regex::Regex; regex::Regex,
std::io::Cursor
};
pub async fn rust_message() -> Result<Option<String>, Error> { pub async fn rust_message() -> Result<Option<String>, Error> {
let redis = get_redis().await; let redis = get_redis().await;
@ -44,10 +48,17 @@ pub async fn rust_message() -> Result<Option<String>, Error> {
Ok(None) Ok(None)
} else { } else {
save_to_redis(rkey, &blog).await?; save_to_redis(rkey, &blog).await?;
Ok(Some(format!("Rust Team has put out a new article!\n**[{}](<{}>)**", article.links[0].title.clone().unwrap(), article.links[0].href))) Ok(Some(format!(
"Rust Team has put out a new article!\n**[{}](<{}>)**",
article.links[0].title.clone().unwrap(),
article.links[0].href
)))
} }
} else { } else {
task_err("RSS:RustBlog", &format!("Article URL does not match the expected RegEx pattern! ({})", article_id)); task_err(
"RSS:RustBlog",
&format!("Article URL does not match the expected RegEx pattern! ({})", article_id)
);
Ok(None) Ok(None)
} }
} }

View File

@ -14,9 +14,7 @@ impl TSClient {
pub async fn get(&self) -> Result<TokenServiceApi, crate::Error> { pub async fn get(&self) -> Result<TokenServiceApi, crate::Error> {
match self.0.connect().await { match self.0.connect().await {
Ok(api) => { Ok(api) => Ok(api),
Ok(api)
}
Err(e) => Err(e) Err(e) => Err(e)
} }
} }

View File

@ -1,8 +1,10 @@
use poise::serenity_prelude::UserId; use {
use std::sync::LazyLock; super::tsclient::TSClient,
use tokio::sync::Mutex; poise::serenity_prelude::UserId,
use tokenservice_client::TokenServiceApi; std::sync::LazyLock,
use super::tsclient::TSClient; tokenservice_client::TokenServiceApi,
tokio::sync::Mutex
};
pub static BOT_VERSION: LazyLock<String> = LazyLock::new(|| { pub static BOT_VERSION: LazyLock<String> = LazyLock::new(|| {
let cargo_version = cargo_toml::Manifest::from_str(include_str!("../../Cargo.toml")) let cargo_version = cargo_toml::Manifest::from_str(include_str!("../../Cargo.toml"))
@ -16,9 +18,7 @@ pub static BOT_VERSION: LazyLock<String> = LazyLock::new(|| {
static TSCLIENT: LazyLock<Mutex<TSClient>> = LazyLock::new(|| Mutex::new(TSClient::new())); static TSCLIENT: LazyLock<Mutex<TSClient>> = LazyLock::new(|| Mutex::new(TSClient::new()));
pub async fn token_path() -> TokenServiceApi { pub async fn token_path() -> TokenServiceApi { TSCLIENT.lock().await.get().await.unwrap() }
TSCLIENT.lock().await.get().await.unwrap()
}
pub fn mention_dev(ctx: poise::Context<'_, (), crate::Error>) -> Option<String> { pub fn mention_dev(ctx: poise::Context<'_, (), crate::Error>) -> Option<String> {
let devs = super::config::BINARY_PROPERTIES.developers.clone(); let devs = super::config::BINARY_PROPERTIES.developers.clone();
@ -32,11 +32,7 @@ pub fn mention_dev(ctx: poise::Context<'_, (), crate::Error>) -> Option<String>
} }
} }
if mentions.is_empty() { if mentions.is_empty() { None } else { Some(mentions.join(", ")) }
None
} else {
Some(mentions.join(", "))
}
} }
pub fn format_duration(secs: u64) -> String { pub fn format_duration(secs: u64) -> String {

View File

@ -5,35 +5,37 @@ mod internals;
// Using the new filesystem hierarchy // Using the new filesystem hierarchy
use crate::internals::{ use crate::internals::{
config::BINARY_PROPERTIES,
tasks::{
rss,
run_task
},
utils::{ utils::{
BOT_VERSION, BOT_VERSION,
token_path, mention_dev,
mention_dev token_path
}, }
tasks::{
run_task,
rss
},
config::BINARY_PROPERTIES
}; };
use std::{ use {
sync::Arc, poise::serenity_prelude::{
borrow::Cow, ChannelId,
thread::current ClientBuilder,
};
use poise::serenity_prelude::{
builder::{
CreateMessage,
CreateEmbed,
CreateEmbedAuthor
},
Ready,
Context, Context,
FullEvent, FullEvent,
ClientBuilder, GatewayIntents,
ChannelId, Ready,
GatewayIntents builder::{
CreateEmbed,
CreateEmbedAuthor,
CreateMessage
}
},
std::{
borrow::Cow,
sync::Arc,
thread::current
}
}; };
type Error = Box<dyn std::error::Error + Send + Sync>; type Error = Box<dyn std::error::Error + Send + Sync>;
@ -67,7 +69,9 @@ async fn on_ready(
.thumbnail(ready.user.avatar_url().unwrap_or_default()) .thumbnail(ready.user.avatar_url().unwrap_or_default())
.author(CreateEmbedAuthor::new(format!("{} is ready!", ready.user.name))); .author(CreateEmbedAuthor::new(format!("{} is ready!", ready.user.name)));
ChannelId::new(BINARY_PROPERTIES.ready_notify).send_message(&ctx.http, message.add_embed(ready_embed)).await?; ChannelId::new(BINARY_PROPERTIES.ready_notify)
.send_message(&ctx.http, message.add_embed(ready_embed))
.await?;
Ok(()) Ok(())
} }
@ -104,7 +108,7 @@ async fn main() {
commands::ping::ping(), commands::ping::ping(),
commands::status::status(), commands::status::status(),
commands::midi::midi_to_wav(), commands::midi::midi_to_wav(),
commands::uptime::uptime() commands::uptime::uptime(),
], ],
prefix_options: poise::PrefixFrameworkOptions { prefix_options: poise::PrefixFrameworkOptions {
prefix, prefix,
@ -114,35 +118,37 @@ async fn main() {
ignore_thread_creation: true, ignore_thread_creation: true,
..Default::default() ..Default::default()
}, },
pre_command: |ctx| Box::pin(async move { pre_command: |ctx| {
Box::pin(async move {
let get_guild_name = match ctx.guild() { let get_guild_name = match ctx.guild() {
Some(guild) => guild.name.clone(), Some(guild) => guild.name.clone(),
None => String::from("Direct Message") None => String::from("Direct Message")
}; };
println!( println!("Discord[{get_guild_name}]: {} ran /{}", ctx.author().name, ctx.command().qualified_name);
"Discord[{get_guild_name}]: {} ran /{}", })
ctx.author().name, },
ctx.command().qualified_name on_error: |error| {
); Box::pin(async move {
}),
on_error: |error| Box::pin(async move {
match error { match error {
poise::FrameworkError::Command { error, ctx, .. } => { poise::FrameworkError::Command { error, ctx, .. } => {
println!("PoiseCommandError({}): {error}", ctx.command().qualified_name); println!("PoiseCommandError({}): {error}", ctx.command().qualified_name);
ctx.reply(format!( ctx
.reply(format!(
"Encountered an error during command execution, ask {} to check console for more details!", "Encountered an error during command execution, ask {} to check console for more details!",
mention_dev(ctx).unwrap_or_default() mention_dev(ctx).unwrap_or_default()
)).await.expect("Error sending message"); ))
.await
.expect("Error sending message");
}, },
poise::FrameworkError::EventHandler { error, event, .. } => println!("PoiseEventHandlerError({}): {error}", event.snake_case_name()), poise::FrameworkError::EventHandler { error, event, .. } => println!("PoiseEventHandlerError({}): {error}", event.snake_case_name()),
poise::FrameworkError::UnknownInteraction { interaction, .. } => println!( poise::FrameworkError::UnknownInteraction { interaction, .. } => println!(
"PoiseUnknownInteractionError: {} tried to execute an unknown interaction ({})", "PoiseUnknownInteractionError: {} tried to execute an unknown interaction ({})",
interaction.user.name, interaction.user.name, interaction.data.name
interaction.data.name
), ),
other => println!("PoiseOtherError: {other}") other => println!("PoiseOtherError: {other}")
} }
}), })
},
initialize_owners: true, initialize_owners: true,
event_handler: |framework, event| Box::pin(event_processor(framework, event)), event_handler: |framework, event| Box::pin(event_processor(framework, event)),
..Default::default() ..Default::default()
@ -152,12 +158,11 @@ async fn main() {
let mut client = ClientBuilder::new( let mut client = ClientBuilder::new(
token_path().await.main, token_path().await.main,
GatewayIntents::GUILDS GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT
| GatewayIntents::GUILD_MESSAGES
| GatewayIntents::MESSAGE_CONTENT
) )
.framework(framework) .framework(framework)
.await.expect("Error creating client"); .await
.expect("Error creating client");
if let Err(why) = client.start().await { if let Err(why) = client.start().await {
println!("Error starting client: {why:#?}"); println!("Error starting client: {why:#?}");