From 28b89406092058797918f0adb483142d96bc88ee Mon Sep 17 00:00:00 2001 From: pomni Date: Tue, 3 Dec 2024 00:17:58 +1100 Subject: [PATCH] Bring over the rustfmt stuff --- Cargo.lock | 231 +++++++++++++-------------- Cargo.toml | 8 +- run.sh | 2 +- rust-toolchain | 2 + rustfmt.toml | 20 +++ src/commands.rs | 6 +- src/commands/ilo.rs | 164 ++++++++++--------- src/commands/midi.rs | 65 ++++---- src/commands/status.rs | 47 +++--- src/commands/uptime.rs | 42 ++--- src/controllers/cache.rs | 92 +++++++---- src/internals/config.rs | 52 +++--- src/internals/http.rs | 27 ++-- src/internals/tasks.rs | 36 +++-- src/internals/tasks/rss.rs | 61 +++---- src/internals/tasks/rss/esxi.rs | 71 ++++---- src/internals/tasks/rss/github.rs | 49 +++--- src/internals/tasks/rss/gportal.rs | 49 +++--- src/internals/tasks/rss/processor.rs | 76 +++++---- src/internals/tasks/rss/rust.rs | 35 ++-- src/internals/tsclient.rs | 4 +- src/internals/utils.rs | 22 ++- src/main.rs | 123 +++++++------- 23 files changed, 719 insertions(+), 565 deletions(-) create mode 100644 rust-toolchain create mode 100644 rustfmt.toml diff --git a/Cargo.lock b/Cargo.lock index c05f2fb..072b793 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -64,7 +64,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -170,9 +170,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" +checksum = "325918d6fe32f23b19878fe4b34794ae41fc19ddbe53b10571a4874d44ffd39b" [[package]] name = "camino" @@ -185,9 +185,9 @@ dependencies = [ [[package]] name = "cargo-platform" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc" +checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" dependencies = [ "serde", ] @@ -217,9 +217,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" +checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" dependencies = [ "shlex", ] @@ -277,9 +277,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ca741a962e1b0bff6d724a1a0958b686406e853bb14061f218562e1896f95e6" +checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" dependencies = [ "libc", ] @@ -358,7 +358,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -369,7 +369,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -431,7 +431,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -458,7 +458,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -469,12 +469,12 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" +checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -593,7 +593,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -689,9 +689,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" +checksum = "ccae279728d634d083c00f6099cb58f01cc99c145b84b8be2f6c74618d79922e" dependencies = [ "atomic-waker", "bytes", @@ -714,9 +714,9 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" [[package]] name = "hashbrown" -version = "0.15.1" +version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a9bfc1af68b1726ea47d3d5109de126281def866b33970e10fbab11b5dafab3" +checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" [[package]] name = "heck" @@ -724,12 +724,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - [[package]] name = "hostname" version = "0.3.1" @@ -835,14 +829,14 @@ dependencies = [ [[package]] name = "hyper" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbbff0a806a4728c99295b254c8838933b5b082d75e3cb70c8dab21fdfbcfa9a" +checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" dependencies = [ "bytes", "futures-channel", "futures-util", - "h2 0.4.6", + "h2 0.4.7", "http 1.1.0", "http-body 1.0.1", "httparse", @@ -875,9 +869,9 @@ checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" dependencies = [ "futures-util", "http 1.1.0", - "hyper 1.5.0", + "hyper 1.5.1", "hyper-util", - "rustls 0.23.17", + "rustls 0.23.19", "rustls-pki-types", "tokio", "tokio-rustls 0.26.0", @@ -892,7 +886,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", "http-body-util", - "hyper 1.5.0", + "hyper 1.5.1", "hyper-util", "native-tls", "tokio", @@ -911,7 +905,7 @@ dependencies = [ "futures-util", "http 1.1.0", "http-body 1.0.1", - "hyper 1.5.0", + "hyper 1.5.1", "pin-project-lite", "socket2", "tokio", @@ -1057,7 +1051,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -1099,12 +1093,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.6.0" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f" dependencies = [ "equivalent", - "hashbrown 0.15.1", + "hashbrown 0.15.2", ] [[package]] @@ -1127,22 +1121,23 @@ checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708" [[package]] name = "itoa" -version = "1.0.11" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" [[package]] name = "js-sys" -version = "0.3.72" +version = "0.3.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" +checksum = "a865e038f7f6ed956f788f0d7d60c541fff74c7bd74272c5d4cf15c63743e705" dependencies = [ + "once_cell", "wasm-bindgen", ] [[package]] name = "kon" -version = "0.5.0" +version = "0.5.1" dependencies = [ "bb8", "bb8-redis", @@ -1162,9 +1157,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.164" +version = "0.2.167" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "433bfe06b8c75da9b2e3fbea6e5329ff87748f0b144ef75306e674c3f6f7c13f" +checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" [[package]] name = "linked-hash-map" @@ -1180,9 +1175,9 @@ checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "litemap" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" +checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104" [[package]] name = "lock_api" @@ -1272,11 +1267,10 @@ dependencies = [ [[package]] name = "mio" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" +checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" dependencies = [ - "hermit-abi", "libc", "wasi", "windows-sys 0.52.0", @@ -1380,7 +1374,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -1484,7 +1478,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -1504,9 +1498,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.89" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] @@ -1711,11 +1705,11 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2 0.4.6", + "h2 0.4.7", "http 1.1.0", "http-body 1.0.1", "http-body-util", - "hyper 1.5.0", + "hyper 1.5.1", "hyper-rustls 0.27.3", "hyper-tls", "hyper-util", @@ -1731,7 +1725,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper 1.0.1", + "sync_wrapper 1.0.2", "system-configuration 0.6.1", "tokio", "tokio-native-tls", @@ -1815,9 +1809,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.17" +version = "0.23.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f1a745511c54ba6d4465e8d5dfbd81b45791756de28d4981af70d6dca128f1e" +checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1" dependencies = [ "once_cell", "rustls-pki-types", @@ -1979,7 +1973,7 @@ checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -2112,9 +2106,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" -version = "0.5.7" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8" dependencies = [ "libc", "windows-sys 0.52.0", @@ -2157,9 +2151,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.87" +version = "2.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" +checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" dependencies = [ "proc-macro2", "quote", @@ -2174,9 +2168,9 @@ checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" [[package]] name = "sync_wrapper" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" dependencies = [ "futures-core", ] @@ -2189,14 +2183,14 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] name = "sysinfo" -version = "0.32.0" +version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ae3f4f7d64646c46c4cae4e3f01d1c5d255c7406fdd7c7f999a94e488791" +checksum = "4c33cd241af0f2e9e3b5c32163b873b29956890b5342e6745b917ce9d490f4af" dependencies = [ "core-foundation-sys", "libc", @@ -2284,7 +2278,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -2382,7 +2376,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -2422,7 +2416,7 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.23.17", + "rustls 0.23.19", "rustls-pki-types", "tokio", ] @@ -2440,7 +2434,7 @@ dependencies = [ "tokio", "tokio-rustls 0.25.0", "tungstenite", - "webpki-roots 0.26.6", + "webpki-roots 0.26.7", ] [[package]] @@ -2498,9 +2492,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.40" +version = "0.1.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" dependencies = [ "log", "pin-project-lite", @@ -2510,20 +2504,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.27" +version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] name = "tracing-core" -version = "0.1.32" +version = "0.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" dependencies = [ "once_cell", ] @@ -2651,7 +2645,7 @@ checksum = "fd9fc0ad9e03a2b0c2e2a0eafaecccef2121829e1ab6ce9c9d790e6c6766bd1c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -2668,9 +2662,9 @@ checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" [[package]] name = "unicode-ident" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" +checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" [[package]] name = "unicode-normalization" @@ -2700,9 +2694,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.3" +version = "2.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d157f1b96d14500ffdc1f10ba712e780825526c03d9a49b4d0324b0d9113ada" +checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" dependencies = [ "form_urlencoded", "idna 1.0.3", @@ -2776,9 +2770,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" +checksum = "d15e63b4482863c109d70a7b8706c1e364eb6ea449b201a76c5b89cedcec2d5c" dependencies = [ "cfg-if", "once_cell", @@ -2787,36 +2781,37 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" +checksum = "8d36ef12e3aaca16ddd3f67922bc63e48e953f126de60bd33ccc0101ef9998cd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.45" +version = "0.4.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7ec4f8827a71586374db3e87abdb5a2bb3a15afed140221307c3ec06b1f63b" +checksum = "9dfaf8f50e5f293737ee323940c7d8b08a66a95a419223d9f41610ca08b0833d" dependencies = [ "cfg-if", "js-sys", + "once_cell", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" +checksum = "705440e08b42d3e4b36de7d66c944be628d579796b8090bfa3471478a2260051" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2824,22 +2819,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" +checksum = "98c9ae5a76e46f4deecd0f0255cc223cfa18dc9b261213b8aa0c7b36f61b3f1d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" +checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49" [[package]] name = "wasm-streams" @@ -2856,9 +2851,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.72" +version = "0.3.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" +checksum = "a98bc3c33f0fe7e59ad7cd041b89034fa82a7c2d4365ca538dda6cdaf513863c" dependencies = [ "js-sys", "wasm-bindgen", @@ -2872,9 +2867,9 @@ checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" [[package]] name = "webpki-roots" -version = "0.26.6" +version = "0.26.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841c67bff177718f1d4dfefde8d8f0e78f9b6589319ba88312f567fc5841a958" +checksum = "5d642ff16b7e79272ae451b7322067cdc17cadf68c23264be9d94a32319efe7e" dependencies = [ "rustls-pki-types", ] @@ -2955,7 +2950,7 @@ checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -2966,7 +2961,7 @@ checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] @@ -3189,9 +3184,9 @@ checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" [[package]] name = "yoke" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40" dependencies = [ "serde", "stable_deref_trait", @@ -3201,13 +3196,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", "synstructure", ] @@ -3229,27 +3224,27 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] [[package]] name = "zerofrom" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +checksum = "cff3ee08c995dee1859d998dea82f7374f2826091dd9cd47def953cae446cd2e" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", "synstructure", ] @@ -3278,5 +3273,5 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.90", ] diff --git a/Cargo.toml b/Cargo.toml index 60f77e3..5922601 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "kon" -version = "0.5.0" -edition = "2021" +version = "0.5.1" +edition = "2024" [dependencies] bb8 = "0.8.6" @@ -14,8 +14,8 @@ regex = "1.11.1" reqwest = { version = "0.12.9", features = ["json", "native-tls-vendored"] } serde = "1.0.215" serde_json = "1.0.133" -sysinfo = "0.32.0" -tokenservice-client = { version = "0.4.0", registry = "gitea" } +sysinfo = "0.32.1" +tokenservice-client = { version = "0.4.1", registry = "gitea" } tokio = { version = "1.41.1", features = ["macros", "signal", "rt-multi-thread"] } uptime_lib = "0.3.1" diff --git a/run.sh b/run.sh index 2492acd..ff19b1c 100755 --- a/run.sh +++ b/run.sh @@ -1,3 +1,3 @@ #!/bin/bash -clear && cargo run kon_dev +clear && cargo fmt && cargo run kon_dev diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000..5d56faf --- /dev/null +++ b/rust-toolchain @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..3086d77 --- /dev/null +++ b/rustfmt.toml @@ -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 diff --git a/src/commands.rs b/src/commands.rs index e6ce2a7..1b445d8 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -9,11 +9,7 @@ pub mod uptime; type PoiseCtx<'a> = poise::Context<'a, (), Error>; /// Deploy the commands globally or in a guild -#[poise::command( - prefix_command, - owners_only, - guild_only -)] +#[poise::command(prefix_command, owners_only, guild_only)] pub async fn deploy(ctx: PoiseCtx<'_>) -> Result<(), Error> { poise::builtins::register_application_commands_buttons(ctx).await?; Ok(()) diff --git a/src/commands/ilo.rs b/src/commands/ilo.rs index 9d6ca73..b0f774a 100644 --- a/src/commands/ilo.rs +++ b/src/commands/ilo.rs @@ -6,26 +6,28 @@ use crate::{ } }; -use reqwest::{ - ClientBuilder, - Error as ReqError -}; -use serde::{ - Serialize, - Deserialize -}; -use poise::{ - CreateReply, - serenity_prelude::{ - CreateEmbed, - Timestamp +use { + poise::{ + CreateReply, + serenity_prelude::{ + CreateEmbed, + Timestamp + } + }, + reqwest::{ + ClientBuilder, + Error as ReqError + }, + serde::{ + Deserialize, + Serialize } }; #[derive(Serialize, Deserialize)] struct Chassis { #[serde(rename = "Fans")] - fans: Vec, + fans: Vec, #[serde(rename = "Temperatures")] temperatures: Vec } @@ -35,27 +37,27 @@ struct Fan { #[serde(rename = "CurrentReading")] current_reading: i32, #[serde(rename = "FanName")] - fan_name: String, + fan_name: String, #[serde(rename = "Status")] - status: Status, + status: Status } #[derive(Serialize, Deserialize)] struct Temperature { #[serde(rename = "CurrentReading")] - current_reading: i32, + current_reading: i32, #[serde(rename = "Name")] - name: String, + name: String, #[serde(rename = "ReadingCelsius")] - reading_celsius: i32, + reading_celsius: i32, #[serde(rename = "Status")] - status: Status, + status: Status, #[serde(rename = "Units")] - units: String, + units: String, #[serde(rename = "UpperThresholdCritical")] upper_threshold_critical: i32, #[serde(rename = "UpperThresholdFatal")] - upper_threshold_fatal: i32 + upper_threshold_fatal: i32 } #[derive(Serialize, Deserialize)] @@ -63,7 +65,7 @@ struct Status { #[serde(rename = "Health")] health: Option, #[serde(rename = "State")] - state: String + state: String } #[derive(Serialize, Deserialize, Debug)] @@ -73,7 +75,7 @@ struct Power { #[serde(rename = "PowerConsumedWatts")] power_consumed_watts: i32, #[serde(rename = "PowerMetrics")] - power_metrics: PowerMetrics + power_metrics: PowerMetrics } #[derive(Serialize, Deserialize, Debug)] @@ -81,21 +83,21 @@ struct PowerMetrics { #[serde(rename = "AverageConsumedWatts")] average_consumed_watts: i32, #[serde(rename = "MaxConsumedWatts")] - max_consumed_watts: i32, + max_consumed_watts: i32, #[serde(rename = "MinConsumedWatts")] - min_consumed_watts: i32 + min_consumed_watts: i32 } #[derive(Serialize, Deserialize)] struct System { #[serde(rename = "Memory")] - memory: Memory, + memory: Memory, #[serde(rename = "Model")] - model: String, + model: String, #[serde(rename = "Oem")] - oem: Oem, + oem: Oem, #[serde(rename = "PowerState")] - power_state: String, + power_state: String, #[serde(rename = "ProcessorSummary")] processor_summary: ProcessorSummary } @@ -111,7 +113,7 @@ struct ProcessorSummary { #[serde(rename = "Count")] count: i32, #[serde(rename = "Model")] - cpu: String + cpu: String } #[derive(Serialize, Deserialize)] @@ -153,10 +155,7 @@ impl RedfishEndpoint { } async fn ilo_data(endpoint: RedfishEndpoint) -> Result, ReqError> { - let client = ClientBuilder::new() - .danger_accept_invalid_certs(true) - .build() - .unwrap(); + let client = ClientBuilder::new().danger_accept_invalid_certs(true).build().unwrap(); let res = client .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)) @@ -168,15 +167,15 @@ async fn ilo_data(endpoint: RedfishEndpoint) -> Result { let body: Chassis = res.json().await.unwrap(); Ok(Box::new(body)) - } + }, RedfishEndpoint::Power => { let body: Power = res.json().await.unwrap(); Ok(Box::new(body)) - } + }, RedfishEndpoint::System => { let body: System = res.json().await.unwrap(); Ok(Box::new(body)) - } + }, RedfishEndpoint::EventService => { let body: Event = res.json().await.unwrap(); Ok(Box::new(body)) @@ -191,9 +190,7 @@ async fn ilo_data(endpoint: RedfishEndpoint) -> Result) -> Result<(), Error> { - Ok(()) -} +pub async fn ilo(_: super::PoiseCtx<'_>) -> Result<(), Error> { Ok(()) } /// Retrieve the server's temperature data #[poise::command(slash_command)] @@ -204,11 +201,7 @@ pub async fn temperature(ctx: super::PoiseCtx<'_>) -> Result<(), Error> { let mut tempdata = String::new(); let mut fandata = String::new(); - let allowed_sensors = [ - "01-Inlet Ambient", - "04-P1 DIMM 1-6", - "14-Chipset Zone" - ]; + let allowed_sensors = ["01-Inlet Ambient", "04-P1 DIMM 1-6", "14-Chipset Zone"]; for temp in &data.temperatures { 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)); } - ctx.send(CreateReply::default().embed( - CreateEmbed::new() - .color(BINARY_PROPERTIES.embed_color) - .timestamp(Timestamp::now()) - .title(format!("{} - Temperatures", ILO_HOSTNAME)) - .fields(vec![ - ("Temperatures", tempdata, false), - ("Fans", fandata, false) - ]) - )).await?; + ctx + .send( + CreateReply::default().embed( + CreateEmbed::new() + .color(BINARY_PROPERTIES.embed_color) + .timestamp(Timestamp::now()) + .title(format!("{} - Temperatures", ILO_HOSTNAME)) + .fields(vec![("Temperatures", tempdata, false), ("Fans", fandata, false)]) + ) + ) + .await?; 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!("**Min Consumed:** `{}w`", &data.power_metrics.min_consumed_watts)); - ctx.send(CreateReply::default().embed( - CreateEmbed::new() - .color(BINARY_PROPERTIES.embed_color) - .timestamp(Timestamp::now()) - .title(format!("{} - Power", ILO_HOSTNAME)) - .description(powerdata) - )).await?; + ctx + .send( + CreateReply::default().embed( + CreateEmbed::new() + .color(BINARY_PROPERTIES.embed_color) + .timestamp(Timestamp::now()) + .title(format!("{} - Power", ILO_HOSTNAME)) + .description(powerdata) + ) + ) + .await?; Ok(()) } @@ -277,10 +275,7 @@ pub async fn power(ctx: super::PoiseCtx<'_>) -> Result<(), Error> { pub async fn system(ctx: super::PoiseCtx<'_>) -> Result<(), Error> { ctx.defer().await?; - let (ilo_sys, ilo_event) = tokio::join!( - ilo_data(RedfishEndpoint::System), - ilo_data(RedfishEndpoint::EventService) - ); + let (ilo_sys, ilo_event) = tokio::join!(ilo_data(RedfishEndpoint::System), ilo_data(RedfishEndpoint::EventService)); let ilo_sys = ilo_sys.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); } - 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!("**Power:** `{}`\n", &system_data.power_state)); data.push_str(&format!("**Model:** `{}`", &system_data.model)); - ctx.send(CreateReply::default().embed( - CreateEmbed::new() - .color(BINARY_PROPERTIES.embed_color) - .timestamp(Timestamp::now()) - .title(format!("{} - System", ILO_HOSTNAME)) - .description(data) - .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) - ]) - )).await?; + ctx + .send( + CreateReply::default().embed( + CreateEmbed::new() + .color(BINARY_PROPERTIES.embed_color) + .timestamp(Timestamp::now()) + .title(format!("{} - System", ILO_HOSTNAME)) + .description(data) + .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), + ]) + ) + ) + .await?; Ok(()) } diff --git a/src/commands/midi.rs b/src/commands/midi.rs index 5d4b651..f998045 100644 --- a/src/commands/midi.rs +++ b/src/commands/midi.rs @@ -1,30 +1,32 @@ use crate::{ Error, internals::utils::{ - mention_dev, - format_bytes + format_bytes, + mention_dev } }; -use regex::Regex; -use std::{ - os::unix::fs::MetadataExt, - fs::{ - write, - remove_file, - metadata +use { + poise::{ + CreateReply, + serenity_prelude::CreateAttachment + }, + regex::Regex, + std::{ + fs::{ + metadata, + remove_file, + write + }, + os::unix::fs::MetadataExt } }; -use poise::{ - CreateReply, - serenity_prelude::CreateAttachment -}; /// Convert MIDI file to WAV #[poise::command( context_menu_command = "MIDI -> WAV", install_context = "User", - interaction_context = "Guild|BotDm|PrivateChannel", + interaction_context = "Guild|BotDm|PrivateChannel" )] pub async fn midi_to_wav( ctx: super::PoiseCtx<'_>, @@ -42,13 +44,13 @@ pub async fn midi_to_wav( let bytes = match message.attachments[0].download().await { Ok(bytes) => bytes, Err(y) => { - ctx.send(CreateReply::default() - .content(format!( + ctx + .send(CreateReply::default().content(format!( "Download failed, ask {} to check console for more information!", mention_dev(ctx).unwrap_or_default() - )) - ) - .await.unwrap(); + ))) + .await + .unwrap(); return Err(Error::from(format!("Failed to download the file: {y}"))) } @@ -71,9 +73,9 @@ pub async fn midi_to_wav( match output { Ok(_) => { - let reply = ctx.send(CreateReply::default() - .attachment(CreateAttachment::path(&*wav_path).await.unwrap()) - ).await; + let reply = ctx + .send(CreateReply::default().attachment(CreateAttachment::path(&*wav_path).await.unwrap())) + .await; if reply.is_err() { println!( @@ -81,21 +83,24 @@ pub async fn midi_to_wav( ctx.command().qualified_name ); - ctx.send(CreateReply::default() - .content(format!( + ctx + .send(CreateReply::default().content(format!( "Couldn't upload the processed file (`{}`, `{}`) due to upload limit", - &*wav_path, format_bytes(metadata(&*wav_path).unwrap().size()) - )) - ).await.unwrap(); + &*wav_path, + format_bytes(metadata(&*wav_path).unwrap().size()) + ))) + .await + .unwrap(); } else if reply.is_ok() { remove_file(midi_path)?; remove_file(&*wav_path)?; } }, Err(y) => { - ctx.send(CreateReply::default() - .content("Command didn't execute successfully, check console for more information!") - ).await.unwrap(); + ctx + .send(CreateReply::default().content("Command didn't execute successfully, check console for more information!")) + .await + .unwrap(); return Err(Error::from(format!("Midi conversion failed: {y}"))) } diff --git a/src/commands/status.rs b/src/commands/status.rs index 1b70a14..f81cd27 100644 --- a/src/commands/status.rs +++ b/src/commands/status.rs @@ -7,12 +7,14 @@ use crate::{ } }; -use serde_json::Value; -use std::collections::HashMap; -use tokio::join; -use poise::{ - CreateReply, - serenity_prelude::builder::CreateEmbed +use { + poise::{ + CreateReply, + serenity_prelude::builder::CreateEmbed + }, + serde_json::Value, + std::collections::HashMap, + tokio::join }; async fn pms_serverstatus(url: &str) -> Result)>, Error> { @@ -38,11 +40,10 @@ async fn pms_serverstatus(url: &str) -> Result)>, Error> fn process_pms_statuses(servers: Vec<(String, Vec)>) -> Vec<(String, String, bool)> { let mut server_map: HashMap> = HashMap::new(); - let id_name_map: HashMap<&str, &str> = [ - ("wotbsg", "ASIA"), - ("wowssg", "WoWS (ASIA)"), - ("wowseu", "WoWS (EU)") - ].iter().cloned().collect(); + let id_name_map: HashMap<&str, &str> = [("wotbsg", "ASIA"), ("wowssg", "WoWS (ASIA)"), ("wowseu", "WoWS (EU)")] + .iter() + .cloned() + .collect(); for (title, mapped_servers) in servers { for server in mapped_servers { @@ -54,26 +55,28 @@ fn process_pms_statuses(servers: Vec<(String, Vec)>) -> Vec<(String, Stri _ => "Unknown" }; 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(); for (title, servers) in server_map { - let servers_str = servers.iter().map(|(name, status)| format!("{}: {}", name, status)).collect::>().join("\n"); + let servers_str = servers + .iter() + .map(|(name, status)| format!("{}: {}", name, status)) + .collect::>() + .join("\n"); statuses.push((title, servers_str, true)); } statuses } /// Query the server statuses -#[poise::command( - slash_command, - subcommands("wg") -)] -pub async fn status(_: super::PoiseCtx<'_>) -> Result<(), Error> { - Ok(()) -} +#[poise::command(slash_command, subcommands("wg"))] +pub async fn status(_: super::PoiseCtx<'_>) -> Result<(), Error> { Ok(()) } /// Retrieve the server statuses from Wargaming #[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 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(()) } diff --git a/src/commands/uptime.rs b/src/commands/uptime.rs index 8f23dc5..52b392b 100644 --- a/src/commands/uptime.rs +++ b/src/commands/uptime.rs @@ -1,27 +1,29 @@ use crate::{ Error, - GIT_COMMIT_HASH, GIT_COMMIT_BRANCH, + GIT_COMMIT_HASH, internals::utils::{ BOT_VERSION, format_duration } }; -use sysinfo::System; -use uptime_lib::get; -use std::{ - fs::File, - path::Path, - time::{ - Duration, - SystemTime, - UNIX_EPOCH +use { + std::{ + fs::File, + io::{ + BufRead, + BufReader + }, + path::Path, + time::{ + Duration, + SystemTime, + UNIX_EPOCH + } }, - io::{ - BufRead, - BufReader - } + sysinfo::System, + uptime_lib::get }; fn get_os_info() -> String { @@ -32,13 +34,11 @@ fn get_os_info() -> String { if let Ok(file) = File::open(path) { let reader = BufReader::new(file); 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| { - match line { - 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_ID=") => version = set_value(l), - _ => {} - } + reader.lines().map_while(Result::ok).for_each(|line| match line { + 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_ID=") => version = set_value(l), + _ => {} }); } diff --git a/src/controllers/cache.rs b/src/controllers/cache.rs index 66e2253..aef9d92 100644 --- a/src/controllers/cache.rs +++ b/src/controllers/cache.rs @@ -1,16 +1,20 @@ use crate::internals::utils::token_path; -use bb8_redis::{ - bb8::Pool, - redis::cmd, - redis::RedisError, - redis::RedisResult, - redis::AsyncCommands, - RedisConnectionManager -}; -use tokio::time::{ - Duration, - sleep +use { + bb8_redis::{ + RedisConnectionManager, + bb8::Pool, + redis::{ + AsyncCommands, + RedisError, + RedisResult, + cmd + } + }, + tokio::time::{ + Duration, + sleep + } }; #[derive(Debug)] @@ -31,27 +35,35 @@ impl RedisController { loop { match Pool::builder().max_size(20).retry_connection(true).build(manager.clone()).await { - Ok(pool) => { - match pool.get().await { - Ok(mut conn) => { - let ping: RedisResult = cmd("PING").query_async(&mut *conn).await; - match ping { - Ok(_) => { - println!("Redis[Info]: Successfully connected"); - return pool.clone(); - }, - Err(e) => { - eprintln!("{}", redis_err.replace("{{ e }}", &e.to_string()).replace("{{ backoff }}", &backoff.to_string())); - Self::apply_backoff(&mut backoff).await; - } + Ok(pool) => match pool.get().await { + Ok(mut conn) => { + let ping: RedisResult = cmd("PING").query_async(&mut *conn).await; + match ping { + Ok(_) => { + println!("Redis[Info]: Successfully connected"); + return pool.clone(); + }, + Err(e) => { + eprintln!( + "{}", + redis_err + .replace("{{ e }}", &e.to_string()) + .replace("{{ backoff }}", &backoff.to_string()) + ); + Self::apply_backoff(&mut backoff).await; } - }, - Err(e) => { - eprintln!("{}", redis_err.replace("{{ e }}", &e.to_string()).replace("{{ backoff }}", &backoff.to_string())); - Self::apply_backoff(&mut backoff).await; } + }, + Err(e) => { + eprintln!( + "{}", + redis_err + .replace("{{ e }}", &e.to_string()) + .replace("{{ backoff }}", &backoff.to_string()) + ); + Self::apply_backoff(&mut backoff).await; } - } + }, Err(e) => { eprintln!("Redis[PoolError]: {e}, retrying in {backoff} seconds"); Self::apply_backoff(&mut backoff).await; @@ -68,24 +80,38 @@ impl RedisController { } /// Get a key from the cache - pub async fn get(&self, key: &str) -> RedisResult> { + pub async fn get( + &self, + key: &str + ) -> RedisResult> { let mut conn = self.pool.get().await.unwrap(); 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(); conn.del(key).await } /// 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(); conn.set(key, value).await } /// 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(); conn.expire(key, seconds).await } diff --git a/src/internals/config.rs b/src/internals/config.rs index 34af516..6df28b1 100644 --- a/src/internals/config.rs +++ b/src/internals/config.rs @@ -1,61 +1,73 @@ use std::sync::LazyLock; pub struct ConfigMeta { - pub env: String, - pub embed_color: i32, + pub env: String, + pub embed_color: i32, pub ready_notify: u64, - pub rss_channel: u64, - pub kon_logs: u64, - pub developers: Vec + pub rss_channel: u64, + pub kon_logs: u64, + pub developers: Vec } #[cfg(feature = "production")] pub static BINARY_PROPERTIES: LazyLock = LazyLock::new(ConfigMeta::new); #[cfg(not(feature = "production"))] -pub static BINARY_PROPERTIES: LazyLock = LazyLock::new(|| +pub static BINARY_PROPERTIES: LazyLock = LazyLock::new(|| { ConfigMeta::new() .env("dev") - .embed_color(0xf1d63c) - .ready_notify(865673694184996888) - .rss_channel(865673694184996888) -); + .embed_color(0xF1D63C) + .ready_notify(1311282815601741844) + .rss_channel(1311282815601741844) +}); impl ConfigMeta { fn new() -> Self { Self { - env: "prod".to_string(), - embed_color: 0x5a99c7, + env: "prod".to_string(), + embed_color: 0x5A99C7, ready_notify: 865673694184996888, - rss_channel: 865673694184996888, - kon_logs: 1268493237912604672, - developers: vec![ - 190407856527376384 // toast.ts + rss_channel: 865673694184996888, + kon_logs: 1268493237912604672, + developers: vec![ + 190407856527376384, // toast.ts ] } } // Scalable functions below; #[cfg(not(feature = "production"))] - fn env(mut self, env: &str) -> Self { + fn env( + mut self, + env: &str + ) -> Self { self.env = env.to_string(); self } #[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 } #[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 } #[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 } diff --git a/src/internals/http.rs b/src/internals/http.rs index 083a9c0..15c150f 100644 --- a/src/internals/http.rs +++ b/src/internals/http.rs @@ -1,8 +1,10 @@ -use std::time::Duration; -use reqwest::{ - Client, - Response, - Error +use { + reqwest::{ + Client, + Error, + Response + }, + std::time::Duration }; const ERROR_PREFIX: &str = "HTTPClient[Error]:"; @@ -10,12 +12,17 @@ const ERROR_PREFIX: &str = "HTTPClient[Error]:"; pub struct HttpClient(Client); impl HttpClient { - pub fn new() -> Self { - Self(Client::new()) - } + pub fn new() -> Self { Self(Client::new()) } - pub async fn get(&self, url: &str, ua: &str) -> Result { - let response = self.0.get(url).header( + pub async fn get( + &self, + url: &str, + ua: &str + ) -> Result { + let response = self + .0 + .get(url) + .header( reqwest::header::USER_AGENT, format!("Kon ({}-{}) - {ua}/reqwest", super::utils::BOT_VERSION.as_str(), crate::GIT_COMMIT_HASH) ) diff --git a/src/internals/tasks.rs b/src/internals/tasks.rs index 212e837..a69ef96 100644 --- a/src/internals/tasks.rs +++ b/src/internals/tasks.rs @@ -2,31 +2,41 @@ mod rss; pub use rss::rss; -use tokio::task::spawn; -use poise::serenity_prelude::Context; -use std::{ - sync::{ - Arc, - atomic::{ - AtomicBool, - Ordering +use { + poise::serenity_prelude::Context, + std::{ + future::Future, + sync::{ + Arc, + atomic::{ + AtomicBool, + Ordering + } } }, - future::Future + tokio::task::spawn }; -fn task_info(name: &str, message: &str) { +fn task_info( + name: &str, + message: &str +) { println!("TaskScheduler[{name}]: {message}") } -fn task_err(name: &str, message: &str) { +fn task_err( + name: &str, + message: &str +) { eprintln!("TaskScheduler[{name}:Error]: {message}") } static TASK_RUNNING: AtomicBool = AtomicBool::new(false); -pub async fn run_task(ctx: Arc, task: F) -where +pub async fn run_task( + ctx: Arc, + task: F +) where F: Fn(Arc) -> T + Send + 'static, T: Future> + Send + 'static { diff --git a/src/internals/tasks/rss.rs b/src/internals/tasks/rss.rs index c335aca..84f9190 100644 --- a/src/internals/tasks/rss.rs +++ b/src/internals/tasks/rss.rs @@ -5,32 +5,36 @@ mod github; mod gportal; mod rust; -use crate::{ - Error, - controllers::cache::RedisController -}; -use super::{ +use { super::{ - http::HttpClient, - config::BINARY_PROPERTIES + super::{ + config::BINARY_PROPERTIES, + http::HttpClient + }, + task_err, + task_info }, - task_info, - task_err + crate::{ + Error, + controllers::cache::RedisController + } }; -use once_cell::sync::OnceCell; -use feed_rs::parser::parse; -use reqwest::Response; -use regex::Regex; -use std::sync::Arc; -use poise::serenity_prelude::{ - Context, - CreateEmbed, - Timestamp -}; -use tokio::time::{ - Duration, - interval +use { + feed_rs::parser::parse, + once_cell::sync::OnceCell, + poise::serenity_prelude::{ + Context, + CreateEmbed, + Timestamp + }, + regex::Regex, + reqwest::Response, + std::sync::Arc, + tokio::time::{ + Duration, + interval + } }; const TASK_NAME: &str = "RSS"; @@ -88,7 +92,10 @@ async fn fetch_feed(url: &str) -> Result { 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; redis.set(key, value).await.unwrap(); if let Err(y) = redis.expire(key, REDIS_EXPIRY_SECS).await { @@ -132,11 +139,11 @@ enum IncidentColorMap { impl IncidentColorMap { fn color(&self) -> u32 { match self { - Self::Update => 0xABDD9E, // Madang + Self::Update => 0xABDD9E, // Madang Self::Investigating => 0xA5CCE0, // French Pass - Self::Monitoring => 0x81CBAD, // Monte Carlo - Self::Resolved => 0x57F287, // Emerald - Self::Default => 0x81CBAD // Monte Carlo + Self::Monitoring => 0x81CBAD, // Monte Carlo + Self::Resolved => 0x57F287, // Emerald + Self::Default => 0x81CBAD // Monte Carlo } } } diff --git a/src/internals/tasks/rss/esxi.rs b/src/internals/tasks/rss/esxi.rs index 82b682e..51a2e9a 100644 --- a/src/internals/tasks/rss/esxi.rs +++ b/src/internals/tasks/rss/esxi.rs @@ -1,20 +1,24 @@ -use crate::Error; -use super::{ - super::task_err, - REDIS_EXPIRY_SECS, - get_redis, - save_to_redis, - fetch_feed, - parse, - format_href_to_discord +use { + super::{ + super::task_err, + REDIS_EXPIRY_SECS, + fetch_feed, + format_href_to_discord, + get_redis, + parse, + save_to_redis + }, + crate::Error }; -use std::io::Cursor; -use regex::Regex; -use poise::serenity_prelude::{ - CreateEmbed, - CreateEmbedAuthor, - Timestamp +use { + poise::serenity_prelude::{ + CreateEmbed, + CreateEmbedAuthor, + Timestamp + }, + regex::Regex, + std::io::Cursor }; pub async fn esxi_embed() -> Result, Error> { @@ -57,23 +61,30 @@ pub async fn esxi_embed() -> Result, Error> { Ok(None) } else { save_to_redis(rkey, &article.categories[3].term).await?; - Ok(Some(CreateEmbed::new() - .color(0x4EFBCB) - .author(CreateEmbedAuthor::new(feed.title.unwrap().content).url(home_page)) - .thumbnail(feed.logo.unwrap().uri) - .description(format!( - "{} {} for {} {} has been rolled out!\n{}", - article.categories[2].term, - article.categories[3].term, - article.categories[0].term, - article.categories[1].term, - format_href_to_discord(article.summary.unwrap().content.as_str()) - )) - .timestamp(Timestamp::from(article.updated.unwrap()))) - ) + Ok(Some( + CreateEmbed::new() + .color(0x4EFBCB) + .author(CreateEmbedAuthor::new(feed.title.unwrap().content).url(home_page)) + .thumbnail(feed.logo.unwrap().uri) + .description(format!( + "{} {} for {} {} has been rolled out!\n{}", + article.categories[2].term, + article.categories[3].term, + article.categories[0].term, + article.categories[1].term, + format_href_to_discord(article.summary.unwrap().content.as_str()) + )) + .timestamp(Timestamp::from(article.updated.unwrap())) + )) } } 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) } } diff --git a/src/internals/tasks/rss/github.rs b/src/internals/tasks/rss/github.rs index 74ee804..d5fedcb 100644 --- a/src/internals/tasks/rss/github.rs +++ b/src/internals/tasks/rss/github.rs @@ -1,22 +1,26 @@ -use crate::Error; -use super::{ - super::task_err, - REDIS_EXPIRY_SECS, - IncidentColorMap, - get_redis, - save_to_redis, - fetch_feed, - parse, - embed, - trim_old_content, - format_html_to_discord +use { + super::{ + super::task_err, + IncidentColorMap, + REDIS_EXPIRY_SECS, + embed, + fetch_feed, + format_html_to_discord, + get_redis, + parse, + save_to_redis, + trim_old_content + }, + crate::Error }; -use std::io::Cursor; -use regex::Regex; -use poise::serenity_prelude::{ - CreateEmbed, - Timestamp +use { + poise::serenity_prelude::{ + CreateEmbed, + Timestamp + }, + regex::Regex, + std::io::Cursor }; pub async fn github_embed() -> Result, Error> { @@ -47,7 +51,11 @@ pub async fn github_embed() -> Result, Error> { 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 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) { IncidentColorMap::Update.color() @@ -96,7 +104,10 @@ pub async fn github_embed() -> Result, Error> { ))) } } 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) } } diff --git a/src/internals/tasks/rss/gportal.rs b/src/internals/tasks/rss/gportal.rs index f3aa6d1..72e29c1 100644 --- a/src/internals/tasks/rss/gportal.rs +++ b/src/internals/tasks/rss/gportal.rs @@ -1,22 +1,26 @@ -use crate::Error; -use super::{ - super::task_err, - REDIS_EXPIRY_SECS, - IncidentColorMap, - get_redis, - save_to_redis, - fetch_feed, - parse, - embed, - trim_old_content, - format_html_to_discord +use { + super::{ + super::task_err, + IncidentColorMap, + REDIS_EXPIRY_SECS, + embed, + fetch_feed, + format_html_to_discord, + get_redis, + parse, + save_to_redis, + trim_old_content + }, + crate::Error }; -use std::io::Cursor; -use regex::Regex; -use poise::serenity_prelude::{ - CreateEmbed, - Timestamp +use { + poise::serenity_prelude::{ + CreateEmbed, + Timestamp + }, + regex::Regex, + std::io::Cursor }; pub async fn gportal_embed() -> Result, Error> { @@ -48,7 +52,11 @@ pub async fn gportal_embed() -> Result, Error> { 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 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) { IncidentColorMap::Update.color() @@ -99,7 +107,10 @@ pub async fn gportal_embed() -> Result, Error> { ))) } } 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) } } diff --git a/src/internals/tasks/rss/processor.rs b/src/internals/tasks/rss/processor.rs index fc47ac6..06f7197 100644 --- a/src/internals/tasks/rss/processor.rs +++ b/src/internals/tasks/rss/processor.rs @@ -1,35 +1,36 @@ use super::{ - task_err, - TASK_NAME, BINARY_PROPERTIES, - get_redis, + TASK_NAME, esxi::esxi_embed, + get_redis, github::github_embed, gportal::gportal_embed, - rust::rust_message + rust::rust_message, + task_err }; -use regex::Regex; -use tokio::time::{ - Duration, - sleep -}; -use poise::serenity_prelude::{ - Context, - ChannelId, - EditMessage, - CreateMessage, - CreateEmbed, +use { + poise::serenity_prelude::{ + ChannelId, + Context, + CreateEmbed, + CreateMessage, + EditMessage + }, + regex::Regex, + tokio::time::{ + Duration, + sleep + } }; - // This is for building up the embed with the feed data - /* std::fs::File::create("rss_name.log").unwrap(); - std::fs::write("rss_name.log", format!("{:#?}", feed))?; */ +// This is for building up the embed with the feed data +/* std::fs::File::create("rss_name.log").unwrap(); +std::fs::write("rss_name.log", format!("{:#?}", feed))?; */ // 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. - async fn process_embed( ctx: &Context, embed: Option, @@ -74,11 +75,17 @@ pub async fn feed_processor(ctx: &Context) { match esxi_embed().await { 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) => (), 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()) } } @@ -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(None) => (), 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()) } } @@ -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(None) => (), 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()) } } match rust_message().await { 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) => (), 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()) } } if !log_msgs.is_empty() { - ChannelId::new(BINARY_PROPERTIES.kon_logs).send_message( - &ctx.http, CreateMessage::new().content(log_msgs.join("\n")) - ).await.unwrap(); + ChannelId::new(BINARY_PROPERTIES.kon_logs) + .send_message(&ctx.http, CreateMessage::new().content(log_msgs.join("\n"))) + .await + .unwrap(); } } diff --git a/src/internals/tasks/rss/rust.rs b/src/internals/tasks/rss/rust.rs index 1dc75ab..f5d54f9 100644 --- a/src/internals/tasks/rss/rust.rs +++ b/src/internals/tasks/rss/rust.rs @@ -1,15 +1,19 @@ -use crate::Error; -use super::{ - task_err, - REDIS_EXPIRY_SECS, - get_redis, - save_to_redis, - fetch_feed, - parse +use { + super::{ + REDIS_EXPIRY_SECS, + fetch_feed, + get_redis, + parse, + save_to_redis, + task_err + }, + crate::Error }; -use std::io::Cursor; -use regex::Regex; +use { + regex::Regex, + std::io::Cursor +}; pub async fn rust_message() -> Result, Error> { let redis = get_redis().await; @@ -44,10 +48,17 @@ pub async fn rust_message() -> Result, Error> { Ok(None) } else { 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 { - 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) } } diff --git a/src/internals/tsclient.rs b/src/internals/tsclient.rs index 32eb10a..9290ea8 100644 --- a/src/internals/tsclient.rs +++ b/src/internals/tsclient.rs @@ -14,9 +14,7 @@ impl TSClient { pub async fn get(&self) -> Result { match self.0.connect().await { - Ok(api) => { - Ok(api) - } + Ok(api) => Ok(api), Err(e) => Err(e) } } diff --git a/src/internals/utils.rs b/src/internals/utils.rs index 710cb84..228d010 100644 --- a/src/internals/utils.rs +++ b/src/internals/utils.rs @@ -1,8 +1,10 @@ -use poise::serenity_prelude::UserId; -use std::sync::LazyLock; -use tokio::sync::Mutex; -use tokenservice_client::TokenServiceApi; -use super::tsclient::TSClient; +use { + super::tsclient::TSClient, + poise::serenity_prelude::UserId, + std::sync::LazyLock, + tokenservice_client::TokenServiceApi, + tokio::sync::Mutex +}; pub static BOT_VERSION: LazyLock = LazyLock::new(|| { let cargo_version = cargo_toml::Manifest::from_str(include_str!("../../Cargo.toml")) @@ -16,9 +18,7 @@ pub static BOT_VERSION: LazyLock = LazyLock::new(|| { static TSCLIENT: LazyLock> = LazyLock::new(|| Mutex::new(TSClient::new())); -pub async fn token_path() -> TokenServiceApi { - TSCLIENT.lock().await.get().await.unwrap() -} +pub async fn token_path() -> TokenServiceApi { TSCLIENT.lock().await.get().await.unwrap() } pub fn mention_dev(ctx: poise::Context<'_, (), crate::Error>) -> Option { let devs = super::config::BINARY_PROPERTIES.developers.clone(); @@ -32,11 +32,7 @@ pub fn mention_dev(ctx: poise::Context<'_, (), crate::Error>) -> Option } } - if mentions.is_empty() { - None - } else { - Some(mentions.join(", ")) - } + if mentions.is_empty() { None } else { Some(mentions.join(", ")) } } pub fn format_duration(secs: u64) -> String { diff --git a/src/main.rs b/src/main.rs index e325f2c..f4b98fe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,35 +5,37 @@ mod internals; // Using the new filesystem hierarchy use crate::internals::{ + config::BINARY_PROPERTIES, + tasks::{ + rss, + run_task + }, utils::{ BOT_VERSION, - token_path, - mention_dev - }, - tasks::{ - run_task, - rss - }, - config::BINARY_PROPERTIES + mention_dev, + token_path + } }; -use std::{ - sync::Arc, - borrow::Cow, - thread::current -}; -use poise::serenity_prelude::{ - builder::{ - CreateMessage, - CreateEmbed, - CreateEmbedAuthor +use { + poise::serenity_prelude::{ + ChannelId, + ClientBuilder, + Context, + FullEvent, + GatewayIntents, + Ready, + builder::{ + CreateEmbed, + CreateEmbedAuthor, + CreateMessage + } }, - Ready, - Context, - FullEvent, - ClientBuilder, - ChannelId, - GatewayIntents + std::{ + borrow::Cow, + sync::Arc, + thread::current + } }; type Error = Box; @@ -67,7 +69,9 @@ async fn on_ready( .thumbnail(ready.user.avatar_url().unwrap_or_default()) .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(()) } @@ -104,7 +108,7 @@ async fn main() { commands::ping::ping(), commands::status::status(), commands::midi::midi_to_wav(), - commands::uptime::uptime() + commands::uptime::uptime(), ], prefix_options: poise::PrefixFrameworkOptions { prefix, @@ -114,35 +118,37 @@ async fn main() { ignore_thread_creation: true, ..Default::default() }, - pre_command: |ctx| Box::pin(async move { - let get_guild_name = match ctx.guild() { - Some(guild) => guild.name.clone(), - None => String::from("Direct Message") - }; - println!( - "Discord[{get_guild_name}]: {} ran /{}", - ctx.author().name, - ctx.command().qualified_name - ); - }), - on_error: |error| Box::pin(async move { - match error { - poise::FrameworkError::Command { error, ctx, .. } => { - println!("PoiseCommandError({}): {error}", ctx.command().qualified_name); - ctx.reply(format!( - "Encountered an error during command execution, ask {} to check console for more details!", - mention_dev(ctx).unwrap_or_default() - )).await.expect("Error sending message"); - }, - poise::FrameworkError::EventHandler { error, event, .. } => println!("PoiseEventHandlerError({}): {error}", event.snake_case_name()), - poise::FrameworkError::UnknownInteraction { interaction, .. } => println!( - "PoiseUnknownInteractionError: {} tried to execute an unknown interaction ({})", - interaction.user.name, - interaction.data.name - ), - other => println!("PoiseOtherError: {other}") - } - }), + pre_command: |ctx| { + Box::pin(async move { + let get_guild_name = match ctx.guild() { + Some(guild) => guild.name.clone(), + None => String::from("Direct Message") + }; + println!("Discord[{get_guild_name}]: {} ran /{}", ctx.author().name, ctx.command().qualified_name); + }) + }, + on_error: |error| { + Box::pin(async move { + match error { + poise::FrameworkError::Command { error, ctx, .. } => { + println!("PoiseCommandError({}): {error}", ctx.command().qualified_name); + ctx + .reply(format!( + "Encountered an error during command execution, ask {} to check console for more details!", + mention_dev(ctx).unwrap_or_default() + )) + .await + .expect("Error sending message"); + }, + poise::FrameworkError::EventHandler { error, event, .. } => println!("PoiseEventHandlerError({}): {error}", event.snake_case_name()), + poise::FrameworkError::UnknownInteraction { interaction, .. } => println!( + "PoiseUnknownInteractionError: {} tried to execute an unknown interaction ({})", + interaction.user.name, interaction.data.name + ), + other => println!("PoiseOtherError: {other}") + } + }) + }, initialize_owners: true, event_handler: |framework, event| Box::pin(event_processor(framework, event)), ..Default::default() @@ -152,12 +158,11 @@ async fn main() { let mut client = ClientBuilder::new( token_path().await.main, - GatewayIntents::GUILDS - | GatewayIntents::GUILD_MESSAGES - | GatewayIntents::MESSAGE_CONTENT + GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT ) .framework(framework) - .await.expect("Error creating client"); + .await + .expect("Error creating client"); if let Err(why) = client.start().await { println!("Error starting client: {why:#?}");